diff --git a/AUTONOMY.md b/AUTONOMY.md index ea859f5..687af2a 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -817,6 +817,18 @@ digest); `brief --new` with no goal epic or tag writes `backlog: scoped` with tasks — refused when the prompt names the shift's own code (`_brief.SELF_PATHS`), passed with a line when it names only other paths, a warning when it names none. +**Shift throughput — 2026-11-17 (M3.6c, PyAutoBrain#669), approved by the +human.** The first tick of a shift closes out the newest earlier slot's late +`glance`/`notify` PRs (never closed out, or refused only by the close-out +cutoff) under the new shift's grant; a PR refused for its tier, CI or `/drop` +stays the human's. A task an answer released is admitted whatever the brief's +backlog scope, and a task parked this shift restarts this shift when answered +with more than 30 minutes left. `first: glance` in a brief starts ready +`glance` work before named `judge` tasks (spawn order; the plan's selection is +unchanged), and a released or answered task counts as the human's pick. With no `max-sessions:` and a +`token-budget:`, the session cap is `max(2 × max-workers, ceil(token-budget / +150k))`; an explicit value wins. + **Launch preflight — 2026-11-17 (M3.6a, PyAutoBrain#659), approved by the human.** A live brief (not `shadow: yes`) names its shift **`issue:`**: `batch brief --new --out` creates it on PyAutoMind and writes it, and `batch brief @@ -918,7 +930,10 @@ the exemption it runs under is `PyAutoMind/policy/shift_watcher.md`). and **one comment per shift** on the brief's `issue:` (the digest, phase 3d); and, inside "One Mind writer per shift", the writer's own `git fetch` of PyAutoMind `main` — at each commit, and once per shift before its first plan - (2026-11-14, PyAutoBrain#632). + (2026-11-14, PyAutoBrain#632); and again, at most every 10 minutes, only + while a task of the shift is parked on a question and more than 30 minutes + remain before `review-at:`, so an answer given from the phone can restart it + in-shift (human-approved 2026-11-17, M3.6c, PyAutoBrain#669). It starts worker sessions (`claude --bg`, phase 3b) — that is dispatch, ruled by "Shift briefs and unattended `glance`", not a network read. - **Opt-in and laptop-only.** It runs only from a systemd user timer the human diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index fc52448..8c02935 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -280,7 +280,10 @@ pin that and record every process a full brief run starts. `bin/orchestrator_watch.py --mind ` finds the brief and runs **one tick** of it (finding it is below, "Which brief"); `STOP` first, then the open-brief gate, the tick lock, the lease reap, the plan inside the brief, the caps (`max-workers:`, default 4; -`max-sessions:`, default 8) and an exclusive-create lease per spawn. The plan +`max-sessions:`, default `max(2 × max-workers, ceil(token-budget / 150k))` when the +brief has a `token-budget:`, else 8 — M3.6c) and an exclusive-create lease per +spawn; `first: glance` starts ready glance work before named judge tasks (spawn +order only: what the plan selects is unchanged). The plan 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 @@ -528,6 +531,16 @@ watcher's own: one `claude agents --json` per refresh, only on a live shift holding real worker leases, and `gh pr checks` for unmerged PRs, cached for the interval. +**Carry-over and in-shift restart (M3.6c, PyAutoBrain#669).** A shift's first +tick takes the newest earlier slot's late `glance`/`notify` PRs (never closed +out, or refused only for going green too near `review-at:`) into its own +close-out path under its own grant, and the digest names them ("Carried over +from …"). A task this shift parked on a question restarts this shift when the +inbox answers it with more than 30 minutes left (once per answer; a release +waits for its spawn, else the park stays for the next shift); the writer's +fetch repeats for that only while such a park is open, at most every 10 minutes. +A task an answer released is admitted whatever the brief's backlog scope. + **Late arrivals (PyAutoBrain#594).** A worker may finish after `review-at:`, once the digest is posted. A closed shift with a lease still held, a close-out still running or a ledger op still queued runs `late_sweep` on each tick: it @@ -538,7 +551,8 @@ commits the queued ops through the one Mind writer, and appends one under `### Late arrivals`, amends the pilot line in place (`amended: true`) and posts **one** correction comment for the shift (#610). It never spawns, re-dispatches or starts a close-out, because the grant ended at `review-at:` and -what arrives late waits for `/prm`. It also runs while a failed digest or +what arrives late waits for `/prm` — or for the next shift's first tick, which +carries a late `glance`/`notify` PR over (M3.6c). It also runs while a failed digest or correction post is due its retry. **A blocked worker reaches the human (PyAutoBrain#611).** The human's channel diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index ea6531e..86637e1 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -461,7 +461,8 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, 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). - backlog = Path(r["path"]).name not in named_names + # A task an answer released is the human's word too (M3.6c): no dip gate. + backlog = Path(r["path"]).name not in named_names and not r.get("resume") why = pool_gate(r, next_phase) if why: rejected.append((r["path"], why)) diff --git a/agents/conductors/batch/_brief.py b/agents/conductors/batch/_brief.py index 25e316d..4a8ccbd 100644 --- a/agents/conductors/batch/_brief.py +++ b/agents/conductors/batch/_brief.py @@ -30,6 +30,8 @@ WORKER_MODES = ("auto", "dontAsk", "acceptEdits") DEFAULT_WORKER_MODE = "auto" SCOPED_KEYS = ("epics", "tags", "tiers") +#: `first:` values (M3.6c): `glance` sorts ready glance work first. +FIRST_VALUES = ("glance",) #: 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). @@ -142,10 +144,35 @@ def excluded_of(brief: dict) -> tuple[set[str], dict[str, list[str]]]: return paths, keyed +#: Tokens one worker session is assumed to need at least, for a session cap +#: derived from the budget (M3.6c, human 2026-11-17): the cap is +#: `max(2 × max-workers, ceil(token-budget / SESSION_TOKEN_FLOOR))`, so the +#: token budget binds before the session count does. +SESSION_TOKEN_FLOOR = 150_000 + + def cap_of(brief: dict, key: str) -> int: - """A usage cap from the brief, or its default when the brief omits it.""" + """A usage cap from the brief, or its default when the brief omits it. + With no `max-sessions:`, a brief with a `token-budget:` gets a cap derived + from it and `max-workers:` (M3.6c) — the fixed 8 stopped all new starts in + shift 2026-11-16-pm with 2.3M of 5M tokens unspent.""" value = _nonneg_int(brief.get(key, {}).get("value", "")) - return CAP_DEFAULTS[key] if value is None else value + if value is not None: + return value + if key == "max-sessions": + budget = _nonneg_int(brief.get("token-budget", {}).get("value", "")) + if budget: + return max(2 * cap_of(brief, "max-workers"), -(-budget // SESSION_TOKEN_FLOOR)) + return CAP_DEFAULTS[key] + + +def cap_source(brief: dict, key: str) -> str: + """Where `cap_of` took a cap from: `brief`, `from token-budget` or `default`.""" + if _nonneg_int(brief.get(key, {}).get("value", "")) is not None: + return "brief" + if key == "max-sessions" and _nonneg_int(brief.get("token-budget", {}).get("value", "")): + return "from token-budget" + return "default" #: The caps a `/cap` steering command may lower for one shift (#644). @@ -334,6 +361,10 @@ def check(path: Path, mind: Path) -> dict: + ", ".join(WORKER_MODES) + (" (bypassPermissions is never a worker mode)" if brief["worker-mode"]["value"] == "bypassPermissions" else "")) + # `first: glance` (M3.6c): ready glance work starts before named judge tasks. + if "first" in brief and brief["first"]["value"] not in FIRST_VALUES: + errors.append(f"brief.first: {brief['first']['value'] or 'empty'} — only " + + " | ".join(FIRST_VALUES) + " (or leave the line out)") for key in ("sandbox", "shadow"): if key in brief and brief[key]["value"].lower() not in ("yes", "no"): errors.append(f"brief.{key}: {brief[key]['value']} — yes or no") @@ -601,7 +632,9 @@ def scope(records: list[dict], brief: dict) -> tuple[list[dict], list[tuple[str, or themes & set(ex_keyed.get("tags", []))): rejected.append((r["path"], "excluded by the brief")) continue - if name not in named_names: + # A task an answer released (the inbox, M3.5) is the human's word, as + # naming it would be (M3.6c): no dip policy keeps it out. + if name not in named_names and not r.get("resume"): if backlog == "none": rejected.append((r["path"], "outside the brief (backlog: none)")) continue diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 738da4a..b7cdbc7 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -716,6 +716,17 @@ def names(paths): "their old standing — " + "; ".join( f"`{t}` ({', '.join(v.get('ids') or [])} answered)" for t, v in sorted(resumed.items())[:SUMMARY_NAMES])) + carried = counters.get("carried_in") or {} + if carried.get("prs"): + out.append(f"Carried over from {carried['from']}: {len(carried['prs'])} late PR(s) " + "closed out under this shift's grant — " + ", ".join(carried["prs"][:SUMMARY_NAMES]) + + (f" +{len(carried['prs']) - SUMMARY_NAMES} more" + if len(carried["prs"]) > SUMMARY_NAMES else "")) + again = counters.get("inshift_released") or {} + if again: + out.append(f"Restarted in-shift after an answer: {len(again)} task(s) — " + + "; ".join(f"`{t}` ({', '.join(i for r in rs for i in r.get('ids') or [])})" + for t, rs in sorted(again.items())[:SUMMARY_NAMES])) bare = gates.get("witness_absent") or [] if bare: out.append(f"No Witness: {len(bare)} draft(s) not dipped — a shift dips only " diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 384c51a..b177f98 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -1275,6 +1275,149 @@ def _fetch_once(mind: Path, counters: dict, now: _dt.datetime) -> None: counters["origin_fetch"] = {"at": _iso(now), "ok": False, "error": str(e)[:200]} +_DATED_SLOT_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-") +#: An answer restarts its task this shift only with more than this left (M3.6c). +INSHIFT_RESTART_S = 30 * 60 +#: The bounded re-fetch for an in-shift answer: at most this often (M3.6c). +ANSWER_FETCH_EVERY_S = 10 * 60 + + +def _open_parks(counters: dict) -> list[str]: + """Tasks of this shift parked on a question whose answer is not yet in + hand (a release pending its spawn is not open: the answer was seen).""" + pending = counters.get("inshift_pending") or {} + return [t for t, o in (counters.get("outcomes") or {}).items() + if isinstance(o, dict) and o.get("questions") and "obsolete" not in o + and not o.get("merged") and t not in pending] + + +def _fetch_for_answers(mind: Path, counters: dict, now: _dt.datetime, + review_at: _dt.datetime | None) -> None: + """The shift's one fetch (`_fetch_once`), then — M3.6c, human-approved + 2026-11-17 (AUTONOMY.md "The watcher's network surface") — the same + writer's fetch again, only while a task of this shift is parked on a + question, more than `INSHIFT_RESTART_S` remain before `review-at:`, and at + most every `ANSWER_FETCH_EVERY_S`: an answer from the phone moves only + the remote, and the inbox is read from the local `origin/main`.""" + last = counters.get("origin_fetch") + if not last: + _fetch_once(mind, counters, now) + return + if not _open_parks(counters) or review_at is None \ + or (review_at - now).total_seconds() <= INSHIFT_RESTART_S: + return + at = _parse_iso(last.get("at") or "") if last.get("at") else None + if at is not None and (now - at).total_seconds() < ANSWER_FETCH_EVERY_S: + return + try: + _mind_writer.fetch(mind) + counters["origin_fetch"] = {"at": _iso(now), "ok": True} + except _mind_writer.MindWriteError as e: + counters["origin_fetch"] = {"at": _iso(now), "ok": False, "error": str(e)[:200]} + counters["answer_fetches"] = int(counters.get("answer_fetches") or 0) + 1 + + +def released_here(slot: Path, counters: dict, inbox: dict | None, now: _dt.datetime, + review_at: _dt.datetime | None) -> dict[str, dict]: + """{task: release} for each task THIS shift parked on a question that the + inbox has answered, while more than `INSHIFT_RESTART_S` remain (M3.6c): + the task restarts this shift instead of the next. + + Idempotent and durable (M3.6c review): the release is held in + `inshift_pending` and returned on every tick until the task actually + spawns (`_spawned_release` then uses it up); the parked outcome stays put + meanwhile, so a release that never spawns — a full cap, a pause, the + clock — still leaves the park for the next shift's `parked_elsewhere`. + Once per answer: ids already used to restart the task never release it + again; a new question answered later does.""" + pending = counters.setdefault("inshift_pending", {}) + if review_at is None or (review_at - now).total_seconds() <= INSHIFT_RESTART_S: + pending.clear() + return {} + used = counters.get("inshift_released") or {} + if inbox is not None: + # A pending release the human reopened or dropped since is withdrawn. + for task in list(pending): + if _questions.hold_for(task, Path(slot).name, inbox)[0] != "answered": + pending.pop(task) + for task in _open_parks(counters): + rule, info = _questions.hold_for(task, Path(slot).name, inbox) + if rule != "answered": + continue + spent = {i for r in used.get(task) or [] for i in r.get("ids") or []} + fresh = [i for i in info["ids"] if i not in spent] + if fresh: + pending[task] = dict(info, ids=fresh, picked_in=[Path(slot).name]) + return {t: dict(v) for t, v in pending.items() + if t in (counters.get("outcomes") or {})} + + +def _spawned_release(counters: dict, task: str, now: _dt.datetime) -> None: + """A pending in-shift release whose task has just spawned: its parked + outcome moves to `inshift_released` (the ids are used), it leaves `done`.""" + info = (counters.get("inshift_pending") or {}).pop(task, None) + if info is None: + return + counters.setdefault("inshift_released", {}).setdefault(task, []).append( + {"ids": info.get("ids") or [], "at": _iso(now), + "outcome": counters["outcomes"].pop(task, None)}) + if task in counters["done"]: + counters["done"].remove(task) + + +def carry_in(slot: Path, counters: dict, now: _dt.datetime) -> dict: + """Carry-over at a shift's first tick (M3.6c): the newest earlier slot's + late `glance`/`notify` PRs — never closed out, or refused only because + they went green too close to `review-at:` — enter this shift's outcomes, + so its close-out path takes them under this shift's grant (`merge-cap:`, + CI green, the close-out session's own checks). A PR refused for its tier, + its CI or a `/drop` stays the human's. Recorded once, as `carried_in`.""" + home, here = Path(slot).parent, Path(slot).name + try: + # Dated slots only (`YYYY-MM-DD-…`, a brief record's stem), the newest + # one that ran something: a shadow or empty slot carries nothing and + # must not hide an older one; an override brief's stem carries nothing. + earlier = sorted(d for d in home.iterdir() if d.is_dir() and d.name < here + and _DATED_SLOT_RE.match(d.name) and (d / COUNTERS_FILE).is_file() + and (_safe_counters(d) or {}).get("outcomes")) \ + if _DATED_SLOT_RE.match(here) else [] + except OSError: + earlier = [] + rec = {"from": earlier[-1].name if earlier else "", "prs": [], "at": _iso(now)} + prev = _safe_counters(earlier[-1]) if earlier else {} + try: + cut = "green within " + for task, o in (prev.get("outcomes") or {}).items(): + pick = (prev.get("picks") or {}).get(task) or {} + if pick.get("tier") not in ("glance", "notify") or task in counters["outcomes"] \ + or o.get("questions") or task in (prev.get("dropped") or {}): + # A `/drop`ped task's PR is the human's, whatever its shift + # recorded for it (M3.6c review: a late or paused one has no + # close-out refusal to read). + # A task parked on a question stays parked: its PR waits on + # the answer, and `parked_elsewhere` keeps its hold (review). + continue + prs = [u for u in o.get("prs") or [] if "/pull/" in u + and u not in (o.get("merged") or []) + and ((prev.get("closeouts") or {}).get(u) is None + or str(((prev.get("closeouts") or {}).get(u) or {}).get("why", "")) + .startswith(cut))] + if not prs: + continue + counters["outcomes"][task] = {"prs": prs, "merged": [], "issues": [], + "carried_from": rec["from"]} + counters["picks"][task] = dict(pick, why=f"carried over from {rec['from']} · " + + str(pick.get("why") or "")) + if task not in counters["done"]: + counters["done"].append(task) + rec["prs"] += prs + except (AttributeError, TypeError) as e: + print(f"orchestrator: {rec['from']}/{COUNTERS_FILE} has the wrong shape ({e}) — " + "carry-over stopped there", file=sys.stderr) + counters["carried_in"] = rec + return rec + + def origin_claims(mind: Path, ref: str = "origin/main", fetch=None) -> dict | None: """What Mind `origin/main` holds, read locally and read-only (#632, F4): its `draft/` paths and the `## slug` sections of its `active.md`. @@ -1706,19 +1849,33 @@ def plan() -> dict: # The inbox releases a hold once its questions are answered (M3.5, # #645): read from Mind origin/main after the shift's one fetch. resumes: dict = {} - inbox = _questions.read_origin(mind, fetch=lambda: _fetch_once(mind, counters, now)) + review_at = _brief._iso((shift or {}).get("review_at") or "") + inbox = _questions.read_origin( + mind, fetch=lambda: _fetch_for_answers(mind, counters, now, review_at)) parked = parked_elsewhere(slot, inbox, resumes) + # This shift's own parks an answer released with time left (M3.6c). + here = released_here(slot, counters, inbox, now, review_at) + resumes.update(here) + _write_counters(slot, counters) 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"]] - resumes = {t: v for t, v in resumes.items() if t not in counters["picks"]} + # A task this shift picked is never resumed from an earlier park — + # except one this shift's own answer just released (M3.6c). + resumes = {t: v for t, v in resumes.items() + if t not in counters["picks"] or t in here} recs = resume_records(recs, mind, resumes) # Against Mind origin/main, not the canonical checkout nobody # pulls mid-shift (#632, F4): a draft another shift already # claimed is never picked again, nor one whose repo a claim holds. - recs, claimed = on_origin(recs, mind, set(counters["picks"]), + # A carried task (M3.6c) is closed out, never planned: not this + # shift's own pick for the claim gate, and out of the plan. + 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] + recs, claimed = on_origin(recs, mind, set(counters["picks"]) - carried, fetch=lambda: _fetch_once(mind, counters, now), resumes=resumes) planned["claimed"] = claimed @@ -1761,6 +1918,9 @@ def known(task: str) -> bool: own_tasks=counters["redispatched"]) except _mind_writer.MindWriteError as e: ledger = {"committed": None, "error": str(e)} + if "carried_in" not in counters and not _brief.is_shadow(brief): + carry_in(slot, counters, now) # the shift's first tick (M3.6c) + _write_counters(slot, counters) closeouts = _closeouts(slot, brief, counters, spawner, now, agents, health, pr_state, tokens=tokens, review_at=_brief._iso((shift or {}).get("review_at") or "")) @@ -1816,15 +1976,21 @@ def known(task: str) -> bool: spawned, refused = [], [] # A re-dispatch goes first (#637, item 1): a backlog dip never takes the # worker slot a killed task is waiting for. + first_glance = (brief.get("first") or {}).get("value") == "glance" members = sorted(d["members"], - key=lambda m: task_id(m["path"]) not in counters["pending_redispatch"]) + key=lambda m: (task_id(m["path"]) not in counters["pending_redispatch"], + # `first: glance` (M3.6c): spawn order only — + # the plan's selection is unchanged. + not (first_glance and m.get("consequence") == "glance"))) # The CLI login (M3.6a, #659): an expired one holds every spawn, as its # own event — never a worker "blocked on a person". login = _login_hold(counters, spawner, [] if paused else members, live, now) hold = paused or (login or {}).get("state") == "expired" for member in [] if hold else members: task = task_id(member["path"]) - if task in live or task in counters["done"] or task in counters["abandoned"] \ + released = member.get("resume") and task in (counters.get("inshift_pending") or {}) + if task in live or (task in counters["done"] and not released) \ + or task in counters["abandoned"] \ or task in counters["parked"] or task in counters["dropped"]: continue if len(live) >= max_workers: @@ -1890,6 +2056,8 @@ def known(task: str) -> bool: counters["usage"][lease["worker"]] = {"kind": "worker", "task": task, "total": None, "reserve": reserve} counters["picks"][task] = pick_record(member, brief) + if released: + _spawned_release(counters, task, now) if task in counters["pending_redispatch"]: counters["pending_redispatch"].remove(task) counters["redispatched"][task] = counters["redispatched"].get(task, 0) + 1 @@ -3296,7 +3464,7 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti if _brief.is_shadow(brief) or counters.get("paused"): return events # paused (#622): a green PR waits; it is not refused return _start_closeouts(slot, brief, counters, spawner, now, health, events, - review_at) + review_at, pr_state=pr_state) def queue_retire_op(counters: dict, task: str, pr: str, now: _dt.datetime, @@ -3462,7 +3630,8 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.datetime, - health, events: dict, review_at: _dt.datetime | None) -> dict: + health, events: dict, review_at: _dt.datetime | None, + pr_state=None) -> dict: """Start one close-out per newly green PR, under the watcher's guards.""" lease_dir = slot / "leases" health = health or _digest.pr_health @@ -3485,6 +3654,21 @@ def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt. "→ your /prm"} events["refused"].append(pr) continue + if out.get("carried_from"): + # A carried PR (M3.6c) may have been merged or closed by the + # human since its shift: only an OPEN one is closed out, so a + # human's merge is never counted as an unattended one. + gh = pr_state(pr) if pr_state else None + if not gh: + continue # GitHub unreadable: asked again next tick, never assumed + state = gh.get("state") + if state != "OPEN": + counters["closeouts"][pr] = { + "task": task, "state": "refused", + "why": f"carried over from {out['carried_from']}, but GitHub reads it " + f"{state or '?'} — not closed out"} + events["refused"].append(pr) + continue verdict = health(pr) if verdict == "RUNNING": continue # CI has not landed yet; look again next tick diff --git a/agents/conductors/batch/_watch.py b/agents/conductors/batch/_watch.py index 1eb4c17..991ec01 100644 --- a/agents/conductors/batch/_watch.py +++ b/agents/conductors/batch/_watch.py @@ -173,7 +173,10 @@ def snapshot(brief_path: Path, slot: Path, now: _dt.datetime, *, agents=None, "status_url": _orchestrator.status_url(slot) if started else "", "budgets": { "workers": f"{sum(l.get('state') != 'parked' for l in held.values())} live of {_brief.cap_of(brief, 'max-workers')}", - "sessions": f"{counters.get('sessions', 0)} of {_brief.cap_of(brief, 'max-sessions')}", + "sessions": f"{counters.get('sessions', 0)} of {_brief.cap_of(brief, 'max-sessions')}" + + (" (from token-budget)" # M3.6c: a derived cap says so + if _brief.cap_source(brief, "max-sessions") == "from token-budget" + else ""), "tokens": values["tokens"], "merges": f"{merges} of {_value(brief, 'merge-cap')}" f" ({values['glance-auto-merges']} unattended)", diff --git a/tests/test_batch_watch.py b/tests/test_batch_watch.py index 9dd4967..6775753 100644 --- a/tests/test_batch_watch.py +++ b/tests/test_batch_watch.py @@ -123,7 +123,8 @@ def test_live_snapshot_shows_every_task_state_reason_health_and_budget(tmp_path) assert "- parked — parked: awaiting-input" in text assert "- crashed — crashed — awaiting re-dispatch" in text assert "- workers: 2 live of 3" in text - assert "- sessions: 4 of 8" in text # the max-sessions default (PyAutoBrain#656) + # No max-sessions: derived from token-budget 5000 and max-workers 3 (M3.6c). + assert "- sessions: 4 of 6 (from token-budget)" in text assert "- tokens: 1234 of 5000" in text assert "- merges: 1 of 2 (1 unattended)" in text assert "- workers crashed: 1" in text diff --git a/tests/test_orchestrator_throughput.py b/tests/test_orchestrator_throughput.py new file mode 100644 index 0000000..4365607 --- /dev/null +++ b/tests/test_orchestrator_throughput.py @@ -0,0 +1,426 @@ +"""M3.6c (PyAutoBrain#669): shift throughput. + +Shift 2026-11-16-pm produced no stage-2 rows and idled twice: a late `glance` +PR no later shift picks up, an answered question that released its task only +to the next shift, and `max-sessions 8` stopping new starts with 2.3M tokens +unspent. Human decisions 2026-11-17 (PyAutoMind +`active/shift_throughput_carryover_and_order.md`): a bounded in-shift fetch; carry +over only `glance`/`notify` PRs never closed out or refused by the cutoff, from +the newest earlier slot; `first: glance` reorders; a 150k-token session floor. + +One test group per Witness clause (1-4), on a fake clock; each fails on main +2ca1bd3. Fictional fixtures only. +""" + +from __future__ import annotations + +import datetime as _dt +import json +import sys +from pathlib import Path + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "tests")) +import test_orchestrator_closeout as co # noqa: E402 — the 4b close-out fixtures +import test_orchestrator_digest as t # noqa: E402 — the 3d fixtures +import test_orchestrator_dispatch as d # noqa: E402 — the real-spawner fixtures +from test_orchestrator_digest import _brief, orch # noqa: E402 +import _batch # noqa: E402 +import _questions # noqa: E402 +import _watch # noqa: E402 + +NOW = d.NOW # 09:00Z; the d-fixture briefs end at 11:30Z +LATE = "https://github.com/o/r/pull/720" +CUT = "https://github.com/o/r/pull/721" +RED = "https://github.com/o/r/pull/722" +JUDGE = "https://github.com/o/r/pull/723" +Q1 = "https://github.com/example-org/widgets/issues/70" + + +# --- 1. carry-over at the first tick --------------------------------------------------- + +def _previous_slot(home: Path, name="2026-11-03-pm") -> Path: + """The last shift: a late glance PR, one refused by the cutoff, one refused + for CI and a judge PR — only the first two carry over.""" + slot = home / name + slot.mkdir(parents=True) + pick = {"prompt": "draft/feature/pyautoheart/{}.md", "why": "named task", "tier": "glance", + "title": "", "size": "small", "repos": ["pyautoheart"]} + picks = {k: dict(pick, prompt=pick["prompt"].format(k)) for k in ("late", "cut", "red")} + picks["big"] = dict(pick, prompt=pick["prompt"].format("big"), tier="judge") + (slot / orch.COUNTERS_FILE).write_text(json.dumps({ + "picks": picks, + "outcomes": {k: {"prs": [u], "merged": [], "issues": []} + for k, u in (("late", LATE), ("cut", CUT), ("red", RED), ("big", JUDGE))}, + "closeouts": {CUT: {"task": "cut", "state": "refused", + "why": f"green within {orch.CLOSEOUT_CUTOFF_S // 60} min of " + "review-at — no close-out starts this late"}, + RED: {"task": "red", "state": "refused", + "why": "CI FAILING — never merged unattended"}, + JUDGE: {"task": "big", "state": "refused", + "why": "tier judge — never merged unattended → your /prm"}}, + "parked": [], "done": ["late", "cut", "red", "big"]})) + return slot + + +class _OpenSpawner(co.Spawner): + """GitHub reads every PR OPEN, except those named MERGED.""" + + def __init__(self, merged=()): + super().__init__() + self.merged = set(merged) + + def pr_state(self, url): + return {"state": "MERGED" if url in self.merged else "OPEN", "mergedAt": "", + "mergedBy": ""} + + +def test_1_the_first_tick_closes_out_the_last_shifts_late_glance_prs(tmp_path): + home = tmp_path / "home" + _previous_slot(home) + mind = t._mind(tmp_path / "mind") + brief = tmp_path / "2026-11-04-am.md" + brief.write_text(t.BRIEF.format(issue=t.ISSUE, packet="").replace("merge-cap: 1", + "merge-cap: 4")) + sp = _OpenSpawner() + r = orch.tick(brief, mind, home=home, now=t.NOW, spawner=sp, agents=co.Agents(), + health=co._health({})) + assert {LATE, CUT} <= set(r["closeouts"]["started"]), r["closeouts"] + assert RED not in r["closeouts"]["started"] and JUDGE not in r["closeouts"]["started"] + c = orch.read_counters(orch.slot_dir(brief, home)) + assert c["carried_in"]["from"] == "2026-11-03-pm" + assert sorted(c["carried_in"]["prs"]) == [LATE, CUT] + assert c["picks"]["late"]["why"].startswith("carried over from 2026-11-03-pm") + # Once per shift: a later tick neither re-imports nor starts a second close-out. + co._tick(brief, mind, home, sp, 1) + co._tick(brief, mind, home, sp, 2) + assert [p for _, p in sp.closeouts].count(LATE) == 1 + # The digest says what was carried, and from where. + lines = t._digest.backlog_gate_lines(orch.read_counters(orch.slot_dir(brief, home))) + assert any(ln.startswith("Carried over from 2026-11-03-pm: 2 late PR(s)") for ln in lines) + + +def test_1_a_released_task_is_admitted_whatever_the_brief_scope(): + """The first tick restarts a task whose question was answered: the answer + is the human's word, as naming it would be, so `backlog: none` (or a scope + that does not cover it) does not keep it out.""" + rec = {"path": "active/alpha.md", "lane": "any", "epic": "", "themes": [], + "resume": {"ids": ["Q1"], "shift": "2026-11-03-pm"}} + brief = {"backlog": {"value": "none"}, "lanes": {"value": "any", "children": []}} + kept, rejected, _ = _brief.scope([rec], brief) + assert kept == [rec] and rejected == [] + + +# --- 2. in-shift restart: more than 30 minutes left ----------------------------------- + +def _parked_shift(tmp_path, monkeypatch, answered: bool = True): + mind, brief, home = d._shift(tmp_path, names=("t1",)) + slot = orch.slot_dir(brief, home) + claude = d.FakeClaude() + d._tick(brief, mind, home, NOW, claude) + (slot / "leases" / "t1.done").write_text(f"question: {Q1}\n") + d._tick(brief, mind, home, NOW + _dt.timedelta(minutes=5), claude, + d._agents({"t1": "done"}, slot)) + assert "t1" in orch.read_counters(slot)["done"] + inbox = {"t1": [{"id": "Q7", "shift": slot.name, "issue": Q1, + "state": "answered" if answered else "open", + "answered": "2026-11-04T09:20Z" if answered else "", + "answer": "(a) brass" if answered else "", + "comment": f"{Q1}#issuecomment-1" if answered else ""}]} + monkeypatch.setattr(_questions, "read_origin", lambda *a, **k: inbox) + return mind, brief, home, slot, claude + + +@pytest.mark.parametrize("left,restarts", [(31, True), (29, False)]) +def test_2_an_answer_with_more_than_30_minutes_left_restarts_the_task(tmp_path, monkeypatch, + left, restarts): + mind, brief, home, slot, claude = _parked_shift(tmp_path, monkeypatch) + review_at = _dt.datetime(2026, 11, 4, 11, 30, tzinfo=_dt.timezone.utc) + r = d._tick(brief, mind, home, review_at - _dt.timedelta(minutes=left), claude) + spawned = [s["task"] for s in r["spawned"]] + assert spawned == (["t1"] if restarts else []), r + if restarts: + prompt = claude.calls[-1][0][-1] + assert "parked on a question" in prompt and "Q7" in prompt + c = orch.read_counters(slot) + assert c["picks"]["t1"]["why"].startswith("resumed after Q7 was answered") + # Used up: the next tick does not restart it again. + r = d._tick(brief, mind, home, review_at - _dt.timedelta(minutes=left - 1), claude) + assert r["spawned"] == [] + + +def test_2_an_open_question_restarts_nothing(tmp_path, monkeypatch): + mind, brief, home, slot, claude = _parked_shift(tmp_path, monkeypatch, answered=False) + r = d._tick(brief, mind, home, NOW + _dt.timedelta(minutes=30), claude) + assert r["spawned"] == [] + + +def test_2_the_fetch_repeats_only_for_an_open_park_and_at_most_every_10_minutes(tmp_path, + monkeypatch): + calls = [] + monkeypatch.setattr(orch._mind_writer, "fetch", lambda mind: calls.append(mind)) + counters = {"outcomes": {}, "done": [], "inshift_released": {}} + review_at = _dt.datetime(2026, 11, 4, 11, 30, tzinfo=_dt.timezone.utc) + mind = Path("/nonexistent") + orch._fetch_for_answers(mind, counters, NOW, review_at) # the shift's one fetch + orch._fetch_for_answers(mind, counters, NOW + _dt.timedelta(minutes=20), review_at) + assert len(calls) == 1 # no open park: no more + counters["outcomes"]["t1"] = {"questions": [Q1], "prs": [], "merged": []} + orch._fetch_for_answers(mind, counters, NOW + _dt.timedelta(minutes=21), review_at) + orch._fetch_for_answers(mind, counters, NOW + _dt.timedelta(minutes=25), review_at) + assert len(calls) == 2 # then not within 10 min + orch._fetch_for_answers(mind, counters, NOW + _dt.timedelta(minutes=32), review_at) + assert len(calls) == 3 + late = review_at - _dt.timedelta(minutes=29) + orch._fetch_for_answers(mind, counters, late, review_at) + assert len(calls) == 3 # 30 min or less: never + + +# --- 3. `first: glance` ---------------------------------------------------------------- + +JUDGE_PROMPT = d.PROMPT.replace("Consequence: glance", "Consequence: judge") + + +def _ordered_shift(tmp_path, first: bool): + mind, brief, home = d._shift(tmp_path, names=("j1", "j2", "g1"), + extra=" - max-workers: 1\n" + + (" - first: glance\n" if first else "")) + folder = mind / "draft" / "feature" / "pyautobrain" + for n in ("j1", "j2"): + (folder / f"{n}.md").write_text(JUDGE_PROMPT.format(name=n)) + return mind, brief, home + + +@pytest.mark.parametrize("first,expect", [(True, "g1"), (False, "j1")]) +def test_3_first_glance_starts_ready_glance_work_before_named_judge_tasks(tmp_path, first, + expect): + mind, brief, home = _ordered_shift(tmp_path, first) + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert [s["task"] for s in r["spawned"]] == [expect], r + + +def test_3_brief_check_takes_first_glance_and_refuses_anything_else(tmp_path): + mind, brief, _ = _ordered_shift(tmp_path, True) + assert _brief.check(brief, mind)["ok"] + brief.write_text(brief.read_text().replace("first: glance", "first: notify")) + res = _brief.check(brief, mind) + assert not res["ok"] and any(e.startswith("brief.first:") for e in res["errors"]) + + +# --- 4. a session cap from the token budget -------------------------------------------- + +def _caps(**kv) -> dict: + return {k: {"value": str(v), "children": []} for k, v in kv.items()} + + +def test_4_no_max_sessions_derives_the_cap_from_budget_and_workers(): + assert _brief.cap_of(_caps(**{"token-budget": 5_000_000, "max-workers": 4}), + "max-sessions") == 34 # ceil(5M / 150k) + assert _brief.cap_of(_caps(**{"token-budget": 300_000, "max-workers": 4}), + "max-sessions") == 8 # floor: 2 x max-workers + assert _brief.cap_of(_caps(**{"token-budget": 5_000_000, "max-sessions": 8}), + "max-sessions") == 8 # an explicit value wins + assert _brief.cap_of({}, "max-sessions") == 8 # no budget: as before + assert _brief.cap_source(_caps(**{"token-budget": 5_000_000}), "max-sessions") \ + == "from token-budget" + + +def test_4_the_snapshot_shows_the_derived_cap(tmp_path): + mind, brief, home = d._shift(tmp_path, budget=5_000_000) + d._tick(brief, mind, home, NOW, d.FakeClaude()) + snap = _watch.snapshot(brief, orch.slot_dir(brief, home), NOW) + assert snap["budgets"]["sessions"] == "1 of 34 (from token-budget)", snap["budgets"] + + +def test_4_the_2026_11_16_pm_brief_never_refuses_on_sessions_under_half_its_budget(tmp_path): + """Replayed: max-workers 4, token-budget 5M, no max-sessions; each worker + spends what that shift's eight did on average (2.63M / 8).""" + names = tuple(f"w{i:02d}" for i in range(16)) + mind, brief, home = d._shift(tmp_path, names=names, budget=5_000_000, + extra=" - max-workers: 4\n") + slot = orch.slot_dir(brief, home) + claude, spend = d.FakeClaude(), 2_630_539 // 8 + tokens = lambda sid: spend # noqa: E731 + now = NOW + for _ in range(12): + r = d._tick(brief, mind, home, now, claude, tokens=tokens, + agents=d._agents({n: "done" for n in names}, slot)) + c = orch.read_counters(slot) + if c["tokens"] < 5_000_000 // 2: + assert not any(x["why"].startswith("max-sessions") for x in r["refused"]), r + for task in orch.leases(slot): + (slot / "leases" / f"{task}.done").write_text("https://github.com/o/r/pull/1\n") + now += _dt.timedelta(minutes=5) + assert orch.read_counters(slot)["sessions"] > 8 # past the old cap + + +# --- review fixes (Fable 5.2) ---------------------------------------------------------- + +def _carry_shift(tmp_path, prev_extra: dict, merged=()): + home = tmp_path / "home" + prev = _previous_slot(home) + c = json.loads((prev / orch.COUNTERS_FILE).read_text()) + for k, v in prev_extra.items(): + c.setdefault(k, {}).update(v) + (prev / orch.COUNTERS_FILE).write_text(json.dumps(c)) + mind = t._mind(tmp_path / "mind") + brief = tmp_path / "2026-11-04-am.md" + brief.write_text(t.BRIEF.format(issue=t.ISSUE, packet="").replace("merge-cap: 1", + "merge-cap: 4")) + sp = _OpenSpawner(merged) + r = orch.tick(brief, mind, home=home, now=t.NOW, spawner=sp, agents=co.Agents(), + health=co._health({})) + return r, orch.read_counters(orch.slot_dir(brief, home)) + + +def test_review_a_carried_pr_the_human_merged_since_is_not_closed_out(tmp_path): + r, c = _carry_shift(tmp_path, {}, merged=(LATE,)) + assert LATE not in r["closeouts"]["started"] and CUT in r["closeouts"]["started"] + assert c["closeouts"][LATE]["why"].endswith("GitHub reads it MERGED — not closed out") + assert c.get("glance_auto_merges", 0) == 0 + + +def test_review_a_question_parked_tasks_pr_is_not_carried(tmp_path): + r, c = _carry_shift(tmp_path, {"outcomes": {"late": {"prs": [LATE], "merged": [], + "questions": [Q1]}}}) + assert LATE not in c["carried_in"]["prs"] and "late" not in c["outcomes"] + + +def test_review_an_undated_or_empty_newest_slot_does_not_hide_the_last_real_one(tmp_path): + home = tmp_path / "home" + _previous_slot(home) + for name in ("2026-11-04-aa", "2026-11-03-zz"): # a shadow/empty slot + (home / name).mkdir() + (home / name / orch.COUNTERS_FILE).write_text(json.dumps({"picks": {"x": {}}})) + slot = home / "2026-11-04-am" + slot.mkdir() + c = {"outcomes": {}, "picks": {}, "done": []} + assert orch.carry_in(slot, c, NOW)["from"] == "2026-11-03-pm" + undated = home / "shift" + undated.mkdir() + assert orch.carry_in(undated, {"outcomes": {}, "picks": {}, "done": []}, NOW)["prs"] == [] + + +def test_review_the_first_tick_restarts_a_task_answered_since_the_last_shift(tmp_path, + monkeypatch): + """Witness clause 1, second half, by a tick: `backlog: none`, the task not + named, and still restarted with the human's answer.""" + mind, brief, home = d._shift(tmp_path, names=("t0",)) + (mind / "draft" / "feature" / "pyautobrain" / "t1.md").write_text(d.PROMPT.format(name="t1")) + prev = home / "2026-11-03-pm" + prev.mkdir(parents=True) + (prev / orch.COUNTERS_FILE).write_text(json.dumps({ + "outcomes": {"t1": {"questions": [Q1], "prs": [], "merged": []}}, "parked": [], + "picks": {"t1": {"prompt": "draft/feature/pyautobrain/t1.md"}}})) + monkeypatch.setattr(_questions, "read_origin", lambda *a, **k: {"t1": [ + {"id": "Q3", "shift": "2026-11-03-pm", "issue": Q1, "state": "answered", + "answered": "2026-11-03T22:00Z", "answer": "yes", "comment": ""}]}) + claude = d.FakeClaude() + r = d._tick(brief, mind, home, NOW, claude) + assert sorted(s["task"] for s in r["spawned"]) == ["t0", "t1"], r + prompt = next(c[0][-1] for c in claude.calls if "shift:t1" in c[0]) + assert "parked on a question" in prompt and "Q3" in prompt + + +def test_review_a_release_refused_one_tick_still_resumes_the_next(tmp_path, monkeypatch): + mind, brief, home, slot, claude = _parked_shift(tmp_path, monkeypatch) + (mind / "draft" / "feature" / "pyautobrain" / "t2.md").write_text(d.PROMPT.format(name="t2")) + brief.write_text(brief.read_text().replace( + " - draft/feature/pyautobrain/t1.md", + " - draft/feature/pyautobrain/t2.md\n - draft/feature/pyautobrain/t1.md") + + " - max-workers: 1\n - max-sessions: 8\n") + r = d._tick(brief, mind, home, NOW + _dt.timedelta(minutes=30), claude) + assert [s["task"] for s in r["spawned"]] == ["t2"] # t1 held by max-workers + c = orch.read_counters(slot) + assert "t1" in c["outcomes"] and "t1" in c["inshift_pending"] # the park is kept + (slot / "leases" / "t2.done").write_text("https://github.com/o/r/pull/9\n") + r = d._tick(brief, mind, home, NOW + _dt.timedelta(minutes=40), claude, + d._agents({"t2": "done"}, slot)) + assert [s["task"] for s in r["spawned"]] == ["t1"], r + prompt = claude.calls[-1][0][-1] + assert "parked on a question" in prompt and "Q7" in prompt + + +def test_review_a_release_that_never_spawns_leaves_the_park_for_the_next_shift(tmp_path, + monkeypatch): + mind, brief, home, slot, claude = _parked_shift(tmp_path, monkeypatch) + review_at = _dt.datetime(2026, 11, 4, 11, 30, tzinfo=_dt.timezone.utc) + monkeypatch.setattr(orch, "INSHIFT_RESTART_S", 10**6) # never in time + d._tick(brief, mind, home, review_at - _dt.timedelta(minutes=40), claude) + c = orch.read_counters(slot) + assert "t1" in c["outcomes"] and c["outcomes"]["t1"]["questions"] + resumes = {} + nxt = home / "2026-11-05-am" + nxt.mkdir() + orch.parked_elsewhere(nxt, {"t1": [{"id": "Q7", "shift": slot.name, "state": "answered", + "answered": "x", "answer": "y", "comment": ""}]}, + resumes) + assert "t1" in resumes + + +def test_review_first_glance_reorders_but_selects_the_same_tasks(): + def r(path, tier, minutes): + return {"path": path, "repos": [], "work_type": "feature", "difficulty": "small", + "score": 1, "consequence": tier, "witness": "w", "review_minutes": minutes, + "unattended": "ready", "why": "", "ready_why": [], "epic": "", "lane": "any", + "priority": "normal", "blocked": False, "autonomy": "safe", + "autonomy_cap": "safe", "declared_autonomy": "safe", "done": False, + "phase": float("inf")} + recs = [r("j1.md", "judge", 40)] + [r(f"g{i}.md", "glance", 5) for i in (1, 2, 3)] + base = {"backlog": {"value": "fill-idle", "children": []}, + "lanes": {"value": "any", "children": []}, + "tasks": {"value": "", "children": [{"text": "j1.md"}]}, + "review-minutes": {"value": "45", "children": []}} + a = _batch.plan(recs, brief=base, queue=["x"]) + b = _batch.plan(recs, brief=dict(base, first={"value": "glance", "children": []}), + queue=["x"]) + assert [m["path"] for m in a["members"]] == [m["path"] for m in b["members"]] + + +def test_review_once_per_answer_a_new_answered_question_restarts_again(tmp_path, monkeypatch): + mind, brief, home, slot, claude = _parked_shift(tmp_path, monkeypatch) + r = d._tick(brief, mind, home, NOW + _dt.timedelta(minutes=20), claude) + assert [s["task"] for s in r["spawned"]] == ["t1"] + (slot / "leases" / "t1.done").write_text(f"question: {Q1}\n") # parks again + d._tick(brief, mind, home, NOW + _dt.timedelta(minutes=25), claude, + d._agents({"t1": "done"}, slot)) + entry = {"shift": slot.name, "issue": Q1, "state": "answered", "answered": "x", + "answer": "y", "comment": ""} + monkeypatch.setattr(_questions, "read_origin", lambda *a, **k: {"t1": [ + dict(entry, id="Q7"), dict(entry, id="Q8")]}) + r = d._tick(brief, mind, home, NOW + _dt.timedelta(minutes=40), claude) + assert [s["task"] for s in r["spawned"]] == ["t1"], r + assert "Q8" in claude.calls[-1][0][-1] + assert [x["ids"] for x in orch.read_counters(slot)["inshift_released"]["t1"]] == \ + [["Q7"], ["Q8"]] + + +def test_review2_a_dropped_tasks_late_pr_is_not_carried(tmp_path): + r, c = _carry_shift(tmp_path, {"dropped": {"late": {"at": "2026-11-03T18:00Z"}}}) + assert LATE not in c["carried_in"]["prs"] and LATE not in r["closeouts"]["started"] + + +def test_review2_a_pending_release_clears_at_30_minutes_and_the_park_stays(tmp_path, + monkeypatch): + mind, brief, home, slot, claude = _parked_shift(tmp_path, monkeypatch) + (mind / "draft" / "feature" / "pyautobrain" / "t2.md").write_text(d.PROMPT.format(name="t2")) + brief.write_text(brief.read_text().replace( + " - draft/feature/pyautobrain/t1.md", + " - draft/feature/pyautobrain/t2.md\n - draft/feature/pyautobrain/t1.md") + + " - max-workers: 1\n - max-sessions: 8\n") + review_at = _dt.datetime(2026, 11, 4, 11, 30, tzinfo=_dt.timezone.utc) + d._tick(brief, mind, home, review_at - _dt.timedelta(minutes=40), claude) + assert "t1" in orch.read_counters(slot)["inshift_pending"] + r = d._tick(brief, mind, home, review_at - _dt.timedelta(minutes=29), claude) + c = orch.read_counters(slot) + assert r["spawned"] == [] and c["inshift_pending"] == {} + assert c["outcomes"]["t1"]["questions"] and "t1" in c["done"] + + +def test_review2_the_digest_names_an_in_shift_restart(tmp_path, monkeypatch): + mind, brief, home, slot, claude = _parked_shift(tmp_path, monkeypatch) + d._tick(brief, mind, home, NOW + _dt.timedelta(minutes=20), claude) + lines = t._digest.backlog_gate_lines(orch.read_counters(slot)) + assert "Restarted in-shift after an answer: 1 task(s) — `t1` (Q7)" in lines