diff --git a/AUTONOMY.md b/AUTONOMY.md index ba66b9e5..cc3ca9b7 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -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. diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 60870eb7..e8df516a 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -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 diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 1ab7be01..b358145e 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -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) @@ -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")), } @@ -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.""" @@ -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). @@ -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) @@ -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, } diff --git a/agents/conductors/batch/_brief.py b/agents/conductors/batch/_brief.py index af5d6fa5..ff8c9793 100644 --- a/agents/conductors/batch/_brief.py +++ b/agents/conductors/batch/_brief.py @@ -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*(.*)$") @@ -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] = [] @@ -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 diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index e6766807..e04573c8 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -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" @@ -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): " @@ -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": @@ -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 @@ -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"), @@ -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)] @@ -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]) @@ -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:`, " @@ -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") diff --git a/agents/conductors/batch/_mind_writer.py b/agents/conductors/batch/_mind_writer.py index 4047ab0d..dd51757e 100644 --- a/agents/conductors/batch/_mind_writer.py +++ b/agents/conductors/batch/_mind_writer.py @@ -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") @@ -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. diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 18192015..3ce6c723 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -65,6 +65,10 @@ UNLISTED_READS_FOR_CRASH = 2 #: A task's lease may be re-dispatched after a crash this many times a shift. REDISPATCH_LIMIT = 1 +#: Sessions a re-dispatch may start beyond the brief's `max-sessions:` +#: (PyAutoBrain#637, item 1) — so a backlog dip can never use up the session +#: a killed worker's task needs. The shift's sessions stay under max + this. +REDISPATCH_SESSIONS = 1 #: A real worker `blocked` (waiting on a human) this long is parked: its lease #: stays (state `parked`, holding no worker slot) so a late `.done` is still #: read, the task is not re-dispatched, and the digest names it. @@ -79,6 +83,9 @@ #: fresh, independent session that runs the witness itself is the leg. CLOSEOUT_MODEL = "opus" STAGE2_HEADING = "## Unattended `glance` sub-window (stage 2)" +#: A merged close-out that did not say what became of the task's worktree. +CLEANUP_UNREPORTED = ("not reported by the close-out — check for a worktree left " + "behind (`worktree_remove `)") STAGE2_LOG = "autonomy_log.md" #: Hooks every worker's git runs with (core.hooksPath, set through GIT_CONFIG_*): #: its pre-commit refuses a commit in PyAutoMind and chains to the repo's own. @@ -644,10 +651,94 @@ def _committed_tokens(counters: dict) -> int: return total -def default_token_reserve(budget: int | None, max_sessions: int) -> int: +def default_token_reserve(budget: int | None, max_sessions: int, + estimate: int | None = None) -> int: """The per-worker estimate held at spawn until real usage passes it: an - even share of the budget among the sessions the shift may start.""" - return budget // max(max_sessions, 1) if budget else 0 + even share of the budget among the sessions the shift may start, or the + measured spend of a finished worker when that is larger (#637, item 8). + + An even share alone never refuses a spawn before `max-sessions` does: N + reservations of budget/N fit the budget exactly. Shift B (400k, 4 + sessions) reserved 100k a worker while its workers spent ~125k, so the + session cap bound and the shift ended at 498k. With the measured figure + held instead, a budget sized below the sessions' real cost refuses the + spawn that would pass it.""" + if not budget: + return 0 + share = budget // max(max_sessions, 1) + # Never above half the budget: one outlier worker (450k in a 400k shift) + # must not refuse the first spawn (#637 review). Never below the share. + return max(share, min(int(estimate or 0), budget // 2)) + + +#: Earlier shifts whose finished workers the reservation estimate reads. +ESTIMATE_SHIFTS = 3 + + +def worker_token_estimate(slot: Path, counters: dict, budget: int | None = None, + mind: Path | None = None) -> int | None: + """The median measured spend of a worker that finished — in this shift and + the last `ESTIMATE_SHIFTS` earlier ones in this watcher's home whose + `token-budget:` is within 2x of `budget` (their `counters.json` and brief + record: local files, no network). A crashed or unmeasured session is left + out: it says nothing about a whole task's cost; so is a slot whose files + have the wrong shape. None when there is no such worker yet.""" + import statistics + home, here = Path(slot).parent, Path(slot).name + try: + earlier = sorted(d for d in home.iterdir() if d.is_dir() and d.name < here + and (d / COUNTERS_FILE).is_file()) + except OSError: + earlier = [] + if budget: + earlier = [d for d in earlier + if (b := slot_budget(d, mind)) and budget / 2 <= b <= budget * 2] + totals = [] + for c in [_safe_counters(d) for d in earlier[-ESTIMATE_SHIFTS:]] + [counters]: + try: + finished = {w.get("key") for w in c["workers"] + if "finished" in (w.get("exits") or [])} + totals += [int(u["total"]) for k, u in c["usage"].items() + if k in finished and u.get("kind") == "worker" and u.get("final") + and not u.get("unmeasured") and u.get("total")] + except (AttributeError, TypeError, ValueError, KeyError): + continue + return int(statistics.median(totals)) if totals else None + + +def slot_budget(slot: Path, mind: Path | None = None) -> int | None: + """An earlier shift's `token-budget:` — recorded in its `counters.json` + (from #637), else read from its brief record in Mind's working tree.""" + c = _safe_counters(slot) + b = c.get("token_budget") if isinstance(c, dict) else None + if isinstance(b, int) and b > 0: + return b + if mind is None: + return None + try: + brief = _brief.parse((Path(mind) / "batches" / f"{Path(slot).name}.md") + .read_text(encoding="utf-8"))["brief"] or {} + except (OSError, _brief.BriefError): + return None + return _brief._nonneg_int(brief.get("token-budget", {}).get("value", "")) or None + + +def _safe_counters(slot: Path) -> dict: + """Another slot's counters, or {} when its file has the wrong shape — a + note on stderr, never a planner crash (#637 review).""" + try: + c = read_counters(slot) + for key in ("outcomes", "usage"): + if not isinstance(c[key], dict): + raise TypeError(f"{key} is not an object") + for key in ("parked", "workers"): + if not isinstance(c[key], list): + raise TypeError(f"{key} is not a list") + return c + except (AttributeError, TypeError, ValueError, KeyError) as e: + print(f"orchestrator: {Path(slot).name}/{COUNTERS_FILE} has the wrong shape " + f"({e}) — read as no hold and no measure", file=sys.stderr) + return {} # --- locks and leases ------------------------------------------------------------ @@ -807,6 +898,15 @@ def mark(word, rec=rec): if task in counters["parked"]: counters["parked"].remove(task) mark("finished") + # A worker that merged in-turn (`notify`) ran no close-out here: + # retire its live queue.md entry as an unattended merge does + # (#637, item 11). Queued before the counters write, and a second + # retire of the same entry finds none live and is silent. + for pr in counters["outcomes"][task].get("merged") or []: + retire = queue_retire_op(counters, task, pr, now, by="the shift worker, in-turn") + if retire: + _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, retire) + break _write_counters(slot, counters) proof = lease_dir / f"{task}.proof.md" if proof.exists(): @@ -1035,9 +1135,77 @@ def git(*args): active = git("show", f"{ref}:active.md") except (OSError, subprocess.SubprocessError) as e: return {"error": f"git could not run: {e}"[:200]} - slugs = {ln[3:].strip() for ln in (active.stdout if active.returncode == 0 else "") - .splitlines() if ln.startswith("## ")} - return {"drafts": set(filter(None, tree.stdout.split("\0"))), "active": slugs} + if active.returncode != 0: + # No claims read is not "no claims" (#637 review): fail closed, as an + # unreadable `draft/` tree does — unless the ref truly has no + # active.md (a Mind with no registry claims nothing). + listed = git("ls-tree", "--name-only", ref, "--", "active.md") + if listed.returncode != 0 or listed.stdout.strip(): + return {"error": f"{ref}:active.md unreadable: " + + (active.stderr or "").strip()[:160]} + sections = claim_sections(active.stdout if active.returncode == 0 else "") + return {"drafts": set(filter(None, tree.stdout.split("\0"))), "active": set(sections), + "repos": claimed_repos(sections)} + + +#: A claim that records human-authorized sharing of its repos (#637, item 4). +_COORDINATION_RE = re.compile(r"^- (coordination|conflict-override):\s*\S", re.M) +_CLAIM_REPO_RE = re.compile(r"^\s+- ([A-Za-z0-9_.-]+)") + + +def claim_sections(active_text: str) -> dict[str, dict]: + """The `## slug` sections of an `active.md`: each one's claimed repos (its + `- repos:` block, in either schema `worktree.sh` reads) and whether it + records human-authorized coordination (`coordination:` or + `conflict-override:`).""" + out: dict[str, dict] = {} + slug, body = None, [] + + def flush(): + if slug is None: + return + repos, inside = [], False + for ln in body: + if ln.startswith("- repos:"): + inside = True + inline = ln[len("- repos:"):].strip() + repos += [x for x in re.split(r"[,\s]+", inline) if x] + continue + if inside: + m = _CLAIM_REPO_RE.match(ln) + if m: + repos.append(m.group(1)) + continue + if ln.strip(): + inside = False + out[slug] = {"repos": repos, + "coordinated": bool(_COORDINATION_RE.search("\n".join(body)))} + for ln in active_text.splitlines(): + if ln.startswith("## "): + flush() + slug, body = ln[3:].strip(), [] + elif slug is not None: + body.append(ln) + flush() + return out + + +def _repo_key(name: str) -> str: + """One spelling per repo: the survey's (`_sizing.normalise_repo`).""" + from _sizing import normalise_repo # noqa: E402 — the batch conductor's path + return normalise_repo(name) + + +def claimed_repos(sections: dict[str, dict]) -> dict[str, tuple[str, str]]: + """{repo key: (repo as written, the claiming slug)} for every claim that + does not record human-authorized coordination.""" + out: dict[str, tuple[str, str]] = {} + for slug, sec in sections.items(): + if sec["coordinated"]: + continue + for repo in sec["repos"]: + out.setdefault(_repo_key(repo), (repo, slug)) + return out def on_origin(records: list[dict], mind: Path, own: set[str], @@ -1046,7 +1214,10 @@ def on_origin(records: list[dict], mind: Path, own: set[str], 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 `## ` section in its `active.md`. A task this shift already picked - stays (its own re-dispatch). Returns (kept, {path: why}).""" + stays (its own re-dispatch). A task whose repo a claim in that + `active.md` holds is out too, unless the claim records human-authorized + coordination (PyAutoBrain#637, item 4: a named task started twice, then + parked on a repo an earlier shift's pick held). Returns (kept, {path: why}).""" claims = origin_claims(mind, fetch=fetch) if claims is None: return records, {} @@ -1061,11 +1232,58 @@ def on_origin(records: list[dict], mind: Path, own: set[str], out[r["path"]] = "not in draft/ on Mind origin/main (claimed or retired)" elif task in claims["active"]: out[r["path"]] = "claimed in active.md on Mind origin/main" + elif held := next((claims["repos"][_repo_key(x)] + for x in r.get("declared_repos") or r.get("repos") or [] + if _repo_key(x) in claims.get("repos", {})), None): + 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 parked_elsewhere(slot: Path) -> dict[str, str]: + """{task: why} for every task an earlier shift in this watcher's home left + parked on a question — a `question:` (or other push) issue in its `.done`, + or blocked on a person past the grace — and that no later shift finished + (PyAutoBrain#637, item 3: a prompt still in `draft/` with no claim was + picked again by the next shift). Read from the slots' own `counters.json`: + local files, no network.""" + out: dict[str, str] = {} + home = Path(slot).parent + try: + others = sorted(d for d in home.iterdir() + if d.is_dir() and d != Path(slot) and (d / COUNTERS_FILE).is_file()) + except OSError: + return out + for d in others: + c = _safe_counters(d) + if not c: + continue + held = dict(out) + try: + for task, o in c["outcomes"].items(): + if not isinstance(o, dict): + raise TypeError(f"outcome of {task!r} is not an object") + if o.get("questions") and "obsolete" not in o and not o.get("merged"): + held[task] = (f"parked on a question in shift {d.name} (" + + ", ".join(map(str, o["questions"])) + + ") — not startable until answered") + elif o.get("prs") or o.get("verdicts") or "obsolete" in o: + held.pop(task, None) # finished since: answered + for task in c["parked"]: + if task not in c["outcomes"]: + held[str(task)] = (f"parked in shift {d.name} (blocked on a person) — " + "not startable until answered") + except (AttributeError, TypeError, ValueError) as e: + # One malformed file holds nothing and releases nothing (#637 review). + print(f"orchestrator: {d.name}/{COUNTERS_FILE} has the wrong shape ({e}) — " + "read as no hold", file=sys.stderr) + continue + out = held + return out + + def active_leases(slot: Path) -> dict[str, dict]: """The leases that hold a worker slot: a parked worker's does not.""" return {t: l for t, l in leases(slot).items() if l.get("state") != "parked"} @@ -1103,9 +1321,20 @@ def plan() -> dict: """The plan inside the brief, made once a tick when first needed.""" if "d" not in planned: recs = records if records is not None else _batch.survey(mind) + # Parked on a question by an earlier shift (#637, item 3): not + # startable until answered. A brief that names it again is the + # human's word that it is; a task this shift picked stays. Read + # first, so the digest gives the park as the reason. + named = {Path(t).name for t in _brief.tasks_of(brief)} + parked = parked_elsewhere(slot) + planned["parked"] = {r["path"]: parked[task_id(r["path"])] for r in recs + if task_id(r["path"]) in parked + and task_id(r["path"]) not in counters["picks"] + and Path(r["path"]).name not in named} + recs = [r for r in recs if r["path"] not in planned["parked"]] # Against Mind origin/main, not the canonical checkout nobody # pulls mid-shift (#632, F4): a draft another shift already - # claimed is never picked again. + # claimed is never picked again, nor one whose repo a claim holds. recs, claimed = on_origin(recs, mind, set(counters["picks"]), fetch=lambda: _fetch_once(mind, counters, now)) planned["claimed"] = claimed @@ -1157,7 +1386,9 @@ def known(task: str) -> bool: d = plan() counters["backlog_gates"] = {"lane_absent": sorted(d["lane_absent"]), "queue_stop": d["queue_stop"], - "origin": planned.get("claimed") or {}} + "origin": planned.get("claimed") or {}, + "parked": planned.get("parked") or {}, + "scoped_reach": sorted(d.get("scoped_reach") or [])} paused = bool(counters.get("paused")) if _brief.is_shadow(brief): proposed = [] if paused else _propose( @@ -1169,15 +1400,22 @@ def known(task: str) -> bool: "ledger": ledger} return _steered(out, commands, paused) budget = _brief._nonneg_int(brief.get("token-budget", {}).get("value", "")) + if budget: + counters["token_budget"] = budget # what a later shift's estimate compares # A real worker holds a reservation from its spawn until its measured # usage passes it, so the budget binds on the first tick (#610). A fake # (dry-shift) worker spends nothing. reserve = 0 if getattr(spawner, "real", False): reserve = token_reserve if token_reserve is not None \ - else default_token_reserve(budget, max_sessions) + else default_token_reserve(budget, max_sessions, + worker_token_estimate(slot, counters, budget, mind)) spawned, refused = [], [] - for member in [] if paused else d["members"]: + # A re-dispatch goes first (#637, item 1): a backlog dip never takes the + # worker slot a killed task is waiting for. + members = sorted(d["members"], + key=lambda m: task_id(m["path"]) not in counters["pending_redispatch"]) + for member in [] if paused else members: task = task_id(member["path"]) if task in live or task in counters["done"] or task in counters["abandoned"] \ or task in counters["parked"] or task in counters["dropped"]: @@ -1185,8 +1423,14 @@ def known(task: str) -> bool: if len(live) >= max_workers: refused.append({"task": task, "why": f"max-workers {max_workers} reached"}) continue - if counters["sessions"] >= max_sessions: - refused.append({"task": task, "why": f"max-sessions {max_sessions} reached"}) + # A re-dispatch may pass `max-sessions` by REDISPATCH_SESSIONS (#637, + # item 1): after early dips used every session, a killed worker + # stayed "awaiting re-dispatch" to the end of shift A. + redo = task in counters["pending_redispatch"] + limit = max_sessions + (REDISPATCH_SESSIONS if redo else 0) + if counters["sessions"] >= limit: + refused.append({"task": task, "why": f"max-sessions {max_sessions} reached" + + (f" (+{REDISPATCH_SESSIONS} for a re-dispatch)" if redo else "")}) continue if counters["usage_unavailable"]: # Never counted as 0: a spend the watcher cannot read could be @@ -2227,16 +2471,17 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti review_at) -def queue_retire_op(counters: dict, task: str, pr: str, now: _dt.datetime) -> dict | None: +def queue_retire_op(counters: dict, task: str, pr: str, now: _dt.datetime, + by: str = "the unattended close-out") -> dict | None: """The ledger op that retires a merged task's live `queue.md` entry — what `lifecycle.py close` does and an unattended close-out skipped once - (PyAutoBrain#634). None when the pick recorded no prompt.""" + (PyAutoBrain#634), as did an in-turn merge (#637). None when the pick + recorded no prompt.""" prompt = (counters.get("picks", {}).get(task) or {}).get("prompt") or "" if not prompt: return None return {"op": "queue-retire", "path": "queue.md", "prompt": Path(prompt).name, - "shipped_as": f"{pr} (merged by the unattended close-out, " - f"{now.strftime('%Y-%m-%d')})"} + "shipped_as": f"{pr} (merged by {by}, {now.strftime('%Y-%m-%d')})"} def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_state, @@ -2320,6 +2565,10 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta model = CLOSEOUT_MODEL co.update(state="merged", gate=gate, model=model) co.pop("why", None) + # What became of the task's worktree and local branch (#637, item + # 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"]: diff --git a/agents/conductors/batch/closeout_template.md b/agents/conductors/batch/closeout_template.md index 194f8be3..f35ce14c 100644 --- a/agents/conductors/batch/closeout_template.md +++ b/agents/conductors/batch/closeout_template.md @@ -53,14 +53,22 @@ 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. -7. End at your deliverable. Never arm anything that outlives your turn. +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 + claim release queued in {ledger_dir}/ — then `git -C branch -d + feature/` for a local branch left in a canonical checkout. Never + `PYAUTO_WT_FORCE=1`, never `rm -rf`: a dirty tree or any other refusal + stays, and you say why in the verdict's `cleanup` field. +8. End at your deliverable. Never arm anything that outlives your turn. Last, write {lease_dir}/{task}.closeout as one JSON object: {{"result": "merged" | "refused", "pr": "{pr_url}", "why": "", "gate": "tests …/witness …/review …/heart …", - "model": ""}} + "model": "", + "cleanup": ""}} Without that file the watcher records the close-out as ended without a verdict and never retries it. diff --git a/agents/conductors/batch/worker_template.md b/agents/conductors/batch/worker_template.md index 3477e0c3..15380c72 100644 --- a/agents/conductors/batch/worker_template.md +++ b/agents/conductors/batch/worker_template.md @@ -53,6 +53,10 @@ The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"): change with `{shift_ledger} append|write|move|remove|drop-section ...` (ops land in {ledger_dir}/) and the orchestrator commits them. This covers your `active.md` claim, the `draft/ → active/` move and your close-out. + In your `active.md` row, each PR is its own `- library-pr: ` (library + or organ repo) or `- workspace-pr: ` line (PyAutoMind REFERENCE.md + "The PR keys"). Never a bare `pr:`: the ledger refuses it, and `/prm` + could not find the PR. - When you finish, write {lease_dir}/{task}.proof.md first: one proof packet in the format of PyAutoMind/batches/AGENTS.md "Proof packet", headed `#### {task} — `, with the Witness: output trimmed to the lines that diff --git a/bin/worktree.sh b/bin/worktree.sh index e091bcd9..9d28fe3c 100644 --- a/bin/worktree.sh +++ b/bin/worktree.sh @@ -304,11 +304,30 @@ worktree_add_repo() { # the next one, and the completion record went unwritten). # Fail-open by design: anything unknown (no active.md, unfetched origin/main, # squash-merged branch) returns 1 = "not stale" and the caller proceeds. +# A shift session (PYAUTO_SHIFT_LEDGER_DIR set) never commits to PyAutoMind: +# it queues its claim release as a `drop-section active.md ` op, which +# the shift's one Mind writer commits, and nobody pulls the canonical +# checkout mid-shift. A release queued (or already committed) in that ledger +# is a released claim (PyAutoBrain#637, item 10). Only the guard's question +# changes: the dirty-repo refusal in worktree_remove still applies. +_worktree_release_queued() { + local task="$1" ledger="${PYAUTO_SHIFT_LEDGER_DIR:-}" f + [[ -n "$ledger" && -d "$ledger" ]] || return 1 + for f in "$ledger"/*.json "$ledger"/committed/*.json; do + [[ -f "$f" ]] || continue + grep -Eq '"op": *"drop-section"' "$f" || continue + grep -Eq '"path": *"active\.md"' "$f" || continue + grep -Fq "\"section\": \"${task}\"" "$f" && return 0 + done + return 1 +} + worktree_claim_is_stale() { local task="$1" root="$2" local active="$(pyauto_repo_path PyAutoMind "$PYAUTO_MAIN")/active.md" [[ -f "$active" ]] || return 1 grep -Eq "^## ${task}([[:space:]]|\$)" "$active" || return 1 + _worktree_release_queued "$task" && return 1 local entry head saw_merged=0 for entry in "$root"/*; do diff --git a/tests/test_m31_live_shift_findings.py b/tests/test_m31_live_shift_findings.py new file mode 100644 index 00000000..cc83d69f --- /dev/null +++ b/tests/test_m31_live_shift_findings.py @@ -0,0 +1,481 @@ +"""PyAutoBrain#637: fixes from the M3.1 live shifts of 2026-11-14 (pm2 + pm3). + +One offline test per item; each fails on 421ef0f. + +1. A killed worker is re-dispatched even when dips used every session (+1). +2. Killed and never re-dispatched reads as crashed, with the reason. +3. A task an earlier shift parked on a question is not picked again. +4. A task whose repo a claim on Mind origin/main holds is skipped. +5. A review-minutes-actual pushed through a linked worktree counts at once. +6. `backlog: scoped` reaches beyond queue.md only for small single-repo tasks. +7. A shift never dips a draft targeting Brain, Mind or Hands. +8. The token reservation holds a finished worker's measured spend. +9. A bare `pr:` key in an active.md row is refused. +10. A merged close-out removes the worktree or says why not. +11. An in-turn merge retires the task's queue.md entry. +""" + +from __future__ import annotations + +import datetime as _dt +import json +import shutil +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "tests")) +import test_orchestrator_dispatch as d # noqa: E402 — the real-spawner fixtures +import test_worktree_claim_guard as g # noqa: E402 — the worktree.sh fixtures +from test_orchestrator_dispatch import _brief, _digest, orch # noqa: E402 +import _batch # noqa: E402 +import _mind_writer as mw # noqa: E402 + +NOW = d.NOW +PR = "https://github.com/example-org/repo/pull/7" +QUESTION = "https://github.com/example-org/repo/issues/9" + + +def _later(minutes): + return NOW + _dt.timedelta(minutes=minutes) + + +def git(cwd, *args): + res = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True) + assert res.returncode == 0, (args, res.stderr) + return res.stdout.strip() + + +def _commit(repo, msg): + git(repo, "add", "-A") + git(repo, "-c", "user.name=T", "-c", "user.email=t@example.invalid", "commit", "-q", + "-m", msg) + + +PROMPT = """\ +# {name} + +Type: docs +Target: {target} +Repos: +{repos} +Difficulty: {size} +Autonomy: safe +Priority: normal +Status: draft +Consequence: notify +Witness: a unit test +Review-minutes: 3 +Unattended: ready +Lane: any + +Body. +""" + +SHIFT = """\ +# Batch 2026-11-04 am +- dispatched: 2026-11-04T08:30Z +- review-at: 2026-11-04T11:30Z +- brief: + - goals: + - 1. a shift + - tasks: +{tasks} + - backlog: {backlog} +{scoped} - review-minutes: 45 + - lanes: any local-dev + - merge-cap: 0 + - token-budget: {budget} + - max-workers: {workers} + - max-sessions: {sessions} +""" + + +def _write(mind: Path, name: str, *, target="PyAutoHeart", repos=("PyAutoHeart",), + size="small", folder="draft/docs/x") -> str: + f = mind / folder / f"{name}.md" + f.parent.mkdir(parents=True, exist_ok=True) + f.write_text(PROMPT.format(name=name, target=target, size=size, + repos="\n".join(f"- {r}" for r in repos))) + return f"{folder}/{name}.md" + + +def _shift(tmp_path, named=(), *, backlog="none", scoped="", queue=("draft/docs/x/elsewhere.md",), + budget=100000, workers=2, sessions=6, name="shift.md"): + mind = tmp_path / "mind" + mind.mkdir(exist_ok=True) + (mind / "queue.md").write_text( + "# Queue\n\n" + "".join(f"## {i}. q\n- kind: prompt\n- ref: {q}\n\n" + for i, q in enumerate(queue, 1))) + tasks = "\n".join(f" - {t}" for t in named) or " - draft/docs/x/none.md" + brief = tmp_path / name + brief.write_text(SHIFT.format(tasks=tasks, backlog=backlog, scoped=scoped, budget=budget, + workers=workers, sessions=sessions)) + return mind, brief, tmp_path / "home" + + +def _rec(mind, path): + return _batch.grade(mind / path, mind) | {"epic": "", "phase": float("inf"), + "done": False, "themes": [], "title": path, + "looks_shipped": False} + + +# --- 1. the re-dispatch reserve --------------------------------------------------- + +def test_1_a_killed_worker_is_redispatched_after_dips_used_every_session(tmp_path): + mind, brief, home = d._shift(tmp_path, names=("t1", "t2", "t3"), + extra=" - max-workers: 2\n - max-sessions: 2\n") + slot = orch.slot_dir(brief, home) + claude = d.FakeClaude() + r = d._tick(brief, mind, home, NOW, claude) + assert [s["task"] for s in r["spawned"]] == ["t1", "t2"] # every session used + # The human kills t1's worker: the same tick re-dispatches it, one past the cap. + r = d._tick(brief, mind, home, _later(30), claude, + agents=d._agents({"t1": "stopped", "t2": "working"}, slot)) + assert [s["task"] for s in r["spawned"]] == ["t1"], r + c = orch.read_counters(slot) + assert c["redispatched"] == {"t1": 1} and c["sessions"] == 3 + assert c["pending_redispatch"] == [] + # Never a fresh pick past the cap: t3 waits on max-workers, then on max-sessions. + r = d._tick(brief, mind, home, _later(60), claude, + agents=d._agents({"t1": "done", "t2": "done"}, slot)) + assert r["spawned"] == [] + assert {"task": "t3", "why": "max-sessions 2 reached"} in r["refused"] + + +# --- 2. killed, never re-dispatched ------------------------------------------------ + +def test_2_killed_and_not_redispatched_reads_as_crashed_with_the_reason(): + counters = {"picks": {"t1": {"title": "One", "prompt": "draft/x/t1.md"}}, + "outcomes": {}, "pending_redispatch": ["t1"], + "refusals": [{"task": "t1", "class": "max-sessions 4 reached", "count": 9, + "at": "2026-11-14T18:00:00Z", "last": "2026-11-14T19:30:00Z", + "why": "max-sessions 4 reached"}]} + line = _digest._line("t1", counters, "notify", lambda u: "?") + assert line.startswith("- **Crashed — not re-dispatched** — One"), line + assert "Not started" not in line + state, _ = _digest.task_state("t1", counters, lambda u: "?") + assert state.startswith(_digest.NOT_REDISPATCHED) + assert "max-sessions 4 reached" in state and "2026-11-14T19:30:00Z" in state + # With no refusal on record, review-at came first. + counters["refusals"] = [] + assert "review-at" in _digest.task_state("t1", counters, lambda u: "?")[0] + + +# --- 3. a parked task is not picked again ------------------------------------------ + +def _earlier_slot(home: Path, counters: dict, name="2026-11-04-aa") -> Path: + slot = home / name + slot.mkdir(parents=True) + (slot / orch.COUNTERS_FILE).write_text(json.dumps(counters)) + return slot + + +def test_3_a_task_parked_on_a_question_by_an_earlier_shift_is_not_picked(tmp_path): + mind = tmp_path / "mind" + p1, p2 = _write(mind, "p1"), _write(mind, "p2") + _, brief, home = _shift(tmp_path, backlog="fill-idle") + _earlier_slot(home, {"outcomes": {"p1": {"prs": [], "merged": [], "issues": [QUESTION], + "questions": [QUESTION]}}}) + slot = orch.slot_dir(brief, home) + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert [s["task"] for s in r["spawned"]] == ["p2"], r + gates = orch.read_counters(slot)["backlog_gates"] + assert p1 in gates["parked"] and "until answered" in gates["parked"][p1] + assert any("Parked on a question" in ln for ln in _digest.backlog_gate_lines( + orch.read_counters(slot))) + assert p2 not in gates["parked"] + # Once a later shift finished it (answered), it is startable again. + _earlier_slot(home, {"outcomes": {"p1": {"prs": [PR], "merged": [], "issues": []}}}, + name="2026-11-04-ab") + assert orch.parked_elsewhere(slot) == {} + + +def test_3_a_malformed_earlier_counters_file_is_no_hold_and_never_a_crash(tmp_path, capsys): + home = tmp_path / "home" + _earlier_slot(home, {"outcomes": {"t": None}}, name="2026-11-04-aa") + _earlier_slot(home, {"outcomes": {"p1": {"questions": [QUESTION]}}}, name="2026-11-04-ab") + for name, body in (("2026-11-04-ac", []), ("2026-11-04-ad", {"parked": "p2"})): + (home / name).mkdir() + (home / name / orch.COUNTERS_FILE).write_text(json.dumps(body)) + slot = home / "shift" + held = orch.parked_elsewhere(slot) + assert list(held) == ["p1"] # the good file still holds + err = capsys.readouterr().err + assert "2026-11-04-aa/counters.json has the wrong shape" in err + assert "2026-11-04-ac" in err and "2026-11-04-ad" in err + assert orch.worker_token_estimate(slot, orch.read_counters(slot), 1000) is None + + +# --- 4. repo claims across shifts --------------------------------------------------- + +def test_4_a_task_on_a_repo_claimed_on_origin_is_skipped_unless_coordinated(tmp_path): + 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)) + paths = [_write(mind, n, repos=(r,)) for n, r in + (("a1", "PyAutoEyes"), ("a2", "PyAutoPulse"), ("a3", "PyAutoCortex"))] + (mind / "active.md").write_text( + "# Active\n\n## earlier-pick\n- status: workspace-dev\n- repos:\n" + " - PyAutoEyes: feature/earlier-pick\n- prompt: active/z.md\n\n" + "## shared-claim\n- repos:\n - PyAutoPulse (feature/shared)\n" + "- coordination: human approved sharing this repo\n") + _commit(mind, "seed") + git(mind, "push", "-q", "origin", "HEAD:main") + git(mind, "fetch", "-q", "origin") + records = [{k: _rec(mind, p)[k] for k in ("path", "repos", "declared_repos")} + for p in paths] + kept, out = orch.on_origin(records, mind, own=set()) + assert [r["path"] for r in kept] == [paths[1], paths[2]] + assert out == {paths[0]: "repo PyAutoEyes claimed by `earlier-pick` in active.md on " + "Mind origin/main"} + # This shift's own pick stays (its re-dispatch). + kept, mine = orch.on_origin(records, mind, own={"a1"}) + assert len(kept) == 3 and mine == {} + # A named task the gate kept out says why, never a bare "Not started". + state, _ = _digest.task_state("a1", {"backlog_gates": {"origin": out}}, lambda u: "?") + assert state == "not started — skipped: " + out[paths[0]] + # A repo only mentioned in passing is not a declared one: never a skip. + mentioned = _write(mind, "a4", repos=("PyAutoCortex",)) + (mind / mentioned).write_text((mind / mentioned).read_text() + "\nSee @PyAutoEyes.\n") + rec = _rec(mind, mentioned) + assert "pyautoeyes" in rec["repos"] and "pyautoeyes" not in rec["declared_repos"] + # An active.md on origin that cannot be read fails closed: no claim + # check, no pick (its blob is lost from the local object store). + blob = git(mind, "rev-parse", "origin/main:active.md") + (mind / ".git" / "objects" / blob[:2] / blob[2:]).unlink() + kept, closed = orch.on_origin(records, mind, own={"a2"}) + assert [r["path"] for r in kept] == [paths[1]] # only this shift's own pick + assert closed[paths[0]].startswith("Mind origin/main:active.md unreadable") + assert closed[paths[0]].endswith("fail closed") + line = _digest.backlog_gate_lines({"backlog_gates": {"origin": { + paths[0]: "repo PyAutoEyes claimed by `earlier-pick` in active.md on Mind origin/main"}}}) + assert any(ln.startswith("Repo claimed on Mind origin/main: 1") for ln in line) + + +# --- 5. the calibration gate reads the pushed record -------------------------------- + +def test_5_minutes_pushed_through_a_linked_worktree_count_on_the_next_tick(tmp_path): + 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)) + (mind / "batches").mkdir() + prev = "# Batch 2026-11-04 aa\n- dispatched: 2026-11-04T06:00Z\n- review-at: 2026-11-04T08:00Z\n" + (mind / "batches" / "2026-11-04-aa.md").write_text(prev) + _commit(mind, "shift A") + git(mind, "push", "-q", "origin", "HEAD:main") + # The check-in: the lead pushes the minutes from a linked worktree; the + # canonical working tree is not fast-forwarded. + wt = tmp_path / "wt" + git(mind, "worktree", "add", "-q", "--detach", str(wt), "origin/main") + (wt / "batches" / "2026-11-04-aa.md").write_text( + prev + "- review-minutes-actual: 5\n") + _commit(wt, "check-in") + git(wt, "push", "-q", "origin", "HEAD:main") + assert "review-minutes-actual" not in (mind / "batches" / "2026-11-04-aa.md").read_text() + brief = mind / "batches" / "2026-11-04-ab.md" + brief.write_text(SHIFT.format(tasks=" - draft/docs/x/none.md", backlog="none", scoped="", + budget=1000, workers=1, sessions=1) + .replace("2026-11-04T08:30Z", "2026-11-04T09:00Z")) + errors = _brief.check(brief, mind)["errors"] + assert not [e for e in errors if "review-minutes-actual" in e], errors + # And a record that is measured nowhere still refuses. + (mind / "batches" / "2026-11-04-a0.md").write_text(prev) + brief2 = mind / "batches" / "2026-11-04-a1.md" + brief2.write_text(brief.read_text()) + assert any("review-minutes-actual: missing on the previous record 2026-11-04-a0.md" in e + for e in _brief.check(brief2, mind)["errors"]) + + +# --- 6. backlog reach: queue first, then small single-repo --------------------------- + +def test_6_a_scoped_dip_beyond_the_queue_takes_only_small_single_repo_tasks(tmp_path): + mind = tmp_path / "mind" + queued = _write(mind, "queued_medium", size="medium", repos=("PyAutoHeart", "PyAutoEyes")) + small = _write(mind, "small_single") + medium = _write(mind, "medium_single", size="medium") + multi = _write(mind, "small_multi", repos=("PyAutoHeart", "PyAutoEyes")) + _, brief_path, _ = _shift(tmp_path, backlog="scoped", scoped=" - scoped:\n - tiers: notify\n", + queue=(queued,)) + brief = _brief.parse(brief_path.read_text())["brief"] + records = [_rec(mind, p) for p in (queued, small, medium, multi)] + d_ = _batch.plan(records, session_lane="local-dev", brief=brief, + queue=_batch.read_queue(mind)) + assert sorted(m["path"] for m in d_["members"]) == sorted([queued, small]) + why = dict(d_["rejected"]) + assert "medium, 1 repo(s)" in why[medium] and "ruling 2026-11-16" in why[medium] + assert "small, 2 repo(s)" in why[multi] + assert sorted(d_["scoped_reach"]) == sorted([medium, multi]) + # The ruling is recorded once in the doctrine. + doctrine = (BRAIN / "AUTONOMY.md").read_text() + assert doctrine.count("Human ruling 2026-11-16 (backlog reach, PyAutoBrain#637)") == 1 + + +# --- 7. organ targets are never dipped ------------------------------------------------ + +def test_7_a_shift_never_dips_a_draft_targeting_its_own_organs(tmp_path): + mind = tmp_path / "mind" + brain = _write(mind, "brain_fix", target="PyAutoBrain", repos=("PyAutoBrain",)) + minds = _write(mind, "mind_fix", target="PyAutoMind", repos=("PyAutoMind",)) + hands = _write(mind, "hands_fix", target="PyAutoHands", repos=("PyAutoHands",)) + heart = _write(mind, "heart_fix") + named = _write(mind, "named_brain", target="PyAutoBrain", repos=("PyAutoBrain",)) + _, brief_path, _ = _shift(tmp_path, named=(named,), backlog="fill-idle") + brief = _brief.parse(brief_path.read_text())["brief"] + records = [_rec(mind, p) for p in (brain, minds, hands, heart, named)] + d_ = _batch.plan(records, session_lane="local-dev", brief=brief, + queue=_batch.read_queue(mind)) + assert sorted(m["path"] for m in d_["members"]) == sorted([heart, named]) + why = dict(d_["rejected"]) + for p, organ in ((brain, "PyAutoBrain"), (minds, "PyAutoMind"), (hands, "PyAutoHands")): + assert why[p] == (f"targets {organ} — a shift never changes its own watcher, " + "writer or release path") + + +# --- 8. the token cap binds before the session cap when sized to --------------------- + +def test_8_the_reservation_holds_a_finished_workers_measured_spend(tmp_path): + names = ("t1", "t2", "t3", "t4") + mind, brief, home = d._shift(tmp_path, names=names, budget=400000, + extra=" - max-workers: 4\n - max-sessions: 4\n") + # The shift before: two workers finished at ~125k each (shift B's measure). + _earlier_slot(home, { + "token_budget": 400000, + "usage": {"w1": {"kind": "worker", "total": 125000, "final": True}, + "w2": {"kind": "worker", "total": 126000, "final": True}, + "w3": {"kind": "worker", "total": 4000, "final": True}}, # killed early + "workers": [{"key": "w1", "exits": ["spawned", "finished"]}, + {"key": "w2", "exits": ["spawned", "finished"]}, + {"key": "w3", "exits": ["spawned", "crashed"]}]}) + slot = orch.slot_dir(brief, home) + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert [s["task"] for s in r["spawned"]] == ["t1", "t2", "t3"] + assert r["refused"] == [{"task": "t4", "why": "token-budget 400000: 376500 committed + " + "125500 reserved per worker"}] + assert orch.worker_token_estimate(slot, orch.read_counters(slot)) == 125500 + # No measure yet: the even share, as before. + assert orch.default_token_reserve(400000, 4) == 100000 + assert orch.default_token_reserve(400000, 4, 90000) == 100000 + + +def test_8_one_outlier_worker_never_refuses_the_first_spawn(tmp_path): + """Review of 1ae5d5f: one past worker at 450k in a 400k shift must not + make the reservation 450k. Clamped to half the budget, the median of + comparable shifts only (a 2M shift's workers are not counted).""" + names = ("t1", "t2", "t3") + mind, brief, home = d._shift(tmp_path, names=names, budget=400000, + extra=" - max-workers: 4\n - max-sessions: 4\n") + _earlier_slot(home, {"token_budget": 400000, + "usage": {"w1": {"kind": "worker", "total": 450000, "final": True}}, + "workers": [{"key": "w1", "exits": ["spawned", "finished"]}]}) + _earlier_slot(home, {"token_budget": 2000000, # not comparable: never read + "usage": {"w9": {"kind": "worker", "total": 10, "final": True}}, + "workers": [{"key": "w9", "exits": ["spawned", "finished"]}]}, + name="2026-11-04-ab") + slot = orch.slot_dir(brief, home) + assert orch.worker_token_estimate(slot, orch.read_counters(slot), 400000) == 450000 + assert orch.default_token_reserve(400000, 4, 450000) == 200000 + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert [s["task"] for s in r["spawned"]] == ["t1", "t2"] + assert r["refused"] == [{"task": "t3", "why": "token-budget 400000: 400000 committed + " + "200000 reserved per worker"}] + assert orch.read_counters(slot)["token_budget"] == 400000 + # The median, not the mean: one outlier among three does not move it. + _earlier_slot(home, {"token_budget": 400000, + "usage": {k: {"kind": "worker", "total": 100000, "final": True} + for k in ("a", "b")}, + "workers": [{"key": k, "exits": ["finished"]} for k in ("a", "b")]}, + name="2026-11-04-ac") + assert orch.worker_token_estimate(slot, orch.read_counters(slot), 400000) == 100000 + + +# --- 9. PR keys ------------------------------------------------------------------------- + +def test_9_a_bare_pr_key_in_an_active_md_row_is_refused(): + lm = SimpleNamespace(is_ledger_path=lambda p: True, ENTRY_MERGED_FILES=("active.md",)) + bad = {"op": "append", "path": "active.md", + "text": f"\n## t1\n- status: awaiting-merge\n- pr: {PR}\n"} + errs = mw.validate_op(bad, lm) + assert errs and "`pr:`" in errs[0] and "library-pr:" in errs[0] + good = dict(bad, text=f"\n## t1\n- status: awaiting-merge\n- workspace-pr: {PR}\n" + f"- library-pr: {PR}\n- pending-release: x@{PR}\n- prompt: active/t1.md\n") + assert mw.validate_op(good, lm) == [] + # The worker is told the keys up front. + prompt = orch.worker_prompt("t1", "draft/x/t1.md", Path("b.md"), Path("leases")) + assert "- library-pr: " in prompt and "bare `pr:`" in prompt + + +# --- 10. worktree clean-up after an unattended merge ------------------------------------ + +def test_10_the_stale_claim_guard_counts_a_release_queued_in_the_shift_ledger(tmp_path): + main = tmp_path / "main" + (main / "PyAutoMind").mkdir(parents=True) + (main / "PyAutoMind" / "active.md").write_text(g.CLAIMED) # stale canonical claim + wt_root = tmp_path / "wt" / "task-x" + wt_root.mkdir(parents=True) + g._repo_with_branch(wt_root, merged=True) + ledger = tmp_path / "ledger" + + def stale(): + return subprocess.run( + ["bash", "-c", f'source "{g.WORKTREE_SH}"; worktree_claim_is_stale task-x "{wt_root}"'], + env={"PATH": "/usr/bin:/bin", "HOME": str(tmp_path), "PYAUTO_MAIN": str(main), + "PYAUTO_WT_ROOT": str(tmp_path / "wt"), "PYAUTO_SHIFT_LEDGER_DIR": str(ledger)}, + capture_output=True).returncode + assert stale() == 0 # nothing queued: refuse + mw.queue_op(ledger, {"op": "drop-section", "path": "active.md", "section": "task-x-2"}) + assert stale() == 0 # another task's release + mw.queue_op(ledger, {"op": "drop-section", "path": "active.md", "section": "task-x"}) + assert stale() == 1 # its own release: removable + + +def test_10_a_merged_closeouts_worktree_cleanup_is_in_the_digest(tmp_path): + slot = tmp_path / "home" / "shift" + (slot / "leases").mkdir(parents=True) + counters = orch.read_counters(slot) + counters["picks"]["t1"] = {"prompt": "draft/x/t1.md", "tier": "glance", "title": "One"} + counters["outcomes"]["t1"] = {"prs": [PR], "merged": [], "issues": []} + counters["closeouts"][PR] = {"task": "t1", "state": "running", "pid": 0} + (slot / "leases" / "t1.closeout").write_text(json.dumps( + {"result": "merged", "pr": PR, "gate": "g", "model": "m", + "cleanup": "worktree kept — dirty repo: repo-a"})) + orch.reap_closeouts(slot, counters, NOW, orch.AgentsView([]), None) + assert counters["closeouts"][PR]["cleanup"] == "worktree kept — dirty repo: repo-a" + state, _ = _digest.task_state("t1", counters, lambda u: "?") + assert "worktree: worktree kept — dirty repo: repo-a" in state + # A close-out that said nothing is named too. + counters["closeouts"][PR] = {"task": "t1", "state": "running", "pid": 0} + counters["outcomes"]["t1"]["merged"] = [] + (slot / "leases" / "t1.closeout").write_text(json.dumps( + {"result": "merged", "pr": PR, "gate": "g", "model": "m"})) + orch.reap_closeouts(slot, counters, NOW, orch.AgentsView([]), None) + assert counters["closeouts"][PR]["cleanup"] == orch.CLEANUP_UNREPORTED + assert "worktree_remove" in (BRAIN / "agents" / "conductors" / "batch" + / "closeout_template.md").read_text() + + +# --- 11. an in-turn merge retires its queue.md entry ------------------------------------ + +def test_11_an_in_turn_merge_queues_the_queue_retirement(tmp_path): + slot = tmp_path / "home" / "shift" + (slot / "leases").mkdir(parents=True) + counters = orch.read_counters(slot) + counters["picks"]["t1"] = {"prompt": "draft/x/t1.md", "tier": "notify"} + (slot / "leases" / "t1.json").write_text(json.dumps( + {"task": "t1", "prompt": "draft/x/t1.md", "pid": 0, "started": orch._iso(NOW), + "expires": orch._iso(NOW)})) + (slot / "leases" / "t1.done").write_text(f"merged {PR}\n") + events = orch._reap(slot, counters, _later(5), 0, orch.AgentsView([])) + assert events == [{"task": "t1", "event": "done"}] + ops = [json.loads(f.read_text()) for f in mw.pending_ops(slot)] + assert [o["op"] for o in ops] == ["queue-retire"] + assert ops[0]["prompt"] == "t1.md" and PR in ops[0]["shipped_as"] + assert "in-turn" in ops[0]["shipped_as"] diff --git a/tests/test_orchestrator_closeout.py b/tests/test_orchestrator_closeout.py index 7ea3bc83..52e0c420 100644 --- a/tests/test_orchestrator_closeout.py +++ b/tests/test_orchestrator_closeout.py @@ -199,7 +199,7 @@ def test_a_refused_closeout_is_digested_and_never_retried(tmp_path): assert c["glance_auto_merges"] == 0 and c["outcomes"]["named"]["merged"] == [] d = _digest.build(_brief.parse(brief.read_text())["brief"], slot, c, health=t._health) assert (f"- **Needs you — not merged unattended** — [named]({PR1})\n" - " `named` · glance · small · pyautobrain · awaiting /prm — close-out refused:" + " `named` · glance · small · pyautoheart · awaiting /prm — close-out refused:" " decision-taken label") in d diff --git a/tests/test_orchestrator_digest.py b/tests/test_orchestrator_digest.py index 2497bd37..90429fc2 100644 --- a/tests/test_orchestrator_digest.py +++ b/tests/test_orchestrator_digest.py @@ -40,8 +40,8 @@ - goals: - 1. dry shift - tasks: - - draft/feature/pyautobrain/named.md - - draft/feature/pyautobrain/never.md + - draft/feature/pyautoheart/named.md + - draft/feature/pyautoheart/never.md - backlog: scoped - scoped: - epics: e1 @@ -52,13 +52,15 @@ - max-workers: 3 """ +# The fixture prompts target an organ other than Brain, Mind or Hands: a shift +# never dips those (PyAutoBrain#637, item 7), and these shifts dip `picked`. PROMPT = """\ # {name} Type: feature -Target: PyAutoBrain +Target: PyAutoHeart Repos: -- PyAutoBrain +- PyAutoHeart Difficulty: small Autonomy: supervised Priority: normal @@ -75,7 +77,7 @@ # A non-empty queue.md: an empty or absent one stops an unattended shift's # backlog dip (M2.3), and these shifts dip for `picked`. Its one entry ranks # nothing the brief admits, so every pick still reads "not in queue.md". -QUEUE = "# Queue\n\n## 1. Elsewhere\n- kind: prompt\n- ref: draft/feature/pyautobrain/outside.md\n" +QUEUE = "# Queue\n\n## 1. Elsewhere\n- kind: prompt\n- ref: draft/feature/pyautoheart/outside.md\n" PROOF = """\ #### named — https://github.com/o/r/pull/1 @@ -114,7 +116,7 @@ def session_of(self, agent_id): def _mind(root: Path) -> Path: - folder = root / "draft" / "feature" / "pyautobrain" + folder = root / "draft" / "feature" / "pyautoheart" folder.mkdir(parents=True) (folder / "named.md").write_text(PROMPT.format(name="named", epic="")) (folder / "picked.md").write_text(PROMPT.format(name="picked", epic="Epic: e1\n")) @@ -175,12 +177,12 @@ 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 · pyautobrain · merged") in work + " `named` · glance · small · pyautoheart · merged") 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. assert ("- **Still running — close-out checking it** — [picked](https://github.com/o/r/pull/2)\n" - " `picked` · glance · small · pyautobrain · close-out running" + " `picked` · glance · small · pyautoheart · close-out running" " · why: scoped epic e1 · not in queue.md") in picks assert "`named`" not in picks diff --git a/tests/test_orchestrator_shadow.py b/tests/test_orchestrator_shadow.py index a3fa8c83..a30cc157 100644 --- a/tests/test_orchestrator_shadow.py +++ b/tests/test_orchestrator_shadow.py @@ -44,9 +44,9 @@ def test_a_shadow_tick_proposes_with_reasons_and_spawns_nothing(tmp_path): slot = orch.slot_dir(brief, home) assert orch.leases(slot) == {} picks = orch.read_counters(slot)["picks"] - assert picks["named"] == {"prompt": "draft/feature/pyautobrain/named.md", + assert picks["named"] == {"prompt": "draft/feature/pyautoheart/named.md", "why": "named task", "tier": "glance", "proposed": True, - "title": "named", "size": "small", "repos": ["pyautobrain"]} + "title": "named", "size": "small", "repos": ["pyautoheart"]} assert picks["picked"]["why"].startswith("scoped epic e1 · not in queue.md") assert orch.read_counters(slot)["sessions"] == 0 @@ -72,8 +72,8 @@ def test_the_shadow_digest_lists_proposals_and_validates(tmp_path): d = _digest.build(_brief.parse(brief.read_text())["brief"], slot, orch.read_counters(slot), health=t._health) assert ("- **Proposed (shadow)** — named\n" - " `named` · glance · small · pyautobrain · proposed (shadow)") in d - assert ("- **Proposed (shadow)** — picked\n `picked` · glance · small · pyautobrain" + " `named` · glance · small · pyautoheart · proposed (shadow)") in d + assert ("- **Proposed (shadow)** — picked\n `picked` · glance · small · pyautoheart" " · proposed (shadow) · why: scoped epic e1 · not in queue.md") in d assert "- **Not started** — never" in d assert _digest.NO_PACKETS_SHADOW in d @@ -191,4 +191,4 @@ def test_batch_watch_shows_titles(tmp_path): mind, brief, home = _shadow(tmp_path) orch.tick(brief, mind, home=home, now=t.NOW, spawner=NoSpawn()) text = _watch.render(_watch.snapshot(brief, orch.slot_dir(brief, home), t.NOW, health=t._health)) - assert "- **named** (`named`; small · pyautobrain) — proposed (shadow)" in text + assert "- **named** (`named`; small · pyautoheart) — proposed (shadow)" in text diff --git a/tests/test_orchestrators_lane_brief.py b/tests/test_orchestrators_lane_brief.py index 545c9018..44bf5e51 100644 --- a/tests/test_orchestrators_lane_brief.py +++ b/tests/test_orchestrators_lane_brief.py @@ -220,7 +220,9 @@ def test_plan_under_a_brief_puts_named_tasks_first_and_never_dips_outside(): "draft/feature/autolens/example_named_task.md", "draft/named.md"))["brief"] recs = [_rec("draft/cheap.md", tier="judge", epic="other-epic"), _rec("draft/named.md", tier="judge", review_minutes=20), - _rec("draft/in_scope.md", epic="cluster-strong-lensing"), + # One repo: beyond queue.md a scoped dip is small single-repo + # only (ruling 2026-11-16, PyAutoBrain#637). + _rec("draft/in_scope.md", epic="cluster-strong-lensing", repos=["pyautoheart"]), _rec("draft/excluded.md", epic="euclid-dr1", tier="notify")] d = _batch.plan(recs, session_lane="local-dev", brief=brief) paths = [m["path"] for m in d["members"]]