From 33fbcabf0e682de112ac1d53ae545a0170179edc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:45:33 +0000 Subject: [PATCH 1/6] refactor(batch): retire batch collect, per-worker mentions and the questions backfill The August batch flow (a hand-dispatched record scored by `batch collect` into a review packet, with an optional integration preview) is superseded by the shift orchestrator. Remove the collect verb and its code, _integration.py, packet.js and their tests; the per-worker @mention path, unreachable since the questions inbox replaced it (event-comment retries stay); the one-off `batch questions --backfill`; and names left dead by these removals. Every surviving batch verb prints the same output as before against a real Mind, and the pre-change orchestrator tests pass against this source. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016nhQ8NtYMv2K9yt336CnGn --- AGENTS.md | 2 +- AUTONOMY.md | 6 +- agents/conductors/batch/AGENTS.md | 476 +---- agents/conductors/batch/_batch.py | 2264 +--------------------- agents/conductors/batch/_brief.py | 4 - agents/conductors/batch/_digest.py | 17 +- agents/conductors/batch/_integration.py | 473 ----- agents/conductors/batch/_orchestrator.py | 129 +- agents/conductors/batch/_premise.py | 1 - agents/conductors/batch/_questions.py | 126 -- agents/conductors/batch/_ready.py | 2 - agents/conductors/batch/_status.py | 52 +- agents/conductors/batch/batch.sh | 28 - agents/conductors/batch/packet.js | 324 ---- bin/branch_sweep.sh | 2 +- bin/pyauto-brain | 2 +- skills/COMMANDS.md | 2 +- skills/batch/batch.md | 79 +- skills/batch/reference.md | 54 +- tests/test_batch_collect.py | 927 --------- tests/test_batch_freeze.py | 156 -- tests/test_batch_integration.py | 773 -------- tests/test_batch_records.py | 59 + tests/test_orchestrator_events.py | 9 +- tests/test_orchestrator_mentions.py | 158 +- tests/test_questions_inbox.py | 7 - 26 files changed, 165 insertions(+), 5967 deletions(-) delete mode 100644 agents/conductors/batch/_integration.py delete mode 100644 agents/conductors/batch/packet.js delete mode 100644 tests/test_batch_collect.py delete mode 100644 tests/test_batch_freeze.py delete mode 100644 tests/test_batch_integration.py create mode 100644 tests/test_batch_records.py diff --git a/AGENTS.md b/AGENTS.md index 6c856f42..bc3e9091 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,7 @@ invoking it; `bin/pyauto-brain help ` exposes its full contract. | Verb | Purpose | Entrypoint | |------|---------|------------| | `intake` | File classified prompts; never start development | `bin/pyauto-brain intake` | -| `batch` | Propose a review-budgeted batch; collect its results | `bin/pyauto-brain batch` | +| `batch` | Propose a review-budgeted shift; brief, watch and digest it | `bin/pyauto-brain batch` | | `community` | Triage community threads; human-approved replies and development handoffs | `bin/pyauto-brain community` | | `feature` | Select, size and plan features | `bin/pyauto-brain feature` | | `bug` | Classify regressions and plan repairs | `bin/pyauto-brain bug` | diff --git a/AUTONOMY.md b/AUTONOMY.md index 1a658b86..6a9724ec 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -847,7 +847,7 @@ a skill or a record makes it the default. amendment: the reader did not write the PR, runs the `Witness:` itself and tries to falsify the claims. **A self-run adversary leg is still an absent leg**: the author's own session re-reading its diff is not this pass, -whatever model it is on. `batch collect` reads it so: an adversary row whose +whatever model it is on. Read it so: an adversary row whose `model` equals its `author_model` passes only with `independent_session: true`. @@ -1649,7 +1649,9 @@ Codex hook list. pull request, never a base for one. It is **never forced** — a branch that is not a fast-forward of what is already published is pushed under a new `-N` name instead — and every pushed ref carries a `sweep-after:` date on the - batch record, after which `bin/branch_sweep.sh` may delete it. + batch record, after which `bin/branch_sweep.sh` may delete it. (`batch + collect` was retired on 2026-11-22; the sweep rule stays for refs already + published.) A third exception, added 2026-11-03: the **shift watcher** — read-only `gh pr checks` and `claude agents --json`, and one issue comment per shift — diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 0657047e..797ab759 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -57,8 +57,6 @@ consulting a conductor. If a rule here starts needing to *judge* rather than | **Backpressure** | see below | | **Brief scope** | under a shift brief, only its named tasks and the backlog its dip policy covers run; anything else is a dispatch outside the launch, which "What a batch launch is" forbids (`AUTONOMY.md`, 2026-11-03) | | **Merge cap** | unattended `glance` merges stop at the brief's `merge-cap:`; each merge moves `main` and stales the next member's evidence, and the cap bounds what one unread shift can change | -| **One integration root per slot, and it is local** | `integration/` is cut fresh from `origin/main` on every run and never pushed, so a re-run is a re-preview rather than a rewrite; a dirty integration worktree is skipped, never reset. The one-member-per-library-repo rule above is what keeps within-repo conflicts rare — the common case is one member with organ PRs across five repos. | -| **Publishing that root is a separate act, typed by the human** | `--push` is the only remote write the batch makes, and no record can ask for it — `- integration: yes` requests the *local* preview. What it writes is a throwaway `integration/*` review ref and nothing else: never a pull request, never a base for one, never forced. A refresh that is not a fast-forward publishes `-2` rather than moving what is already there, and the ref expires at the record's `sweep-after:`. | Everything rejected says so, with its reason. A planner that silently drops work teaches the human to distrust the number it reports. @@ -737,25 +735,12 @@ 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 -(2026-11-12) is a GitHub @mention on the shift's digest issue. When a worker is -parked (`blocked` past the grace) or its `.done` names an issue not marked -`verdict:` (`question:`, bare or any other marker — only a posted verdict is not -a push, #632), the -tick posts one comment on the brief's `issue:` naming the task, the reason and -its session, worktree or PR, @-mentioning the login from `PYAUTO_SHIFT_MENTION` -or `config/policy.yaml` `shift_watcher: mention_login:`. One comment per worker -per state, marker (`/mentions/`) before post, a failed post retried next -tick; a crash, refusal or finished worker never mentions (AUTONOMY.md push test). -Each sent mention counts in `pushes`; more than one is a digest finding. The -trigger is durable state (a parked task or an un-verdicted issue in a `.done` with no -marker yet), so a tick that dies between parking and posting mentions on the -next; a failed mention is also retried by the late sweep. - -**The questions inbox replaces those two mentions (M3.5, PyAutoBrain#645).** -A parked worker or a `.done` issue not marked `verdict:` no longer -@-mentions anyone (`_mention_triggers` returns neither; the machinery above -stays for other triggers). The reap queues one `question-add` op per issue +**A blocked worker reaches the human through the questions inbox (M3.5, +PyAutoBrain#645).** A parked worker (`blocked` past the grace) or a `.done` +issue not marked `verdict:` (`question:`, bare or any other marker) @-mentions +nobody: the per-worker @mention of PyAutoBrain#611 was removed. The human's +login (`PYAUTO_SHIFT_MENTION`, else `config/policy.yaml` `shift_watcher: +mention_login:`) now only names whose comments steer the shift. The reap queues one `question-add` op per issue (`land_question`): the task's prompt, the issue, `kind: question` (or `blocked`, filed on the shift issue), the ask and options from the worker's `{task}.question.json` sidecar (sanitised; `see the question on the issue` @@ -774,8 +759,7 @@ claimed (`- session: shift worker …`) is graded from `active/.md` on origin (`resume_records`), kept by `on_origin(…, resumes=)` (its own claim does not hold its repos) and spawned with `RESUME_NOTE`; its pick's `why:` starts `resumed after Q was answered`. The human answers in a `/questions` -chat (`skills/questions`). `batch questions --backfill` prints the -`questions_edit.py add` lines that seed the inbox from today's holds. +chat (`skills/questions`). **The readiness pass (M3.3, PyAutoBrain#671, `_ready.py`).** `batch ready` resolves each `queue.md` entry to its next unit(s) (an epic ledger to its open @@ -849,8 +833,8 @@ The App is minimal on purpose: **Issues read/write on PyAutoMind only** — all the watcher does is comment on, edit its comment on and read the shift issue. It is **not `pyautolabs-bot`**: that App is a ruleset bypass actor with org-wide push, and a laptop timer must hold no bypass power. Posting as an App -also means the @mention of the human comes from another account, so it -notifies them. `_app_token.py` signs an RS256 JWT (`iat` now − 60 s, `exp` now +also means the watcher's comments come from another account, so they +notify the human. `_app_token.py` signs an RS256 JWT (`iat` now − 60 s, `exp` now + 9 min, `iss` the App id; PyJWT, else `openssl dgst -sha256 -sign` with no shell) and mints an installation token with one `POST /app/installations//access_tokens` on the first watcher GitHub call of a @@ -858,7 +842,7 @@ tick, reusing it for the rest of that tick. The token is held **in memory only** — never written to disk, where a worker running as the same user could read it; each tick that makes a watcher GitHub call mints its own. The token is passed as `GH_TOKEN` to the watcher's own `gh` calls and to nothing else: -**every watcher write** (the status comment and its edits, mentions, the digest, +**every watcher write** (the status comment and its edits, event comments, the digest, the correction) and the steering read of the shift issue's comments. Two **reads** deliberately stay under the human's own `gh` auth, because the App cannot see library repositories: `gh pr view` for the PRs its workers named @@ -874,12 +858,9 @@ configured in part (one or two variables) is the same failure. Without the App, `PYAUTO_SHIFT_GH_TOKEN` (a static fine-grained token, PyAutoMind issues:write only) is the fallback; with neither, comments post as the human's account. Neither the App variables, the key path, the static token nor a -minted token reaches a worker or close-out (`worker_env`). Once a shift, -before the first mention, the posting account is named — as the App, -`[bot]` from one `GET /app` with the JWT (`gh api user` does not answer -for an installation token), else `gh api user` — and if it is the mentioned -login (never, as the App) the digest's `### Workers` warns "mention will not -notify: posted as the mentioned account". With nothing pending, the tick is +minted token reaches a worker or close-out (`worker_env`). When the status comment is adopted, the posting account is named — as the +App, `[bot]` from one `GET /app` with the JWT (`gh api user` does not +answer for an installation token), else `gh api user`. With nothing pending, the tick is idle. The worker prompt also forbids EnterWorktree (its permission prompt stalls an unattended worker) and requires the `decision-taken` label on any PR carrying a flagged @@ -926,104 +907,13 @@ pyauto-brain batch plan --budget 45 # review-minutes available pyauto-brain batch plan --awaiting-review 6 # backpressure input pyauto-brain batch plan --json -pyauto-brain batch collect # score the newest record; offline -pyauto-brain batch collect --slot 2026-09-03-pm -pyauto-brain batch collect --evidence ev.json # PR state from this session -pyauto-brain batch collect --fetch # laptop: `gh pr view` per PR -pyauto-brain batch collect --integration # laptop: merge every member's head into one worktree root -pyauto-brain batch collect --evidence ev.json --apply # the one form that writes -pyauto-brain batch collect --out report.md --json - pyauto-brain batch watch --record # live view of a running shift; read-only pyauto-brain batch watch --record --once # one snapshot ``` -**One board: the development one.** The science board this conductor once -opened (`--kind cortex`) was retired on 2026-09-03 — 0 slots were ever opened -by it, 0 rulings came from its packets — and checking in on the science is -`pyauto-brain cortex collect --pull --apply` now, which needs no record at all. - -`plan` is stdlib-only, offline and writes nothing. `collect` is the same by -default — it reads the newest batch record (`--slot` picks another; the -newest is lexical, so `-night` sorts before `-pm` on one date), scores what it -can see and prints. It has no GitHub of its own: on the web surface the -session gathers PR state with the GitHub MCP tools (`skills/GITHUB_ACCESS.md`) -and hands it over as `--evidence `; `--fetch` is the laptop's shortcut, -one `gh pr view` per PR, opt-in and still writing nothing. Only `--apply` -writes — `batches/packets/.html` and the record's own stamps — which is -why it needs a stamp (`--stamp `, else now). - -Exit codes: **0** every member delivered · **1** a member needs the human -(FAILED, NOT-DELIVERED, SUSPECT, or still PENDING) · **2** usage · **4** no -Mind (no `batches/` at all). - -## Running a batch by hand (there is no dispatcher yet, and that is fine) - -Phase 5 — automatic fan-out — is deliberately unbuilt. Everything below works -today, costs about two minutes of tapping, and is the honest way to find out -what a dispatcher actually needs before writing one. - -**In the slot — whenever the human comes in; there is no schedule:** - -1. `pyauto-brain batch plan` — read the BatchDecision. Pass `--budget` if this - slot is not a default 45-minute one. Edit the decision by removing members - you do not want; do not add ones it rejected without reading why. -2. **Acknowledge the Heart reason set for the shift**, if Heart is YELLOW - (`pyauto-brain vitals`). Write it verbatim into the batch record — a grant - recorded loosely is how a scoped one becomes standing, which doctrine voids - (`AUTONOMY.md`, "Leg 4 under a batch launch"). -3. **Say when you expect to be back** — `review-at:`, an ISO timestamp. The - shift is dispatch → `review-at:`, and the grant expires there. It is the one - thing only the human knows, so it is stated, never inferred. -4. Open the batch record `PyAutoMind/batches/-.md` from the - schema in that folder's `AGENTS.md`, and write the members, the planned - review-minutes, `review-at:` and the reason set **before** dispatching. That - file is what makes the launch auditable afterwards. -5. **Dispatch — `local-dev` members first** (2026-08-31): paste their lines - into laptop CLI chats while the laptop is still on, so RAL submissions - queue this evening — that is the priority use of the remaining laptop - hours. Cloud members follow, each line into **its own session**. One - session per member — they must not share one, because a single session - would serialise them and carry one member's context into the next. - Spawned cloud members need the **member-session contract** - (`skills/batch/batch.md`, dispatch step 3): seed PyAutoMind as the session - source with the bootstrap preamble, and instruct members to **end at their - deliverable** — no PR watching, no event subscriptions, no self-armed - check-ins after the last push; the batch review owns follow-through - (2026-08-31: a bare-spawned wave died on missing sources, and green - members' self-armed check-ins drained usage overnight). The rule is now - universal, not a batch-only exemption - (`PyAutoMind/policy/end_at_deliverable.md`). -6. **Open the packet now** (2026-08-31): write the review page to - `PyAutoMind/batches/packets/-.html` with every member present - — overnight runs as PENDING entries — stamped `generated:`. The human - wakes to a live page; the morning collect fills it in. -7. Go and do something else. - -**At `review-at:` (or whenever they actually sit down):** - -8. **Collect** — `pyauto-brain batch collect --evidence --apply` - ("The collect recipe" below). It scores every dev member, fills the PENDING - entries in place and stamps the page `refreshed:` — normally while the - human is already reading the finished members. A dev member without a - green-CI PR is not `delivered:`, and collect says so first and loudly. - Science runs are not batch members at all: `pyauto-brain cortex collect - --pull --apply` is their check-in, and it has its own door. -9. The human reviews on the packet page — tick, choose, annotate, submit — - and the review lands as `batches/reviews/-.md` (or they - dictate it in-chat; same review). Failures first, then `decision-taken`, - then clean. Act on it member by member: merge (`/prm `) and write - science rulings into the project ledgers; tweaks become follow-up prompts - drafted for them at the **top of `queue.md`**; rejects go to - `condemned.md`. **Follow-ups are enacted in the next batch — a review - never executes its own follow-ups, and an open follow-up never holds the - next dispatch** (2026-08-31). -10. Close the batch record — `reviewed-at:` (when they really sat down, which - calibrates their own estimates), `delivered:`, `packet:`, `review:`, and - especially **`review-minutes-actual:`**. That last number is the only - calibration the review estimate will ever get, and everything the planner - does rests on it. -11. Plan the next batch, and declare the next `review-at:`. +`plan` is stdlib-only, offline and writes nothing. + +Exit codes: **0** ok · **1** findings · **2** usage · **4** no Mind. **The one leg you must not skip.** A batch launch requires the independent adversary (`AUTONOMY.md` leg 5). Run it before reading a PR: @@ -1035,331 +925,15 @@ pyauto-brain review --task --witness "" --adversar in a session **that did not write the branch — by default a fresh Opus session or sub-agent, even when your own chat is on Fable**; a more expensive model reads only when the human asks (`AUTONOMY.md` "Adversary model default — -2026-11-22"). A self-run adversary leg is an absent leg, not a weak one. `collect` cannot run -it for you and does not pretend to: with no `adversary` block in the evidence -the leg is UNOBSERVABLE and the member reaches the human as SUSPECT — the -honest state, rather than a gap that closes itself. The shift worker does not -run this pass (`AUTONOMY.md` "Shift speed — 2026-11-19", ruling S3): your read, -or the close-out session for an unattended merge, is the adversary. - -**What to expect from batch 1.** Small. The planner picks against a 45-minute -review budget, and with almost no prompt carrying a `Witness:` nearly everything -grades `judge` at 20 minutes — so a slot holds two or three. That number is the -honest state of the backlog rather than a limit of the machinery, and the way to -move it is to write witnesses, which costs zero review-minutes and is the best -possible fill work. - -## The collect recipe - -The verb answers one question — *what came back, and is it worth the human's -next hour?* — and answers it the way the Cortex conductor answers it for a -science pull: **six legs, then one health word**. It is a reader, not an actor: -it merges nothing, runs nothing and rules on nothing. - -### Six legs, each PASS · FAIL · UNOBSERVABLE - -| Leg | Passes when | -|---|---| -| `pr` | a PR exists | -| `diff` | the diff is non-empty | -| `checks` | every check completed | -| `green` | every check green | -| `witness` | the witness is declared, and holds | -| `adversary` | an independent adversary read it | - -**No evidence is UNOBSERVABLE, never delivered.** The offline default invents -nothing: with neither `--evidence` nor `--fetch`, every leg that needs GitHub -is unobservable and its member reaches the human as SUSPECT. Inventing PASS -would be inventing evidence and FAIL would condemn healthy work — the same -choice the Cortex conductor makes for the `delivered:` legs it cannot see. - -`adversary` is the leg with a rule of its own: it passes only when the read was -independent of the branch's author. **A self-run adversary leg is an absent -leg, not a weak one** (`AUTONOMY.md` leg 5), so a missing `model` or -`author_model` is FAIL, and so is an equal one unless the row carries -`"independent_session": true` — the default Opus reader of an Opus branch, in -a session that did not write it (`AUTONOMY.md` "Adversary model default — -2026-11-22"). - -### Six health words, in the order the human reads them - -``` -FAILED · NOT-DELIVERED · SUSPECT · HEALTHY · PENDING · MERGED -``` - -Severity order and sort order are the same list, so the top of the report is -the part that needs a person and the bottom is the part that is not finished -being work. `FAILED` is a failed check, green or witness; `NOT-DELIVERED` is no -PR, an empty diff, or checks that never ran — green is not delivered -(`batches/AGENTS.md`); `SUSPECT` is green work carrying an unobservable leg or -a flagged decision; `MERGED` and `PENDING` short-circuit ahead of all of it, -because a merged member is a retrospective and a pending one has not landed. -`delivered: n/m` counts HEALTHY and MERGED over every non-PENDING member. - -### The evidence JSON - -One object per member slug; every key optional, so a session supplies what it -actually looked up and nothing more. - -```jsonc -{"schema": 1, "members": { - "resampling-info-summary-section": { - "prs": [{"repo": "PyAutoLabs/PyAutoFit", "number": 1554, "url": "...", - "state": "open", "merged": false, - "additions": 86, "deletions": 12, "changed_files": 3, - "mergeable": "MERGEABLE", - "head_ref": "feature/autofit-resampling-info", - "head_sha": "2629933c...", "head_repo": "PyAutoLabs/PyAutoFit", - "checks": [{"name": "tests", "status": "completed", - "conclusion": "success"}]}], - "witness": {"holds": true, "evidence": "ordering test green on 2629933c"}, - "adversary": {"ran": true, "model": "gpt-5.1", - "author_model": "claude-opus-4", "verdict": "CLEAN"}, - "flagged": ["decide-and-flag: PR opened rather than parked"], - "pending": false, - "summary": "one line"}}} -``` - -`head_ref`/`head_repo` are the member -> branch map: the record stores no repo -or branch per member and `active.md`'s `repos:` field has four dialects, so the -PR's own head is the only reliable source. A `head_repo` that differs from -`repo` is a fork — its head is not on `origin`, so it is reported rather than -merged. - -`witness.holds` is tri-state: `true` PASS, `false` FAIL, absent UNOBSERVABLE. - -### Integration branches (`--integration`) - -One throwaway worktree root per slot under `$PYAUTO_WT_ROOT`, built by -`bin/worktree.sh` with `PYAUTO_WT_BRANCH=integration/`. Every affected -repo becomes a real worktree on `integration/`, cut from `origin/main`, -with every member's head branch merged in **dispatch order** — so the human can -*run* the whole batch before ruling on any of it, and "how would these resolve -at the end?" is answered by a merge rather than by reading diffs. - -**It fetches and reads; it never pushes, opens a PR, or touches a remote ref.** -Like `--fetch` it is opt-in, non-default and laptop-only — a cloud session is -pointed at the laptop rather than failing halfway through a root it cannot -finish. Pushing `integration/` is a separate, later decision, and a -separate flag — see `--push` below. - -```jsonc -{"slot": "2026-09-03-pm", - "root": "~/Code/PyAutoLabs-wt/integration-2026-09-03-pm", - "activate": "/activate.sh", "branch": "integration/2026-09-03-pm", - "at": "2026-09-03T08:00Z", - "repos": [{"repo": "PyAutoLabs/PyAutoFit", "dir": "PyAutoFit", - "path": "/PyAutoFit", "branch": "integration/2026-09-03-pm", - "base": "origin/main", "base_sha": "…", "head_sha": "…", - "merged": ["autofit-resampling-info"], - "conflicts": [{"member": "autoarray-x", "branch": "feature/x", - "paths": ["src/mask/mask_2d.py"]}], - "status": "clean | conflicted | skipped", "note": "", - // --push only; "" and false on every run without it - "remote_branch": "integration/2026-09-03-pm", "pushed": true, - "push_note": ""}], - "pushed": false, "sweep_after": "", - "notes": ["…"]} -``` - -`status` is the merge verdict and `pushed` is the network one; they are -deliberately separate. A push that fails leaves a clean integration reading -`clean`, because whether the merge collided is a fact about the merge and a -dead network does not change it. - -**Four reasons a member's PR is left out**, each said out loud: it is already -merged; it is CLOSED; it has no `head_ref` in the evidence (gathered before the -head fields were asked for — re-run `--fetch`); or its head lives on a **fork**, -whose branch is not on `origin` and cannot be merged from a local checkout at -all. A repo with no local checkout under the workspace root is dropped the same -way. - -**Nothing is resolved.** A member whose merge conflicts is left OUT of that -repo's branch and named with the conflicting paths; the merge is aborted and -the next member is tried. **That report is the product** — it does not change -the exit code, and it does not change any member's health word. A member's -health is about *its own* delivery; a merge collision is a property of the -*slot*, and mixing them would make a green, delivered member read as SUSPECT -because a sibling touched the same file. - -**A dirty integration worktree is skipped, never reset.** The branch is re-cut -from `origin/main` on every run (`checkout -B`), because the merge result is a -function of the current base and the current heads — a second run stacked onto -the first would preview a base that no longer exists. That is safe only because -the one thing a re-cut could destroy, a human's uncommitted experiment inside -the review root, is refused outright and reported. **That refusal, not the -branch policy, is the safety property.** - -`activate.sh`'s `PYTHONPATH` covers the libraries, so a **library** member's -change is live anywhere once the root is sourced. A **workspace** member is a -real worktree in the root but is not on the PYTHONPATH, so its script must be -run from inside `/`. - -**Collect does not rewrite your `--evidence` file.** That file is an *input*; -`--apply` writes exactly two things, the packet and the record's stamps. The -computed block is emitted on `--json`, rendered into the packet and stamped on -the record as `integration-root:` — persisting it is `--json > ev.json`'s job, -and a block pasted back into an evidence file is how a cloud session renders one -at all. - -### Pushing the integration branch (`--push`) - -`--push` publishes what `--integration` built. It **requires** `--integration` -(without it, a usage error and rc 2) and it is refused on `plan` — and no -record can ask for it. `- integration: yes` is a request for the *local* -preview; putting a ref on GitHub is a separate act, typed at collect by the -human, because it writes into shared repos under the laptop's own credential. -Laptop lane only, for the same reason `--integration` is: a cloud session's -credential cannot write a ref at all, so it is pointed at the laptop rather -than failing halfway. - -**What it publishes.** One real branch per repo — `integration/` — whose -tip is exactly the state `--integration` merged. A **conflicted** repo still -publishes: its branch carries the members that merged, and the ones left out -are named, with their conflicting paths, in the same report. A pushed branch is -therefore never a claim that the whole slot merges; it is the same partial -preview, on a machine the reviewer can reach. - -**Never a PR, never a base.** These refs are review scaffolding with a -death date, not proposals. Nothing opens a pull request from one, nothing -targets one as a base, and nothing merges one anywhere. - -**Never forced.** Three arms, decided per repo after re-fetching the -`integration/*` namespace: - -- the remote branch carries the **same tree** → not re-pushed at all, and said - so. This is the common case on a refresh: `--integration` re-cuts and - re-merges honestly, so the commit SHAs differ every run even when nothing - changed. Compare trees, not commits, or every refresh mints a new name. -- the remote branch is an **ancestor** → a plain fast-forward push. -- otherwise → published as `integration/-2` (then `-3`, …, first free - name, capped). The earlier ref is left exactly where it was. There is no - `--force` and no `--force-with-lease` anywhere in this path; `branch -f` - appears once, on a *local* name already proven absent on origin. - -A push that fails is a note and a `push_note` on the row, never a change to the -merge verdict. - -**How it ends.** Every push stamps `integration-remote:` on the record and -fills `sweep-after:` (see below); `bin/branch_sweep.sh --records ` deletes `integration/*` refs on or after that date and -protects them in every other case — no records dir, no record, no date, no -deletion. That expiry is the only thing keeping these refs from accumulating: -they can never be proven contained in `main`, so the sweep's ordinary -containment gate would keep them forever. - -### The packet is refreshed, never rewritten - -`--apply` writes `batches/packets/.html` in place and at the same path, -because the human's chips and notes live in `localStorage` keyed by the page -(`batches/packets/TEMPLATE.md`) and a moved file orphans them. Every member -owns a section with a stable `id="m-"`; a refresh replaces that span and -leaves **every other member's markup byte-identical** — a PENDING stub becomes -a full block under the same id, and nothing a neighbour's stored notes are -anchored to moves. The regenerable non-member regions (stamp, tiles, rulings -needed, sidenav) are bounded by `pyauto:*` sentinel comments; a hand-authored -archived packet has none, so it gets its member splices plus a note saying the -header was left alone. Collect never rewrites such a page wholesale. - -### What it stamps on the record - -`--apply` edits the batch record line by line, never re-serialising it: -`collected:` once (the first collect owns it), one `refreshed:` line per apply, -`delivered: n/m`, `packet:`, and — after an `--integration` run — -`integration-root:` (a key of its own: the dispatch-time -`- integration: yes` is the human's request, and is never overwritten -with a path). After an `--integration --push` run it also writes -`integration-remote:` — `:`, comma-separated, under the repo name -`branch_sweep.sh --name` matches on — **rewritten on every push**, because the -current publication is the truth and a stale list would send the sweep after a -ref that no longer exists. Alongside it, `sweep-after:` is **filled once and -never overwritten**: `review-at:` plus a week by default, and a date the human -typed is a decision about their own review. Member outcomes become ` ()` — -**unless the outcome already opens with a ruling word** -(`ACCEPTED`, `REJECTED`, `MERGED`, `LEAVE-TO-FINISH`, …), which is a human's -verdict and is never overwritten by a machine re-read. Once the slot's review -has landed, **no member line changes at all** — the record is the history of -a batch that closed, and the pm record's `PR OPENED AT REVIEW (…)` sentences -are exactly the outcomes no word list would have protected. The write is -rehearsed on a throwaway copy and refused if a member line or a key would be -lost; the `notes: |` block is never touched. - -Two **blocks** are stamped alongside those keys, both derived and both rewritten -on every apply of an open record (and filled once, then left, on a closed one — -its contents are history, like `delivered:`): - -- **`outcomes:`** — one `: ` per member. This is the *accounting*; the member line's outcome - column is the *evidence* ("PyAutoFit#1554, 4/4 checks green"). It is read - from the ledger and nothing else: a `complete/` record that names the member - (`- batch: — member ```, or a record filed under the member's - own name) → `merged`; a review `decision:` that rejected it → - `rejected-at-review`; a row still in `active.md` → `carried`; otherwise - `unreviewed`. In that order, because a rejected member is still in - `active.md` and a merged one may be too. All nine members of the - 2026-08-31-pm slot merged and every one of them was recorded - `decision: UNREVIEWED` — the completion records knew, and nothing read them. -- **`merge-order:`** — the `/prm` sequence, as advice and never an action: - dispatch order (the order the human listed the members in — the only stable - order there is, since `members` is sorted by health), with library repos - first (the library-first merge gate) and same-repo members serialised (the - first merge moves `main` and stales its siblings' evidence). Nothing is - filtered: a member with no PR is listed in its place with what it is waiting - on, because an order that silently omits a member is an order somebody merges - out of. It is rendered in the collect report's summary too. - -### The close leg - -**`dev` — collected once, reviewed once.** A review that has landed closes the -batch outright. Where `batches/reviews/.md` exists, collect **refuses to -write the packet** — that file is the record now, and rewriting the page the -human ruled on destroys what they ruled against — and instead fills -`reviewed-at:`, `review-minutes-actual:` and `review:` from it — **fills, -never overwrites**: a value the record already carries (anything but blank or -`(not given)`) is the human's and stays. The decisions inside are reported, -never enacted: merges, follow-ups and rejections are the orchestrator's next -act with the human, not collect's. The review button lives on `collected:` — -there is exactly one packet to press it on, because a dev batch is dispatched -at once and reviewed at once. - -**`cortex` — a rolling board, reviewed as many times as it takes.** A review -landing does **not** by itself refuse the packet write: `PyAutoCortex/batches/ -AGENTS.md`, "The first review does not close the slot" — the human rules on -whatever is reviewable whenever they come in, and the packet keeps refreshing -under whatever is still on the board while they do. A later sitting lands as -`batches/reviews/-r.md` (N ≥ 2; the first sitting is `.md` — see -"Two kinds, two records" below), and each one adds its own `- review:` line to -the record rather than replacing the last. What a review DOES do, on every -kind, is take its own members out of further splicing (`_on_the_board`): a -member the record already shows `ruled: yes` for is never re-rendered, on this -sitting's collect or any later one — its packet span is what the human was -shown. The record's `delivered:`/`packet:` keys are filled once the slot is -CLOSED — nothing left in a board state, carried members excluded — and moved -on every refresh until then; `reviewed-at:`/`review-minutes-actual:` still -fill from whichever sitting sets them first, and `carried:` is written once -per member the moment a sitting finds it still running. - -### The extension point - -Scoring is registered per member **kind** (`KINDS`) — a scorer plus a block -renderer, over the one flat scored shape the report and the packet both read. -`dev` was the kind that shipped first; the science kind (`cortex`) now ships -here too, over the phase-2 Cortex conductor's own `score_phase` and -`member_block` rather than a second collect. A third kind is a scorer, a block -renderer and a claim function — nothing else moves. - -## One kind, one record - -`dev` reads the Mind, and that is the whole roster. A second kind — `cortex`, -a science phase on a rolling board with its own record, packet, chips and -carry-forward — existed from 2026-08-31 to 2026-09-03 and was retired: 0 slots -were opened by the conductor, 0 rulings came from a packet, 0 partial reviews -were ever filed. What the human actually does with the science is check in on -the runs, which is `pyauto-brain cortex collect` (`agents/conductors/cortex/`). - -The extension point above (`KINDS`) is what made that possible and is kept: a -member kind is a scorer plus a block builder plus a claim, and nothing about -the record, the packet or the renderer has to learn its vocabulary. +2026-11-22"). A self-run adversary leg is an absent leg, not a weak one. The +shift worker does not run this pass (`AUTONOMY.md` "Shift speed — 2026-11-19", +ruling S3): your read, or the close-out session for an unattended merge, is +the adversary. + +The manual batch flow this conductor began with (a hand-dispatched batch +record, then `batch collect` scoring it into a review packet, with an optional +`integration/` preview) was retired in favour of the watcher above: a +shift is now a brief, and its digest is the report. ## Slicing a `needs-slicing` prompt (`slice`) diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index cc4870f7..7848085b 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """agents/conductors/batch/_batch.py — the batch conductor. -Composes what goes into one unattended shift, and reports what came back. Thin +Composes what goes into one unattended shift. Thin by construction: every judgement it uses — consequence tier, review-minutes, readiness, difficulty — belongs to the sizing faculty, because `ORGANISM.md` makes faculties the opinion sinks and forbids a conductor consulting a @@ -30,7 +30,6 @@ import argparse import datetime as _dt -import html import importlib.util import json import os @@ -38,7 +37,6 @@ import shutil import subprocess import sys -import tempfile from pathlib import Path BRAIN = Path(__file__).resolve().parents[3] @@ -48,12 +46,7 @@ effective_difficulty, pyauto_root, effective_review_minutes, effective_unattended, lane_is_local, normalise_repo, parse_prompt, priority_rank, ) -# `_status` (same directory) is the one definition of this vocabulary — the -# batch status box on the Mind's dashboard reads a record the same way this -# conductor writes one. Re-exported below (`RULING_WORDS`, `PENDING_RE`) so -# existing importers of `_batch` keep working. sys.path.insert(0, str(Path(__file__).resolve().parent)) -from _status import PENDING_RE, RULING_WORDS, freeze_line # noqa: E402 import _brief # noqa: E402 import _green # noqa: E402 — the keep-Heart-green lane (PyAutoBrain#625) import _login # noqa: E402 — the CLI login probe (M3.6a, PyAutoBrain#659) @@ -875,33 +868,7 @@ def emit(d: dict) -> None: print("shift is dispatch -> review-at, and it is where the grant expires.") -# ================================================================ collect === -# What came back from one shift, scored — and the page the human reads it on. -# -# One fact shapes every rule below. **A green session is not a delivered -# task.** A cloud session's green status means it started and exited without an -# infrastructure error; `batches/AGENTS.md` says a member counts as delivered -# only with "a PR that has a non-empty diff and checks that actually ran", and -# that a member ending green with no PR is reported not delivered, loudly, at -# the top of the packet. So this verb never reads a session's own report of -# itself. It reads PR evidence, and where it has none it says UNOBSERVABLE -# rather than inventing either verdict — the third answer the Cortex's own -# collect had to grow for exactly the same reason. -# -# It is offline by default and writes nothing without `--apply`. `--fetch` is -# the one leg that shells out, and only to `gh`, and only where `gh` exists. - -# The batch record's own grammar. `RECORD_KEY` is `_status.py`'s, kept -# byte-identical so the conductor and the status box read one record the same -# way; `MEMBER_RE` is deliberately loose — see `parse_member`. -RECORD_KEY = re.compile(r"^- ([a-z][a-z0-9-]*):(?:\s+(.*?))?\s*$") -MEMBER_RE = re.compile(r"^ - (?P[^:]+): (?P.+)$") - -# `RULING_WORDS` and `PENDING_RE` are `_status`'s (imported above): a record -# line opening with a ruling word is a VERDICT, and `--apply` leaves it alone; -# `PENDING_RE` is the ledger's own "not finished yet" vocabulary. Kept as one -# definition so the batch status box and this conductor never drift. - +# ---------------------------------------------------------- Mind records --- PR_URL_RE = re.compile(r"https://github\.com/([\w.-]+/[\w.-]+)/pull/(\d+)") ISSUE_URL_RE = re.compile(r"https://github\.com/[\w.-]+/[\w.-]+/issues/\d+") @@ -910,118 +877,6 @@ class BatchUsageError(Exception): """Bad input from the human — reported on stderr, exit 2, nothing written.""" -def _utc_now() -> str: - return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%MZ") - - -#: How long a pushed `integration/` ref lives after the review it exists -#: for. A week is generous for a branch whose whole reason to exist is one -#: reading; longer, and the namespace becomes a graveyard nobody dares sweep. -SWEEP_DAYS = 7 - - -def sweep_after_default(review_at: str, notes: list) -> str: - """`review-at` plus a week — the default expiry of a pushed review ref. - - The review is the branch's reason to exist, so the review date is what the - expiry hangs off. An unparsable `review-at:` falls back to today plus the - same week and SAYS SO: a silently guessed deletion date is the one kind of - guess a branch sweep must never act on unexplained. - """ - try: - day = _dt.date.fromisoformat((review_at or "").strip()[:10]) - except ValueError: - notes.append(f"sweep-after: review-at {review_at or '(none)'!r} does " - f"not read as a date — defaulted to today + {SWEEP_DAYS} " - f"days; edit the record to change it") - day = _dt.datetime.now(_dt.timezone.utc).date() - return (day + _dt.timedelta(days=SWEEP_DAYS)).isoformat() - - -def _dash(line: str) -> str: - """` -- ` typed for an em dash. Records are hand-written as often as not.""" - return line.replace(" -- ", " — ") - - -#: The spellings a hand-written record's boolean key is allowed to use. -YES_WORDS = ("yes", "true", "on", "1") - - -def _yes(values) -> bool: - """Is this record key asking for something? `read_record` keeps every value - of every key in file order, so a key is a LIST; the FIRST value is the - answer and a later `- integration: no` does not un-ask it — the same rule - `collected:` follows (the first collect owns it).""" - if isinstance(values, str): - values = [values] - for v in values or []: - return str(v).strip().casefold() in YES_WORDS - return False - - -def parse_member(raw: str) -> dict | None: - """` - : — — — `, or None. - - Deliberately not a strict grammar: a `(?P\\S+)$` tail fails on every - real dev line (all nine outcomes in the 2026-08-31-pm record contain - spaces) and a `(?P\\S+)` fails on a line whose "path" is a sentence. - Splitting on the separator with `maxsplit=3` keeps the outcome whole - however long it runs — and a line whose path holds - a space is simply not this grammar, which is a NOTE, not a crash. - """ - m = MEMBER_RE.match(_dash(raw)) - if not m: - return None - fields = [f.strip() for f in m.group("rest").split(" — ", 3)] - if len(fields) != 4: - return None - path, tier, minutes, outcome = fields - if not path or " " in path: - return None - return {"slug": m.group("slug").strip(), "path": path, "tier": tier, - "minutes": minutes, "outcome": outcome} - - -def read_record(text: str) -> dict: - """One batch record, lossless and line-indexed. - - `{"keys": {k: [v…]}, "key_lines": {k: [lineno…]}, "members": [row…], - "unparsable": [(lineno, raw)…], "members_end": lineno}`. - - Every value of every key is kept, in file order (`- refreshed:` repeats once - per pull and each one is history). The body of `- notes: |` is invisible to - `keys` — which is why every write in this module edits `lines[]` in place - and nothing is ever re-serialised from this dict. - """ - keys: dict[str, list[str]] = {} - key_lines: dict[str, list[int]] = {} - members: list[dict] = [] - unparsable: list[tuple[int, str]] = [] - in_members = False - members_end = 0 - for lineno, raw in enumerate(text.split("\n"), 1): - m = RECORD_KEY.match(raw) - if m: - in_members = m.group(1) == "members" - keys.setdefault(m.group(1), []).append((m.group(2) or "").strip()) - key_lines.setdefault(m.group(1), []).append(lineno) - continue - if in_members and raw.startswith(" - "): - members_end = lineno - row = parse_member(raw) - if row is None: - unparsable.append((lineno, raw)) - else: - row.update({"lineno": lineno, "raw": raw}) - members.append(row) - elif raw.strip() and not raw.startswith(" ") and in_members: - # The continuation rule: a member list ends at the first line that - # is neither a member nor an indented wrap of one. - in_members = False - return {"keys": keys, "key_lines": key_lines, "members": members, - "unparsable": unparsable, "members_end": members_end} - - def batch_records(mind: Path) -> list[Path]: return sorted(p for p in (mind / "batches").glob("*.md") if p.name != "AGENTS.md") @@ -1036,7 +891,6 @@ def newest_slot(mind: Path) -> str: return records[-1].stem if records else "" -# ------------------------------------------------------- the other inputs --- def find_prompt(mind: Path, path: str) -> Path | None: """A member's prompt, wherever the lifecycle has moved it to. @@ -1057,69 +911,6 @@ def find_prompt(mind: Path, path: str) -> Path | None: return next(iter(sorted(mind.glob(f"complete/**/{name}"))), None) -_HEADER_LINE_RE = re.compile(r"^[A-Z][A-Za-z_ -]{0,24}:(?:\s|$)") - - -def _title_of(text: str) -> str: - for line in text.split("\n"): - if line.startswith("# "): - return line[2:].strip() - return "" - - -def _question_of(text: str) -> str: - """The first prose paragraph — what the member was dispatched to answer. - - Header keys, headings, fences and bullets are skipped rather than joined: - the packet block wants the sentence a human wrote, not the front matter. - """ - para: list[str] = [] - in_fence = False - for line in text.split("\n"): - s = line.strip() - if s.startswith("```"): - in_fence = not in_fence - continue - if in_fence: - continue - if not s: - if para: - break - continue - if (s.startswith("#") or s.startswith(("- ", "* ", "|", ">")) - or _HEADER_LINE_RE.match(s)): - if para: - break - continue - para.append(s) - return " ".join(para)[:600] - - -def prompt_facts(mind: Path, path: str) -> dict: - """What the prompt says about itself. The record's own tier and minutes - win — `grade()` is never called here, because re-sizing a task at collect - would report a member against a number nobody dispatched it under.""" - out = {"witness": None, "consequence": None, "review_minutes": None, - "repos": [], "path": path, "found": "", "title": "", "question": ""} - p = find_prompt(mind, path) - if p is None: - return out - try: - parsed = parse_prompt(p, mind) - except (OSError, ValueError, KeyError): - # A prompt that will not parse is a note on one member, never the end - # of the collect. - return out - text = parsed.get("text", "") - out.update(witness=parsed.get("witness"), - consequence=parsed.get("declared_consequence"), - review_minutes=parsed.get("declared_review_minutes"), - repos=parsed.get("repos") or [], - found=parsed.get("path") or str(p), - title=_title_of(text), question=_question_of(text)) - return out - - ACTIVE_KEY_RE = re.compile(r"^- ([a-z][a-z0-9_-]*):(?:\s+(.*?))?\s*$") @@ -1202,456 +993,6 @@ def derive_awaiting_review(mind: Path) -> int: return n -def active_for(member: dict, active: dict) -> tuple: - """`(entry, how)` — the `active.md` entry for a member, and which pass - found it. - - Three passes because the record's member slug is a dispatch label and the - registry's slug is the task's name, and they routinely differ: - `autofit-resampling-info` is registered as `resampling-info-summary-section`, - `autonerves-colab-silence` as `silence-colab-cli-message`. An unmatched - member is reported, never crashed on. - """ - slug = member.get("slug", "") - if slug in active: - return active[slug], "slug" - name = Path(member.get("path") or "").name - if name: - for entry in active.values(): - if entry["prompt"] and entry["prompt"] == name: - return entry, "prompt basename" - for entry in active.values(): - if f"member {slug}" in entry["text"]: - return entry, "named in the entry" - return None, "" - - -# -------------------------------------------------------------- evidence --- -#: The evidence file's shape, `{"schema": 1, "members": {slug: {…}}}`. Every -#: key is optional and a bare `{slug: …}` map reads too — a human assembling -#: one by hand from the GitHub MCP tools in a web session should not have to -#: get a wrapper right. -EVIDENCE_KEYS = ("prs", "witness", "adversary", "flagged", "pending", "summary") - -#: The `gh pr view --json` field list. The four `head*` fields are the -#: authoritative member -> (repo, branch) map: the record stores no branch per -#: member, so a PR's own head is the only reliable source. The head *repo* is -#: recorded too because a fork's head is not on `origin` and cannot be merged -#: from a local checkout at all. -#: `mergedAt`, NOT `merged`: `gh pr view --json` has no `merged` field (gh -#: 2.98 rejects the whole request with "Unknown JSON field", so ONE bad name -#: made every `--fetch` PR UNOBSERVABLE rather than dropping one column). The -#: timestamp is the same fact, and `merged` is derived from it below. -GH_FIELDS = ("number,url,state,additions,deletions,changedFiles,mergeable," - "mergedAt,statusCheckRollup,headRefName,headRefOid," - "headRepository,headRepositoryOwner") - - -def load_evidence(path) -> dict: - try: - data = json.loads(Path(path).read_text(encoding="utf-8")) - except OSError as e: - raise BatchUsageError(f"batch: cannot read --evidence {path}: {e}") - except json.JSONDecodeError as e: - raise BatchUsageError(f"batch: --evidence {path} is not valid JSON: {e}") - if not isinstance(data, dict): - raise BatchUsageError(f"batch: --evidence {path} must be a JSON object") - members = data.get("members") if isinstance(data.get("members"), dict) else data - return {k: v for k, v in members.items() if isinstance(v, dict)} - - -def load_evidence_doc(path) -> dict: - """The whole evidence document. `load_evidence` deliberately returns only - its members; this returns the wrapper too, because `integration` is - slot-level rather than per member — and a laptop's integration block pasted - into a cloud session is how a non-laptop surface renders one at all.""" - try: - data = json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return {} - return data if isinstance(data, dict) else {} - - -#: The integration leg lives in its own module: it is a git engine, it imports -#: nothing from here, and a session that never types `--integration` never pays -#: for it. Loaded by file location and cached, exactly like the Cortex -#: conductor below — and for the same reason. -INTEGRATION_MOD = (BRAIN / "agents" / "conductors" / "batch" / - "_integration.py") -_INTEG = None - - -def load_integration(): - global _INTEG - if _INTEG is None: - spec = importlib.util.spec_from_file_location( - "_batch_integration_leg", INTEGRATION_MOD) - mod = importlib.util.module_from_spec(spec) - spec.loader.exec_module(mod) - _INTEG = mod - return _INTEG - - -def _checks_from_rollup(rollup) -> list: - """`statusCheckRollup` — two shapes in one list. A check run reports - `status`/`conclusion`; a commit status context reports `state` only, and a - reader that knows one shape scores half of a PR's checks UNOBSERVABLE.""" - out = [] - for row in rollup or []: - if not isinstance(row, dict): - continue - name = row.get("name") or row.get("context") or "check" - if row.get("state"): - state = str(row["state"]).lower() - out.append({"name": name, "status": "completed", - "conclusion": "success" if state == "success" else state}) - else: - out.append({"name": name, - "status": str(row.get("status") or "").lower(), - "conclusion": str(row.get("conclusion") or "").lower()}) - return out - - -def _head_of(data: dict, repo: str) -> dict: - """The PR's head branch and where it lives. `headRepository` / - `headRepositoryOwner` are objects (`{"name": ...}` / `{"login": ...}`) and - either may be null on a deleted fork — a missing head is reported empty, - never guessed as `origin`, so a caller can tell "same repo" from "unknown". - """ - data = data if isinstance(data, dict) else {} - name = data.get("headRepository") - owner = data.get("headRepositoryOwner") - name = name.get("name") if isinstance(name, dict) else None - owner = owner.get("login") if isinstance(owner, dict) else None - return { - "head_ref": str(data.get("headRefName") or ""), - "head_sha": str(data.get("headRefOid") or ""), - "head_repo": f"{owner}/{name}" if owner and name else "", - } - - -def fetch_evidence(members: list, active: dict) -> tuple: - """PR evidence from `gh`, when there is a `gh`. Never writes. - - `gh` is the lane probe (`detect_lane`), so its absence is answered with one - pointer line rather than a caught 403: in a web session `gh` installs fine, - authenticates fine and then 403s every repo-scoped call - (`skills/GITHUB_ACCESS.md`), which is worse than not having it. - """ - notes: list[str] = [] - if detect_lane() != "local-dev": - notes.append( - "batch collect: no gh here — gather PR evidence with the GitHub " - "MCP tools (skills/GITHUB_ACCESS.md) and pass it as " - "--evidence .") - return {}, notes - out: dict[str, dict] = {} - for m in members: - entry, _how = active_for(m, active) - prs = [] - for url in (entry or {}).get("prs", []): - got = PR_URL_RE.match(url) - if not got: - continue - repo, number = got.group(1), got.group(2) - try: - r = subprocess.run( - ["gh", "pr", "view", number, "--repo", repo, "--json", - GH_FIELDS], capture_output=True, text=True, timeout=30) - except (OSError, subprocess.SubprocessError) as e: - notes.append(f"{m['slug']}: gh pr view {repo}#{number} could " - f"not run ({e}) — scored UNOBSERVABLE") - continue - if r.returncode != 0: - tail = (r.stderr or r.stdout).strip().splitlines() - notes.append(f"{m['slug']}: gh pr view {repo}#{number} exited " - f"{r.returncode}" + (f": {tail[-1][:120]}" if tail - else "") + " — UNOBSERVABLE") - continue - try: - data = json.loads(r.stdout) - except json.JSONDecodeError: - notes.append(f"{m['slug']}: gh returned no JSON for " - f"{repo}#{number} — UNOBSERVABLE") - continue - prs.append({ - "repo": repo, "number": data.get("number") or int(number), - "url": data.get("url") or url, "state": data.get("state"), - "additions": data.get("additions"), - "deletions": data.get("deletions"), - "changed_files": data.get("changedFiles"), - "mergeable": data.get("mergeable"), - "merged": bool(data.get("mergedAt")), - "checks": _checks_from_rollup(data.get("statusCheckRollup")), - **_head_of(data, repo), - }) - if prs: - out[m["slug"]] = {"prs": prs} - return out, notes - - -# ------------------------------------------------------------- the legs ---- -PASS, FAIL, UNOBSERVABLE = "PASS", "FAIL", "UNOBSERVABLE" - -#: The six legs, in packet order — the three `delivered:` legs of -#: `batches/AGENTS.md` (a PR, a non-empty diff, checks that ran), the green -#: reading of those checks, and the two legs `AUTONOMY.md` adds to a batch -#: launch: the pre-registered witness and the independent adversary. -LEGS = ("pr", "diff", "checks", "green", "witness", "adversary") -LEG_TITLES = { - "pr": "a PR exists", - "diff": "the diff is non-empty", - "checks": "every check completed", - "green": "every check green", - "witness": "the witness is declared, and holds", - "adversary": "an independent adversary read it", -} -GREEN_CONCLUSIONS = ("success", "neutral", "skipped") - -NO_EVIDENCE = "no evidence supplied — pass --evidence or run --fetch" - - -def _prs(ev) -> list: - return [p for p in (ev or {}).get("prs", []) if isinstance(p, dict)] - - -def _pr_label(p: dict) -> str: - return f"{p.get('repo') or '?'}#{p.get('number') or '?'}" - - -def _all_checks(prs: list) -> list: - out = [] - for p in prs: - for c in p.get("checks") or []: - if isinstance(c, dict): - out.append((p, c)) - return out - - -def leg_pr(ev) -> tuple: - if ev is None: - return UNOBSERVABLE, NO_EVIDENCE - prs = _prs(ev) - if not prs: - # The loud one. `batches/AGENTS.md`: a member that ends green with no - # PR is reported as not delivered, at the top of the packet. - return FAIL, "no PR — a session that ended green with no PR is not delivered" - return PASS, ", ".join(_pr_label(p) for p in prs) - - -def leg_diff(ev) -> tuple: - if ev is None: - return UNOBSERVABLE, NO_EVIDENCE - prs = _prs(ev) - if not prs: - return UNOBSERVABLE, "no PR to measure" - counted = [p for p in prs if any(p.get(k) is not None - for k in ("additions", "deletions", - "changed_files"))] - if not counted: - return UNOBSERVABLE, "the evidence carries no diff counts" - adds = sum(int(p.get("additions") or 0) for p in counted) - dels = sum(int(p.get("deletions") or 0) for p in counted) - files = sum(int(p.get("changed_files") or 0) for p in counted) - if adds + dels == 0 or files == 0: - return FAIL, (f"+{adds}/−{dels} over {files} file(s) — an empty diff " - "is not a delivery") - return PASS, f"+{adds}/−{dels} over {files} file(s)" - - -def leg_checks(ev, *, pending: bool) -> tuple: - if ev is None: - return UNOBSERVABLE, NO_EVIDENCE - prs = _prs(ev) - if not prs: - return UNOBSERVABLE, "no PR to check" - if not any("checks" in p for p in prs): - return UNOBSERVABLE, "the evidence records no checks" - checks = _all_checks(prs) - if not checks: - # Distinct from red, and the record's own words for it: green with - # checks that never ran is NOT DELIVERED, not FAILED. - return FAIL, "checks never ran" - unfinished = [(p, c) for p, c in checks if c.get("status") != "completed"] - if unfinished: - p, c = unfinished[0] - why = (f"{len(unfinished)} of {len(checks)} still " - f"{c.get('status') or 'queued'} ({_pr_label(p)} {c.get('name')})") - return (UNOBSERVABLE, why + " — still in flight") if pending \ - else (FAIL, why) - return PASS, f"{len(checks)} check(s) completed" - - -def leg_green(ev) -> tuple: - if ev is None: - return UNOBSERVABLE, NO_EVIDENCE - checks = _all_checks(_prs(ev)) - if not checks: - return UNOBSERVABLE, "no checks to read" - red = [(p, c) for p, c in checks - if (c.get("conclusion") or "") not in GREEN_CONCLUSIONS] - if red: - p, c = red[0] - return FAIL, (f"{_pr_label(p)} {c.get('name')}: " - f"{c.get('conclusion') or 'no conclusion'}" - + (f" (+{len(red) - 1} more)" if len(red) > 1 else "")) - return PASS, f"{len(checks)}/{len(checks)} green" - - -def leg_witness(declared, ev) -> tuple: - if not (declared or "").strip(): - return UNOBSERVABLE, "no witness declared — reviewed as `judge`" - row = (ev or {}).get("witness") - holds = row.get("holds") if isinstance(row, dict) else None - detail = (row.get("evidence") if isinstance(row, dict) else "") or "" - if holds is False: - return FAIL, f"the declared witness does not hold: {detail or declared}" - if holds is True: - return PASS, detail or declared - return UNOBSERVABLE, (f"declared (`{declared[:80]}`) but not verified here " - "— read it on the PR") - - -def leg_adversary(ev) -> tuple: - row = (ev or {}).get("adversary") - if not isinstance(row, dict) or not row.get("ran"): - return UNOBSERVABLE, "no adversary leg recorded" - model, author = (row.get("model") or ""), (row.get("author_model") or "") - # AUTONOMY.md leg 5: the leg is a reading independent of the author. A - # different model is one; so is the same model in a session that did not - # write the branch ("Adversary model default — 2026-11-22": Opus reads - # Opus by default), which the row must say — it is never assumed. - independent = row.get("independent_session") is True - if not model or not author or (model == author and not independent): - return FAIL, ("a self-run adversary leg is an absent leg, not a weak " - "one (AUTONOMY.md leg 5)" - + (f" — model {model}" if model else " — no model named")) - how = "independent session" if model == author else f"vs author {author}" - return PASS, f"{model} {how}: {row.get('verdict') or 'read'}" - - -#: Health, in the order the packet shows members in: what failed, what did not -#: arrive, what cannot be trusted, what is fine, what has not finished, what -#: already landed. `RUNNING` is the Cortex kind's word for a member whose run -#: line is still live — it is not `PENDING` (a dev member whose checks have not -#: come back), and it holds no review control at all. -HEALTHS = ("FAILED", "NOT-DELIVERED", "SUSPECT", "HEALTHY", "RUNNING", - "PENDING", "MERGED") -HEALTH_SEV = {"FAILED": "failed", "NOT-DELIVERED": "failed", - "SUSPECT": "suspect", "HEALTHY": "healthy", - "RUNNING": "running", "PENDING": "running", "MERGED": "merged"} - - -def health_of(legs: dict, *, pending: bool = False, merged: bool = False, - flagged=()) -> str: - """One member's health from its six legs. - - The three `delivered:` legs are tested BEFORE the red-check leg, which - inverts the order the legs are listed in: "checks never ran" is a FAIL on - the checks leg but `batches/AGENTS.md` calls it not-delivered, not failed, - and the distinction is the whole point of that page's first rule. - """ - verdicts = {k: legs[k][0] for k in LEGS} - if merged: - return "MERGED" - if pending: - return "PENDING" - never_ran = (verdicts["checks"] == FAIL - and "never ran" in legs["checks"][1]) - if never_ran or FAIL in (verdicts["pr"], verdicts["diff"]): - return "NOT-DELIVERED" - if FAIL in (verdicts["checks"], verdicts["green"], verdicts["witness"]): - return "FAILED" - if flagged or UNOBSERVABLE in verdicts.values(): - return "SUSPECT" - return "HEALTHY" - - -# ------------------------------------------------- the scored dev member --- -def _int(value) -> int: - try: - return int(str(value).strip()) - except (TypeError, ValueError): - return 0 - - -def _md_link(text: str, url: str) -> str: - return f"[{text}]({url})" if url else text - - -# ------------------------------------------------------ ledger outcomes --- -# What became of each member, read from the LEDGER and nothing else. Before -# this, a collected member kept whatever the record's outcome column said and -# `batches/reviews/…` recorded `decision: UNREVIEWED` for all nine members of -# the 2026-08-31-pm slot — every one of which had in fact merged. The -# completion records knew (`- batch: — member ```); nothing -# read them. -# -# Offline by construction: no `gh`, no network. The four outcomes are what the -# organism's own files can prove. -OUTCOMES = ("merged", "rejected-at-review", "carried", "unreviewed") - -#: How a `complete/` record names the batch member it shipped as. -MEMBER_CITE_RE = re.compile(r"member `([^`]+)`") - -#: A review `decision:` that rejected the member. Matched on the first word so -#: `reject`, `rejected`, `REJECTED — ` are all one ruling. -REJECT_WORDS = ("reject", "rejected") - - -def completed_members(mind: Path, slot: str = "") -> dict: - """`{member slug: complete/ record path}` — every member the completion - ledger says shipped. - - Two joins, because records are filed under the TASK's name and a batch - member carries a DISPATCH label, and they routinely differ - (`autofit-resampling-info` shipped as `resampling-info-summary-section`). - The record's own `- batch: — member ``` line is the - authoritative one; the record filename is the fallback for a member whose - task was named after it.""" - out: dict[str, str] = {} - for f in sorted(mind.glob("complete/**/*.md")): - if f.name == "index.md": - continue - try: - text = f.read_text(encoding="utf-8", errors="replace") - except OSError: - continue - rel = str(f.relative_to(mind)) - for line in text.split("\n"): - if not line.startswith("- batch:"): - continue - if slot and slot not in line: - continue - for m in MEMBER_CITE_RE.finditer(line): - out[m.group(1)] = rel - out.setdefault(f.stem, rel) - return out - - -def member_outcome(member: dict, ctx: dict) -> tuple: - """`(outcome, why)` for one member, from the ledger only. - - Order matters. A rejected member is still in `active.md` — it is work that - came back — so the review must be read before the registry, or every - rejection would report as `carried`. A merged one is read first of all: - its `complete/` record is the end of the story and outranks any row left - behind in `active.md`. - """ - slug = member.get("slug", "") - record = (ctx.get("completed") or {}).get(slug) - if record: - return "merged", f"complete/ record: {record}" - row = ((ctx.get("review") or {}).get("members") or {}).get(slug) or {} - decision = (row.get("decision") or "").strip() - if decision.split()[:1] and decision.split()[0].strip(",.:").lower() in REJECT_WORDS: - return "rejected-at-review", f"review decision: {decision}" - entry, how = active_for(member, ctx.get("active") or {}) - if entry is not None: - return "carried", f"still in active.md as `{entry['slug']}` (by {how})" - return "unreviewed", "no complete/ record, no ruling, no active.md row" - - def read_outcomes(text: str) -> dict: """The record's `- outcomes:` block as `{slug: outcome}`. @@ -1693,1479 +1034,18 @@ def previous_carried(mind: Path) -> tuple: return slot, [s for s, o in read_outcomes(text).items() if o == "carried"] -# --------------------------------------------------------- the merge order --- -def _repo_key(name: str) -> str: - """One repo, one key. A prompt header spells a library by its short name - and a PR URL spells it with the packaging prefix; a merge order that - treated those as two repos would serialise neither.""" - key = normalise_repo(name) - return key[2:] if key.startswith("pyauto") else key - - -def _member_repos(s: dict) -> list: - """Every repo this member touches, deduplicated by `_repo_key`. - - Three sources, because no single one covers a whole slot: the prompt's - `Repos:` header (absent once the prompt is absorbed into its completion - record), the PRs the evidence found, and the PR links the member's - `active.md` row carries. A member whose prompt has moved on still merges - into a repo.""" - urls = [pr.get("url") or "" for pr in s.get("prs") or []] - urls += [u for _label, u in s.get("links") or []] - names = list((s.get("facts") or {}).get("repos") or []) - names += [m.group(2) for u in urls for m in [PR_URL_RE.match(u)] if m] - out, seen = [], set() - for name in names: - key = _repo_key(name) - if key and key not in seen: - seen.add(key) - out.append(name) - return out - - -def merge_order(members: list, dispatch_order: list) -> list: - """The order to merge this slot's PRs in — advice, never an action. - - `collect` used to decline this outright ("members is sorted by HEALTH, so - it cannot drive a merge order"), which is true of that list and not of the - record: `dispatch_order` is the order the human listed the members in, and - it is stable. Three rules on top of it: - - 1. **Library first.** A workspace change is validated against the library - it calls, so the library PR lands first — the same gate `/prm` applies - (`ship_workspace`, "library-first merge gate"). - 2. **Same repo, one at a time.** The first merge moves `main` and stales - every sibling's test and CI evidence; the sequence says which sibling - is re-validated against what. - 3. **Otherwise, dispatch order**, so the sequence a human reads matches - the shift they dispatched. - - Nothing is filtered: a member with no PR is still listed, in its place, - with what it is waiting on — an order that silently omits a member is an - order somebody merges out of. - """ - def libs_of(s: dict) -> list: - return [r for r in _member_repos(s) if _repo_key(r) in LIBRARY_REPOS] - - pos = {slug: i for i, slug in enumerate(dispatch_order)} - rows = sorted(members, key=lambda s: (0 if libs_of(s) else 1, - pos.get(s["slug"], len(pos)), - s["slug"])) - out, seen = [], {} - for s in rows: - repos = _member_repos(s) - libs = libs_of(s) - shared = [(r, seen[_repo_key(r)]) for r in repos - if _repo_key(r) in seen] - why = (f"library ({', '.join(libs)}) — before its workspace dependants" - if libs else - (f"{', '.join(repos)} — after the libraries" if repos - else "no repo recorded — order is the dispatch order")) - if shared: - why += "; after " + ", ".join(f"{slug} (shares {r})" - for r, slug in shared) - if not s.get("prs") and not s.get("links"): - why += "; no PR recorded — nothing to merge yet" - out.append({"slug": s["slug"], "repos": repos, "why": why}) - for r in repos: - seen[_repo_key(r)] = s["slug"] - return out - - -def score_dev(member: dict, ctx: dict) -> dict: - """One dev member, scored. The ONLY shape the report and the renderer read. - - A `kind` is exactly this: a scorer that returns this dict and a block - builder that fills its `blocks`. Registering one is how the Cortex's - science members join a Mind packet without either side learning the - other's vocabulary. - """ - slug = member["slug"] - ev = (ctx.get("evidence") or {}).get(slug) - entry, how = active_for(member, ctx.get("active") or {}) - facts = prompt_facts(ctx["mind"], member.get("path") or "") - notes: list[str] = [] - if entry is None: - notes.append("no active.md entry matched — PR links come from the " - "evidence only") - elif how != "slug": - notes.append(f"matched active.md entry `{entry['slug']}` by {how}") - if facts["found"]: - if facts["found"] != member.get("path"): - notes.append(f"prompt found at `{facts['found']}` (the record " - f"names `{member.get('path')}`)") - elif member.get("path"): - notes.append(f"prompt `{member.get('path')}` is not in this Mind — " - "question and witness unavailable") - - prs = _prs(ev) - flagged = [str(f) for f in (ev or {}).get("flagged") or []] - merged = any(p.get("merged") for p in prs) - pending = bool((ev or {}).get("pending")) or bool( - PENDING_RE.search(member.get("outcome") or "")) - legs = { - "pr": leg_pr(ev), - "diff": leg_diff(ev), - "checks": leg_checks(ev, pending=pending), - "green": leg_green(ev), - "witness": leg_witness(facts["witness"], ev), - "adversary": leg_adversary(ev), - } - health = health_of(legs, pending=pending, merged=merged, flagged=flagged) - est = _int(member.get("minutes")) - links = [(_pr_label(p), p.get("url") or "") for p in prs] - if entry and entry["issue"]: - links.append(("issue", entry["issue"])) - for url in (entry or {}).get("prs", []): - got = PR_URL_RE.match(url) - label = f"{got.group(1)}#{got.group(2)}" if got else url - if label not in [t for t, _u in links]: - links.append((label, url)) - - s = { - "slug": slug, "kind": "dev", "id": f"m-{slug}", - "title": facts["title"] or slug.replace("-", " "), - "health": health, - "eyebrow": " · ".join(x for x in ( - ", ".join(facts["repos"]) or (entry or {}).get("slug", ""), - member.get("tier") or "", (entry or {}).get("status", "")) if x), - "jobs": " · ".join(t for t, _u in links) or "(no PR recorded)", - "chip": _chip_text(health, legs, prs), - "est_minutes": est, "tier": member.get("tier") or "", - "pending": pending, "merged": merged, "flagged": flagged, - "legs": legs, "links": links, "notes": notes, - "path": member.get("path") or "", "outcome": member.get("outcome") or "", - "prs": prs, "facts": facts, - "ruling_line": "_(one line — yours to write)_", - "review_chips": review_chips(health, pending), - "summary": (ev or {}).get("summary") or "", - } - s["blocks"] = dev_blocks(s) - return s - - -def _chip_text(health: str, legs: dict, prs: list) -> str: - if health == "MERGED": - return "merged" - if health == "PENDING": - return "PENDING — refreshed during your read" - if legs["green"][0] == PASS: - return f"PR green · {legs['green'][1]}" - if health == "NOT-DELIVERED": - return "not delivered" - return health.lower() - - -def review_chips(health: str, pending: bool) -> list: - """`Accept / Tweak / Reject / Defer`, with the first chip renamed to fit - the member — TEMPLATE.md's rule, and the values the submit schema names.""" - first = ("leave-to-finish", "Leave to finish") if pending else \ - ("structure-ok", "Structure OK") if health == "MERGED" else \ - ("merge", "Merge") - return [first, ("tweak", "Tweak"), ("reject", "Reject"), ("defer", "Defer")] - - -def dev_blocks(s: dict) -> list: - """One member's blocks, in `batches/packets/TEMPLATE.md`'s order.""" - facts = s["facts"] - blocks = [("Question this member was dispatched to answer", - facts["question"] or "_(no prompt found — see the record line)_")] - witness = facts["witness"] - blocks.append(("Witness", - (f"Declared: {witness}\n\n{s['legs']['witness'][0]} — " - f"{s['legs']['witness'][1]}") if witness else - "None declared — the review is the diff itself " - "(reviewed as `judge`).")) - if s["pending"]: - # A pending member shows what it was asked and nothing it has not - # earned: its health legs are a reading of a run still going. - blocks.append(("Status", f"PENDING — {s['outcome'] or 'in flight'}")) - return blocks - blocks.append(("Health evidence", "\n".join( - f"- {LEG_TITLES[k]} — {s['legs'][k][0]} — {s['legs'][k][1]}" - for k in LEGS))) - blocks.append(("Readout", _pr_table(s))) - blocks.append(("Ruling", s["ruling_line"])) - blocks.append(("Follow-ups", "\n".join(f"- {f}" for f in s["flagged"]) - or "_(none flagged by the run)_")) - where = [f"- {_md_link(t, u)}" for t, u in s["links"]] - if s["path"]: - where.append(f"- prompt: `{facts['found'] or s['path']}`") - # Deliberately NOT the record's outcome column: `--apply` rewrites that - # column, so a packet quoting it would differ from itself on the next - # refresh for no reason a reader could see. - blocks.append(("Where to look yourself", "\n".join(where) - or "_(nothing recorded)_")) - return blocks - - -def _pr_table(s: dict) -> str: - if not s["prs"]: - return "_(no PR evidence — nothing to read out)_" - rows = ["| PR | State | Diff | Mergeable | Checks |", "|---|---|---|---|---|"] - for p in s["prs"]: - checks = p.get("checks") - if checks is None: - cell = "not recorded" - elif not checks: - cell = "never ran" - else: - green = sum(1 for c in checks - if (c.get("conclusion") or "") in GREEN_CONCLUSIONS) - cell = f"{green}/{len(checks)} green" - diff = ("not recorded" if p.get("additions") is None - and p.get("deletions") is None else - f"+{_int(p.get('additions'))}/−{_int(p.get('deletions'))} over " - f"{_int(p.get('changed_files'))} file(s)") - rows.append(f"| {_md_link(_pr_label(p), p.get('url') or '')} " - f"| {p.get('state') or '?'} | {diff} " - f"| {p.get('mergeable') or '?'} | {cell} |") - return "\n".join(rows) - - -def kind_of(member: dict, ctx: dict) -> str: - """`dev` unless a registered kind claims the member. No other kind is - registered today, so the default is never a guess; the hook stays because - a member kind is the cheapest way for a second board to arrive.""" - for name, (_score, _blocks, claims) in ctx.get("kinds", KINDS).items(): - if claims is not None and claims(member, ctx): - return name - return "dev" - - -#: The extension point. `{name: (score, blocks, claims)}` — `score(member, ctx)` -#: returns the scored dict, `blocks(scored)` fills its `blocks`, and -#: `claims(member, ctx)` says whether this kind owns a member (None = the -#: fallback kind, which claims whatever is left). A scored dict must carry -#: `slug id kind title health eyebrow jobs chip est_minutes tier pending legs -#: blocks review_chips notes path outcome` — the report, the record and the -#: renderer read those and nothing else, which is what would let a second -#: board register a kind without either side learning the other's vocabulary. -#: -#: Six keys are OPTIONAL, each with the dev reading as its default: `leg_order` -#: and `leg_titles` (a kind whose legs are not the dev six), `reviewable` -#: (False takes the member's review controls away and drops it from the -#: progress denominator), `state`, and `pending_line`/`clean_line` (the one -#: line the rulings list shows when nothing failed). -KINDS = {"dev": (score_dev, dev_blocks, None)} - - -# --------------------------------------------------------- collect() ------- -def collect(mind: Path, slot: str, *, evidence: dict | None = None, - kinds: dict | None = None, kind: str = "dev") -> dict: - """Score one slot. Reads three inputs, writes nothing. - - The record is the spine (it is the ledger of what was dispatched); the - prompt supplies the question and the pre-registered witness; `active.md` - supplies where the work landed. Evidence — PR state, checks, the witness - verdict, the adversary leg — comes from outside, because nothing this - conductor can reach offline knows whether a PR is green. - - `kind` names the ORGAN this slot belongs to, not the member kinds in it. - One organ today — `dev`, a `PyAutoMind/batches/` record — and the member - kinds are still claimed per member. - """ - kinds = kinds or KINDS - root = mind - organ = organ_for(kind, root, slot) - record_path = root / "batches" / f"{slot}.md" - text = record_path.read_text(encoding="utf-8", errors="replace") - rec = read_record(text) - notes: list[str] = [] - for lineno, raw in rec["unparsable"]: - notes.append(f"line {lineno} does not read as a member line — reported, " - f"not scored: {raw.strip()[:140]}") - ctx = {"mind": mind, "root": root, "organ": organ, "slot": slot, - "active": read_active(mind), - "evidence": evidence or {}, "notes": notes, "kinds": kinds, - # The completion ledger, read once: `member_outcome` asks it per - # member and re-globbing `complete/**` for each one would read the - # same few hundred files ten times over. - "completed": completed_members(mind, slot)} - - review_path = root / "batches" / "reviews" / f"{slot}.md" - review = (read_review(review_path.read_text(encoding="utf-8", - errors="replace")) - if review_path.is_file() else None) - ctx["review"] = review - - scored = [] - for member in rec["members"]: - name = kind_of(member, ctx) - score, blocks, _claims = kinds.get(name) or kinds["dev"] - s = score(member, ctx) - s.setdefault("kind", name) - s.setdefault("id", f"m-{s['slug']}") - if not s.get("blocks"): - s["blocks"] = blocks(s) - if name == "dev": - # The record's outcome column is EVIDENCE (a PR number and its - # check counts); this is the ACCOUNTING — what became of the - # member. Two different questions, two different fields. - s["outcome_ledger"], s["outcome_why"] = member_outcome(member, ctx) - scored.append(s) - notes += [f"{s['slug']}: {n}" for n in s.get("notes", [])] - # Failures first, then what cannot be trusted, then the clean ones, then - # what has not finished — the order TEMPLATE.md gives the packet. Within a - # band, the most expensive review first: it is what the slot is spent on. - scored.sort(key=lambda s: (HEALTHS.index(s["health"]), -s["est_minutes"], - s["slug"])) - - counts: dict[str, int] = {} - for s in scored: - counts[s["health"]] = counts.get(s["health"], 0) + 1 - ended = [s for s in scored if not s["pending"]] - delivered = (sum(1 for s in ended if s["health"] in ("HEALTHY", "MERGED")), - len(ended)) - return { - "slot": slot, "mind": mind, "root": root, "kind": kind, - "organ": organ, - "record": str(record_path), - "members": scored, "notes": notes, "counts": counts, - "delivered": delivered, - "est_minutes": sum(s["est_minutes"] for s in scored), - "review": review, - "not_delivered": [s["slug"] for s in scored - if s["health"] == "NOT-DELIVERED"], - # Heart's release freeze, read at collect time: the packet is where a - # human decides what to merge, so the window has to be on the page. - # Empty whenever nothing is frozen (or Heart's state is absent — this - # runs on a laptop, in CI and in a web container). - "freeze": freeze_line(heart_freeze()), - "rulings": [(s["slug"], _ruling_line(s)) for s in scored], - "unparsable": rec["unparsable"], - # `members` above is sorted by HEALTH, so it cannot drive a merge - # order. Dispatch order is a property of the record — the order the - # human listed the members in — and it is the order `--integration` - # merges heads in, so the preview matches the shift. - "dispatch_order": [m["slug"] for m in rec["members"]], - # …but it CAN drive a merge order, which is what `merge_order` makes of - # it: dispatch order, library repos first, same-repo members - # serialised. Advice for the human's `/prm` sequence, never an action. - "merge_order": (merge_order(scored, [m["slug"] for m in rec["members"]]) - if kind == "dev" else []), - "outcomes": {s["slug"]: s["outcome_ledger"] for s in scored - if s.get("outcome_ledger")}, - "integration_requested": _yes(rec["keys"].get("integration")), - # Read for `--push` only: `review-at` is what the default expiry of a - # published ref hangs off, and a `sweep-after:` the human wrote is - # theirs and wins over that default. - "review_at": (rec["keys"].get("review-at") or [""])[0].strip(), - "sweep_after": (rec["keys"].get("sweep-after") or [""])[0].strip(), - "stamp": "", - } - - -def _ruling_line(s: dict) -> str: - """The one-line "why this needs you" for the rulings list. - - The legs are read through `leg_order`/`leg_titles` rather than the dev - constants, so a kind whose legs are not the dev six reads correctly here - instead of raising `KeyError` on every one of them. - """ - order = s.get("leg_order", LEGS) - titles = s.get("leg_titles", LEG_TITLES) - for k in order: - if s["legs"][k][0] == FAIL: - return f"{s['health']} — {titles[k]}: {s['legs'][k][1]}" - if s["pending"]: - return s.get("pending_line") or ( - "PENDING — not finished at collect; refreshed during your read") - for k in order: - if s["legs"][k][0] == UNOBSERVABLE: - return f"{s['health']} — {titles[k]}: {s['legs'][k][1]}" - clean = s.get("clean_line") or ( - f"{s['legs']['green'][1]}; merge / tweak / reject") - return f"{s['health']} — {clean}" - - -# ------------------------------------------------------- report and JSON --- -def _integ_detail(r: dict) -> str: - """One repo's outcome, minus its name and its status word — what the packet - puts after the chip and the report puts after both. Written once so the - terminal and the page cannot report the same merge differently.""" - if r.get("status") == "skipped": - return r.get("note") or "nothing to cut from" - merged = ", ".join(r.get("merged") or []) - detail = (f"{r.get('branch')} — {len(r.get('merged') or [])} member(s) " - "merged" + (f": {merged}" if merged else "")) - for c in r.get("conflicts") or []: - paths = ", ".join(c.get("paths") or []) or "(no paths reported)" - detail += (f"; {c['member']} ({c['branch']}) collides on {paths} — " - "left out") - if r.get("pushed") and r.get("remote_branch"): - detail += f"; pushed to origin/{r['remote_branch']}" - if r.get("push_note"): - detail += f" ({r['push_note']})" - elif r.get("push_note"): - detail += f"; NOT pushed — {r['push_note']}" - return detail - - -def _integ_line(r: dict) -> str: - return f"{r.get('repo', '')} — {r.get('status', '')} — {_integ_detail(r)}" - - -def _integration_report(d: dict) -> list: - """The copy-paste line first, at the top of the report: the whole point of - the leg is that the human can RUN the batch, and a `source …` line five - screens down is a line nobody sources.""" - block = d.get("integration") - if not block: - return [] - L = ["## Integration branches", "", - f"Run the whole batch: `source {block.get('activate', '')}`", ""] - if block.get("pushed"): - L += [f"Pushed for review; the branch sweep may delete these after " - f"**{block.get('sweep_after') or '(no sweep-after)'}**. Never a " - f"PR, never a base.", ""] - L += [f"- {_integ_line(r)}" for r in block.get("repos") or []] - return L + [""] - - -#: PyAutoHeart's freeze flag, read straight off its sidecar. Brain never -#: writes it — Heart owns the file (`PyAutoHeart/heart/freeze.py`), and this is -#: a read of state that lives on the same box, in the same spirit as the -#: profiling conductor's read of `~/.pyauto-heart`. A shell-out to -#: `pyauto-heart freeze --show --json` would say the same thing; the file read -#: keeps `collect` runnable where Heart is not on PATH. -HEART_STATE_DIR = Path(os.environ.get("HEART_STATE_DIR") - or Path.home() / ".pyauto-heart") - - -def heart_freeze(now: _dt.datetime | None = None, - state_dir: Path | None = None) -> dict: - """`{"state": clear|active|expired, ...}` — Heart's reading, re-derived. - - Expiry is applied here rather than trusted from the file, so a flag whose - window has passed reads as thawed even if nobody cleared it. Anything - unreadable reads as clear: a freeze nobody can parse must not be able to - stop a batch from being collected. - """ - path = (state_dir or HEART_STATE_DIR) / "freeze.json" - try: - rec = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError): - return {"state": "clear"} - if not isinstance(rec, dict): - return {"state": "clear"} - try: - until = _dt.datetime.fromisoformat(str(rec.get("until", "")).replace("Z", "+00:00")) - except ValueError: - return {"state": "clear"} - if until.tzinfo is None: - until = until.replace(tzinfo=_dt.timezone.utc) - ref = now or _dt.datetime.now(_dt.timezone.utc) - return {**rec, "state": "active" if ref < until else "expired"} - - -def collect_report(d: dict) -> str: - L = [f"# Batch collect {d['slot']}", ""] - if d["not_delivered"]: - # First and loud, per `batches/AGENTS.md` — this is the one finding a - # human must not have to scroll for. - n, total = len(d["not_delivered"]), d["delivered"][1] - by_slug = {s["slug"]: s for s in d["members"]} - why = ", ".join( - f"{slug} ({_short(by_slug[slug]['legs']['pr'][1] if by_slug[slug]['legs']['pr'][0] == FAIL else _evidence_line(by_slug[slug]))})" - for slug in d["not_delivered"]) - L += [f"**NOT DELIVERED — {n} of {total}**: {why}", ""] - if d.get("freeze"): - # One line, above the members: whoever reads this packet is deciding - # what to merge, and a library merge landing inside a validation window - # restales the whole rehearsal. `/prm` is what actually stops. - L += [f"**{d['freeze']}** — library `main`s are frozen; `/prm` will " - "refuse a library PR until it clears (`--thaw` overrides, " - "logged).", ""] - L += _integration_report(d) - L += _merge_order_report(d) - for s in d["members"]: - L += _member_report(s) - if d["review"] is not None: - L += ["## Review submitted", "", - f"`batches/reviews/{d['slot']}.md` exists — the packet is not " - "rewritten after a review. Decisions are reported, never enacted:", - ""] - for slug, row in d["review"]["members"].items(): - L.append(f"- {slug}: {row['decision'] or '(none)'} " - f"(ruled {row['ruled'] or 'no'})") - L.append("") - if d["notes"]: - L += ["## Notes", ""] + [f"- {n}" for n in d["notes"]] + [""] - return "\n".join(L) + "\n" - - -def _merge_order_report(d: dict) -> list: - """The `/prm` sequence, said once, near the top — it is read before any - member is opened, and it is the whole reason `dispatch_order` is kept.""" - if not d.get("merge_order"): - return [] - L = ["## Merge order", "", - "Advice for your `/prm` sequence — nothing here is enacted:", ""] - for i, row in enumerate(d["merge_order"], 1): - L.append(f"{i}. **{row['slug']}** — {row['why']}") - return L + [""] - - -def _member_report(s: dict) -> list: - L = [f"## {s['slug']} — {s['health']}", ""] - facets = [x for x in (f"`{s['path']}`" if s["path"] else "", s["eyebrow"], - f"{s['est_minutes']} est. review-minutes", - (f"outcome: {s['outcome_ledger']} " - f"({s.get('outcome_why', '')})") - if s.get("outcome_ledger") else "") if x] - L += [" — ".join(facets), ""] - for label, body in s["blocks"]: - L += [f"**{label}**", "", body, ""] - return L - - -def _short(text: str, limit: int = 90) -> str: - text = " ".join(str(text).split()) - return text if len(text) <= limit else text[:limit - 1] + "…" - - -def emit_collect(d: dict, out: str = "") -> None: - n, total = d["delivered"] - print(f"collect {d['slot']}: {len(d['members'])} members, " - f"delivered {n}/{total}") - if d.get("freeze"): - print(d["freeze"]) - body = collect_report(d) - if out: - Path(out).write_text(body, encoding="utf-8") - print(f"Wrote: {out}") - else: - print(body, end="") - - -# ------------------------------------------------------------ the packet --- -def _asset(name: str) -> str: - """The CSS and JS live beside this file. They are full of `{`, `}` and `%` - — every one of which a `.format`/`%`/`Template` pass would eat — so they - are read verbatim and only `%%TOKEN%%` placeholders are substituted.""" - return (Path(__file__).resolve().parent / name).read_text(encoding="utf-8") - - -def _e(value) -> str: - return html.escape(str(value), quote=True) - - -_MD_LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)\s]+)\)") -_MD_CODE_RE = re.compile(r"`([^`]+)`") -_MD_BOLD_RE = re.compile(r"\*\*([^*]+)\*\*") -_MD_EM_RE = re.compile(r"(? str: - """Inline markdown → HTML, escaped FIRST so nothing in a record, a prompt - or a check name can inject markup. (Escaping first also means a `&` inside - a link target arrives as `&`; no url this page emits carries one.)""" - out = _e(text) - out = _MD_LINK_RE.sub(lambda m: f'{m.group(1)}', - out) - out = _MD_CODE_RE.sub(lambda m: f"{m.group(1)}", out) - out = _MD_BOLD_RE.sub(lambda m: f"{m.group(1)}", out) - out = _MD_EM_RE.sub(lambda m: f"{m.group(1)}", out) - return out - - -def _md_table(rows: list) -> str: - cells = [[c.strip() for c in row.strip().strip("|").split("|")] - for row in rows] - head, body = cells[0], cells[2:] if len(cells) > 1 else [] - out = ['
', ""] - out += [f"" for c in head] - out += ["", ""] - for row in body: - out.append("" + "".join(f"" for c in row) - + "") - out += ["", "
{_inline(c)}
{_inline(c)}
"] - return "".join(out) - - -def _md_to_html(body: str) -> str: - """The small subset the blocks are written in: paragraphs, `- ` lists and - pipe tables. One block shape feeds the markdown report and this page, so - neither surface can drift from the other.""" - lines = body.split("\n") - out, i = [], 0 - while i < len(lines): - line = lines[i] - if line.startswith("|"): - block = [] - while i < len(lines) and lines[i].startswith("|"): - block.append(lines[i]) - i += 1 - out.append(_md_table(block)) - continue - if line.startswith("- "): - items = [] - while i < len(lines) and lines[i].startswith("- "): - items.append(_inline(lines[i][2:])) - i += 1 - out.append("
    " + "".join(f"
  • {x}
  • " for x in items) - + "
") - continue - if not line.strip(): - i += 1 - continue - para = [] - while (i < len(lines) and lines[i].strip() - and not lines[i].startswith(("- ", "|"))): - para.append(lines[i].strip()) - i += 1 - out.append(f"

{_inline(' '.join(para))}

") - return "\n".join(out) - - -def render_member_section(s: dict) -> str: - """One `
`, self-contained. - - Self-contained is load-bearing: the refresh replaces exactly this span and - nothing else, so everything a member needs — including its review controls, - whose state the human may already have typed — has to live inside it. - - A member that is not `reviewable` renders with no Ruled box and no decision - chips — a kind may declare that a member cannot be ruled on yet. The note - textarea stays, because a human starts noting on a member long before it - finishes. - """ - sev = HEALTH_SEV.get(s["health"], "suspect") - reviewable = s.get("reviewable", True) - if not reviewable: - classes, chip_cls = "member running", "chip-running" - elif s["pending"]: - classes, chip_cls = "member pending", "chip-pending" - else: - classes, chip_cls = "member", f"chip-{sev}" - mid = _e(s["id"]) - L = [f'
', - '
', - '
', - f'

{_e(s["eyebrow"] or s["kind"])}

', - f'

{_e(s["title"])}

', - f'

{_e(s["jobs"])}

', - '
', - '
', - f' {_e(s["chip"])}'] - if reviewable: - L.append(f' ') - L += ['
', - '
', - '
'] - for label, body in s["blocks"]: - if label == "Ruling": - L += ['
', - '

Ruling

', - f'

{_inline(body)}

', - '
'] - continue - L += ['
', - f'

{_e(label)}

', - _indent(_md_to_html(body), 6), - '
'] - # Present on PENDING members too, deliberately: the reference packet found - # that a human starts noting on a running member long before it finishes, - # and a refresh that withheld the controls would drop those notes. - L += ['
', - '

Your review

'] - if reviewable: - L.append('
') - for value, label in s["review_chips"]: - L.append(f' ') - L.append('
') - else: - L.append('

Still running — no review control ' - 'until its results are pulled. A note here is kept.

') - L += [f' ', - '
', - f'

Est. {_e(s["est_minutes"])} ' - f'review-minutes · {_e(s["tier"] or s["kind"])}

', - '
', - '
'] - return "\n".join(L) - - -def _indent(text: str, spaces: int) -> str: - pad = " " * spaces - return "\n".join(pad + ln if ln.strip() else ln for ln in text.split("\n")) - - -def section_span(html_text: str, member_id: str) -> tuple | None: - """`(start, end)` of the member section carrying this id, `
` - included — depth-aware, because a member block may nest a section.""" - needle = f'id="{member_id}"' - pos = 0 - while True: - start = html_text.find("", start) - if gt < 0: - return None - tag = html_text[start:gt] - if 'class="member' in tag and needle in tag: - depth, i = 0, start - while i < len(html_text): - nxt_open = html_text.find("", i) - if nxt_close < 0: - return None - if 0 <= nxt_open < nxt_close: - depth += 1 - i = nxt_open + len("") - if depth == 0: - return start, i - return None - pos = gt + 1 - - -def _member_spans(html_text: str) -> list: - """Every member section in the page, in page order.""" - spans, pos = [], 0 - while True: - start = html_text.find("", start) - if gt < 0: - return spans - tag = html_text[start:gt] - got = re.search(r'id="([^"]+)"', tag) - if 'class="member' in tag and got: - span = section_span(html_text, got.group(1)) - if span: - spans.append((span[0], span[1], got.group(1))) - pos = span[1] - continue - pos = gt + 1 - - -def splice(html_text: str, start: int, end: int, new: str) -> str: - return html_text[:start] + new + html_text[end:] - - -def replace_region(html_text: str, name: str, new: str) -> tuple: - """Rewrite one sentinelled region. `(html, replaced)` — a page with no - sentinels for it is left ALONE, never guessed at.""" - begin, end = f"", f"" - i, j = html_text.find(begin), html_text.find(end) - if i < 0 or j < 0 or j < i: - return html_text, False - return (html_text[:i + len(begin)] + "\n" + new.strip("\n") + "\n" - + html_text[j:]), True - - -_GENERATED_RE = re.compile(r"Generated ([^·<]+)") - - -def _mind_home(mind: Path) -> str: - """`https://github.com//PyAutoMind`, read from the checkout rather - than named here — a fork's packets must point at the fork, and organ code - names no GitHub owner (the Mind's tenant firewall). The `origin` remote is - tried first, then a page that travels with the repo; with neither there is - no home, and the packet's Commit-on-GitHub button says so instead of - guessing one.""" - try: - r = subprocess.run(["git", "-C", str(mind), "config", "--get", - "remote.origin.url"], capture_output=True, - text=True, timeout=10) - m = re.search(r"github\.com[:/]([\w.-]+)/PyAutoMind", r.stdout) - if r.returncode == 0 and m: - return f"https://github.com/{m.group(1)}/PyAutoMind" - except (OSError, subprocess.SubprocessError): - pass - for name in ("README.md", "AGENTS.md"): - f = mind / name - if f.is_file(): - m = re.search(r"https://github\.com/([\w.-]+)/PyAutoMind", - f.read_text(encoding="utf-8", errors="replace")) - if m: - return f"https://github.com/{m.group(1)}/PyAutoMind" - return "" - - -def _tiles(d: dict) -> str: - L = ['
', - f'
{len(d["members"])}' - 'Members
'] - for health in HEALTHS: - n = d["counts"].get(health, 0) - if not n: - continue - L.append(f'
' - f'{n}' - f'{_e(health.title())}
') - total = d["est_minutes"] - addition = " + ".join(str(s["est_minutes"]) for s in d["members"]) or "0" - L += ['
', - f' {total}', - ' Est. review-minutes', - f' {_e(addition)}', - f' delivered {d["delivered"][0]} of ' - f'{d["delivered"][1]} ended member(s)', - '
', '
'] - return "\n".join(L) - - -def _rulings(d: dict) -> str: - L = ['
', '

Rulings needed

', - '
    '] - for slug, line in d["rulings"]: - L.append(f'
  1. ' - f'{_e(slug)} — {_e(line)}
  2. ') - if not d["rulings"]: - L.append("
  3. No members in this record.
  4. ") - L += ['
', '
'] - return "\n".join(L) - - -CHIP_FOR_STATUS = {"clean": "chip-healthy", "conflicted": "chip-failed", - "skipped": "chip-pending"} - - -def _integration_panel(d: dict) -> str: - """The integration block, rendered. Every value goes through `_e` and the - panel carries no `data-*` hook: `packet.js` queries `[data-ruled]`, - `[data-decision]`, `[data-note]` and `[data-meta]` only, and there is - nothing for the human to *rule* about a merge preview — it is a finding they - read, not a control they operate.""" - block = d.get("integration") - if not block: - return "" - root = block.get("root", "") - # The lede tells the truth about THIS block: "nothing is pushed" is a - # promise the panel may no longer be able to make. - pushed = bool(block.get("pushed")) - lede = ('One throwaway worktree root merges every member's head ' - 'branch per repo, off origin/main. ' - + ('Nothing is resolved: a member whose merge conflicts is left ' - 'out and named.' if pushed else - 'Nothing is pushed and nothing is resolved: a member whose ' - 'merge conflicts is left out and named.')) - L = ['
', - '

Integration branches

', - f'

{lede}

', - f'

source {_e(block.get("activate", ""))}

'] - if pushed: - L.append( - '

Pushed for review; the branch sweep may ' - 'delete these after ' - f'{_e(block.get("sweep_after") or "(no sweep-after)")}. ' - 'Never a PR, never a base. A pushed branch carries only the ' - 'members that merged — each one named left out below ' - 'is not in it.

') - L += ['

Once that is sourced, a library ' - 'change is live anywhere — it is on the PYTHONPATH. A ' - 'workspace member is a real worktree but is not on the ' - 'PYTHONPATH, so run its script from inside ' - f'{_e(root)}/<workspace>.

', - '
    '] - for r in block.get("repos") or []: - status = str(r.get("status") or "") - chip = CHIP_FOR_STATUS.get(status, "chip-pending") - L.append(f'
  • {_e(r.get("repo", ""))} ' - f'{_e(status)} — ' - f'{_e(_integ_detail(r))}
  • ') - if not (block.get("repos") or []): - L.append("
  • No repo had a mergeable member head.
  • ") - L += ['
', '
'] - return "\n".join(L) - - -def _sidenav(d: dict) -> str: - L = [''] - return "\n".join(L) - - -def _organ(d: dict) -> dict: - """The organ this packet belongs to. A `d` assembled by hand (a test, an - older caller) still renders: the Mind is the default, as it always was.""" - return d.get("organ") or organ_for("dev", d.get("mind") or Path("."), - d["slot"]) - - -def _members_js(d: dict) -> str: - # Packet pages are standalone and do not embed the family click handler. - sys.path.insert(0, str(BRAIN / "board")) - from _theme import PROMPT_GUARD_JS - - members = [{"id": s["id"], "slug": s["slug"], "health": s["health"], - "reviewable": s.get("reviewable", True)} - for s in d["members"]] - # `<` escaped to its JSON `\u003c` escape — still valid JSON, and the one - # thing that keeps a slug reading `` from ending the script tag - # early. Every other interpolation goes through `_e`; this one cannot, - # because it must stay parseable JSON. - payload = json.dumps(members, indent=2, ensure_ascii=False).replace( - "<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026") - js = _asset("packet.js") - organ = _organ(d) - home = organ["home"] - for token, value in ( - ("%%MEMBERS_JSON%%", payload), - ("%%SLOT%%", d["slot"]), - ("%%PACKET_PATH%%", organ["packet_path"]), - ("%%REVIEW_PATH%%", organ["review_path"]), - ("%%FOLLOWUPS_HEADING%%", organ["followups_heading"]), - ("%%DEFAULT_DECISION%%", organ["default_decision"]), - ("%%GITHUB_NEW%%", (f"{home}/new/main" if home else ""))): - js = js.replace(token, value) - return "" - - -def _callout(d: dict) -> str: - if d["not_delivered"]: - by_slug = {s["slug"]: s for s in d["members"]} - items = "".join( - f"
  • {_e(slug)} — " - f"{_e(_short(_evidence_line(by_slug[slug]), 140))}
  • " - for slug in d["not_delivered"]) - return (f'
    ' - f'\n

    Most important finding

    \n' - f'

    {len(d["not_delivered"])} member(s) did not deliver. A ' - f'session that ends green is not a delivered task — these have ' - f'no PR, an empty diff, or checks that never ran.

    \n' - f'
      {items}
    \n
    ') - return ('
    \n' - '

    Most important finding

    \n' - f'

    Every ended member of this slot produced a PR with a ' - f'non-empty diff and checks that ran. ' - f'{_e(d["counts"].get("SUSPECT", 0))} still need your eyes for a ' - f'leg the collect could not observe.

    \n
    ') - - -def _stamp_block(d: dict, generated: str, stamp: str) -> str: - return "\n".join([ - f'

    Generated {_e(generated)} · refreshed ' - f'{_e(stamp)}

    ', - f'

    Permanent home: ' - f'batches/packets/{_e(d["slot"])}.html

    ']) - - -PACKET_HEAD = """ - - - - -Slot Review %%SLOT%% - - - - -""" - - -def _fresh_packet(d: dict, stamp: str) -> str: - slot = d["slot"] - head = PACKET_HEAD.replace("%%CSS%%", _asset("packet.css")).replace( - "%%SLOT%%", _e(slot)) - organ = _organ(d) - n, total = d["delivered"] - # The progress line counts what can actually be ruled: a member with no - # review control would leave a denominator that never reaches "all - # decided" however complete the review was. - votes = sum(1 for s in d["members"] if s.get("reviewable", True)) - L = [head, '
    ', '', '
    ', - f'

    {_e(slot)} · batch collect · ' - f'{len(d["members"])} member(s)

    ', - f'

    Slot Review — {_e(slot)}

    ', - '

    ' - + organ["lede"].format(n=n, total=total) - + ' Choose a decision and leave a note on each member, then ' - 'Submit review at the bottom; the review lands in ' - f'{_e(organ["review_path"])} for the orchestrator to ' - 'enact.

    ', - '', - _stamp_block(d, stamp, stamp), - '', - '
    ', '', - '', _tiles(d), '', - '', - '
    ', - '
    ', - ' ', - ' ', - '
    ', - '
    ', - ' ', - ' ', - '
    ', - '

    The minutes figure is the only calibration ' - 'the review-cost estimate ever gets.

    ', - '
    ', '', - _callout(d), '', - '', _rulings(d), - '', '', - # The sentinels ship even when the body is empty, so a LATER - # `--integration` refresh of this same page has somewhere to splice - # into. A region that only appears once it has content can never be - # filled in place. - '', _integration_panel(d), - '', '', - '
    ', '', - '', _sidenav(d), - '', '', - '
    ', '', - ''] - for s in d["members"]: - L += [render_member_section(s), ''] - L += ['', '', - '
    ', '
    ', '', - '
    ', - '
    ', '', - '
    ', - f'

    Ruled 0 of ' - f'{votes} · decisions 0 of {votes}

    ', - ' ', - '
    ', '', - '', '', - '', _members_js(d), - '', '', - '', '', ''] - return "\n".join(L) - - -def packet_html(d: dict, existing: str | None = None) -> tuple: - """`(html, notes)` — the packet page, fresh or refreshed IN PLACE. - - A refresh never rewrites the page: it replaces each member's own section - and the regenerable regions between their sentinels, and leaves every other - byte alone. That is what lets the human keep reading a packet while the - overnight members fill in under them, and it is why an archived - hand-authored page (no sentinels) degrades to member splices plus a note - rather than being regenerated wholesale. - """ - stamp = d.get("stamp") or _utc_now() - if existing is None: - return _fresh_packet(d, stamp), [] - notes: list[str] = [] - out = existing - generated = (_GENERATED_RE.search(existing).group(1).strip() - if _GENERATED_RE.search(existing) else stamp) - missing = [] - for s in d["members"]: - span = section_span(out, s["id"]) - if span: - out = splice(out, span[0], span[1], render_member_section(s)) - else: - missing.append(s) - if missing: - block = "\n".join(render_member_section(s) for s in missing) + "\n" - at = out.find("") - if at >= 0: - out = out[:at] + block + out[at:] - else: - spans = _member_spans(out) - at = spans[-1][1] if spans else out.find("") - if at < 0: - at = len(out) - out = out[:at] + "\n" + block + out[at:] - notes.append( - f"packet has no pyauto:members sentinels — {len(missing)} new " - "member section(s) appended after the last existing one; this " - "page was not written by this renderer") - regions = [ - ("stamp", _stamp_block(d, generated, stamp), "header stamp"), - ("tiles", _tiles(d), "stat tiles"), - ("rulings", _rulings(d), "rulings list"), - ("sidenav", _sidenav(d), "sidenav"), - ("members-js", _members_js(d), "MEMBERS array"), - ] - # Only when this collect HAS an integration block. A plain refresh must not - # blank the region the last `--integration` filled: the merge preview is - # still true, and the human is reading it. - if d.get("integration"): - regions.append(("integration", _integration_panel(d), - "integration branches")) - for name, new, what in regions: - out, ok = replace_region(out, name, new) - if not ok: - notes.append(f"packet has no pyauto:{name} sentinels — member " - f"sections refreshed, {what} left alone") - return out, notes - - -# ------------------------------------------------------------- the record --- -def _evidence_line(s: dict) -> str: - """The one line the record's outcome column carries — the first leg that - explains the health, never a summary of all six.""" - order = s.get("leg_order", LEGS) - titles = s.get("leg_titles", LEG_TITLES) - for k in order: - if s["legs"][k][0] == FAIL: - return _short(f"{titles[k]}: {s['legs'][k][1]}", 160) - if s["pending"]: - return _short(s["outcome"] or "still in flight", 160) - for k in order: - if s["legs"][k][0] == UNOBSERVABLE: - return _short(f"{titles[k]}: {s['legs'][k][1]}", 160) - if s.get("clean_line"): - return _short(s["clean_line"], 160) - return _short(f"{s['legs']['pr'][1]}; {s['legs']['green'][1]}", 160) - - -def _set_key(lines: list, rec: dict, key: str, value: str, - inserts: list) -> None: - """Replace the first line for this key in place, or queue an insert. Key - ORDER varies between records (the am record writes `packet:` before - `collected:`), so nothing here may assume a position.""" - line = f"- {key}: {value}" - if rec["key_lines"].get(key): - lines[rec["key_lines"][key][0] - 1] = line - else: - inserts.append(line) - - -def _insert_anchor(rec: dict) -> int: - """Where a new key goes: immediately before `- notes:` when there is one. - Never inside or after that block — its body is prose, and a `- key:` line - indented into it is not a key at all.""" - notes = rec["key_lines"].get("notes") - if notes: - return notes[0] - 1 - last = rec["members_end"] - for linenos in rec["key_lines"].values(): - last = max(last, max(linenos)) - return last - - -#: A line the block writer has replaced. Dropped in the LAST pass of -#: `record_update`, after the inserts have landed, so no index-based write in -#: this module ever sees a list whose length has changed under it. -_DROPPED = "\x00dropped" - - -def _set_block(lines: list, rec: dict, key: str, values: list, inserts: list, - *, fill: bool = False) -> None: - """Write `- :` followed by its indented ` - ` entries. - - The record's other writes are one line each; these two blocks are not. An - existing block is replaced whole (its old body lines are marked `_DROPPED`, - never deleted in place — see that constant), and `fill=True` leaves one - that is already there alone, which is what a CLOSED record needs: its - contents are history.""" - body = "\n".join([f"- {key}:"] + [f" - {v}" for v in values]) - linenos = rec["key_lines"].get(key) - if not linenos: - inserts.append(body) - return - if fill: - return - start = linenos[0] - 1 - lines[start] = body - i = start + 1 - while i < len(lines) and lines[i].startswith(" - "): - lines[i] = _DROPPED - i += 1 - - -def _fill_key(lines: list, rec: dict, key: str, value: str, - inserts: list) -> None: - """Like `_set_key`, but only where the record has no value yet (or the - placeholder `(not given)`). The close leg fills what the human left blank; - a `reviewed-at:` someone already wrote — the pm record's carries a whole - clause about where the review sat — is theirs, and stays.""" - have = [v for v in rec["keys"].get(key, []) if v and v != "(not given)"] - if not have: - _set_key(lines, rec, key, value, inserts) - - -def record_update(text: str, d: dict, stamp: str) -> str: - """The batch record, updated in place — line by line, never re-serialised. - - A member whose outcome already opens with a ruling word is left exactly as - it is: the am record's `REJECTED`/`ACCEPTED` lines are a review that - happened, and this verb's own earlier verdicts are the same. Rewriting one - would erase a human's sentence with a machine's. And once the slot's - review has landed, NO member line changes: the record is the history of a - batch that closed, and the pm record's `PR OPENED AT REVIEW (…)` sentences - are exactly the kind of outcome no word list would have protected. - """ - lines = text.split("\n") - rec = read_record(text) - by_slug = {m["slug"]: m for m in rec["members"]} - closed = d.get("review") is not None - for s in d["members"]: - m = by_slug.get(s["slug"]) - if m is None or closed: - continue - words = (m["outcome"] or "").split() - first = words[0].strip("(,.").upper() if words else "" - if first in RULING_WORDS: - continue - lines[m["lineno"] - 1] = ( - f" - {s['slug']}: {m['path']} — {m['tier']} — {m['minutes']} — " - f"{s['health']} ({_evidence_line(s)})") - - inserts: list[str] = [] - if not rec["key_lines"].get("collected"): - inserts.append(f"- collected: {stamp}") - n, total = d["delivered"] - # An open batch's `delivered:`/`packet:` are collect's own and move with - # every apply; a closed batch's are history (the pm record's `delivered:` - # is a sentence about what the shift produced) and are filled, not set. - put = _fill_key if closed else _set_key - put(lines, rec, "delivered", f"{n}/{total}", inserts) - put(lines, rec, "packet", f"batches/packets/{d['slot']}.html", inserts) - block = d.get("integration") - if block and not closed: - # A SEPARATE key from the dispatch-time `- integration: yes`. That line - # is the human's REQUEST; overwriting it with a path would erase what - # they asked for and leave only what happened. - clean = sum(1 for r in block.get("repos") or [] - if r.get("status") == "clean") - bad = sum(1 for r in block.get("repos") or [] - if r.get("status") == "conflicted") - _set_key(lines, rec, "integration-root", - f"{block.get('root', '')} — {block.get('branch', '')}; " - f"{clean} clean, {bad} conflicted", inserts) - # What was PUBLISHED, per repo, under the name `branch_sweep.sh --name` - # matches on. Rewritten on every push, because the current publication - # is the truth; `sweep-after:` is filled once and never overwritten, - # because the date a human typed is a decision about their own review. - remotes = [f"{r['dir']}:{r['remote_branch']}" - for r in block.get("repos") or [] if r.get("remote_branch")] - if remotes: - _set_key(lines, rec, "integration-remote", ", ".join(remotes), - inserts) - if block.get("sweep_after"): - _fill_key(lines, rec, "sweep-after", block["sweep_after"], - inserts) - review = d.get("review") - if review is not None: - _fill_key(lines, rec, "review", - f"batches/reviews/{d['slot']}.md", inserts) - reviewed_at = review["keys"].get("reviewed-at", "") - if reviewed_at: - _fill_key(lines, rec, "reviewed-at", reviewed_at, inserts) - minutes = review["keys"].get("review-minutes-actual", "") - if minutes and minutes != "(not given)": - _fill_key(lines, rec, "review-minutes-actual", minutes, inserts) - # The accounting and the advice. Both are DERIVED — from the completion - # ledger, the review file and `active.md` — so on an open record they are - # rewritten on every apply; on a closed one they are written once and left, - # like `delivered:` and `packet:` above. - if d.get("outcomes"): - _set_block(lines, rec, "outcomes", - [f"{slug}: {outcome}" - for slug, outcome in d["outcomes"].items()], - inserts, fill=closed) - if d.get("merge_order"): - _set_block(lines, rec, "merge-order", - [f"{i}. {row['slug']} — {row['why']}" - for i, row in enumerate(d["merge_order"], 1)], - inserts, fill=closed) - inserts.append(f"- refreshed: {stamp} — collect " - f"({len(d['members'])} member(s))") - at = _insert_anchor(rec) - lines[at:at] = inserts - return "\n".join(ln for ln in lines if ln != _DROPPED) - - -def apply_collect(mind: Path, d: dict, stamp: str) -> list: - """Write the record and the packet. Returns the notes; writes nothing when - the rehearsal finds the rewritten record has lost anything.""" - notes: list[str] = [] - record = mind / "batches" / f"{d['slot']}.md" - before = record.read_text(encoding="utf-8", errors="replace") - after = record_update(before, d, stamp) - problems = _rehearse_record(mind, before, after) - if problems: - return [f"record NOT written — the rewrite loses something: {p}" - for p in problems] - record.write_text(after, encoding="utf-8") - notes.append(f"record updated: batches/{d['slot']}.md") - return notes + _apply_packet(mind, d) - - -def _apply_packet(root: Path, d: dict) -> list: - """The packet leg of an apply — the same one for both organs, because the - page is the same page. Written under the organ's own `batches/packets/`.""" - notes: list[str] = [] - packet = root / "batches" / "packets" / f"{d['slot']}.html" - if d.get("review") is not None: - # `batches/packets/AGENTS.md`: the archived page and the review file are - # the audit pair — what was shown, what was ruled. A correction gets a - # new dated page, not an edit. A dev batch is reviewed once — this is - # the WHOLE close. - notes.append("review submitted — the packet is never rewritten after a " - f"review; batches/reviews/{d['slot']}.md is the record now") - return notes - existing = (packet.read_text(encoding="utf-8", errors="replace") - if packet.is_file() else None) - page, pnotes = packet_html(d, existing) - packet.parent.mkdir(parents=True, exist_ok=True) - packet.write_text(page, encoding="utf-8") - notes += pnotes - notes.append(("packet refreshed" if existing is not None - else "packet written") + f": batches/packets/{d['slot']}.html") - return notes - - -def _rehearse_record(mind: Path, before: str, after: str) -> list: - """Re-read the rewritten record from a throwaway copy of `batches/` before - it is written for real. The Cortex's collect does the same, for the same - reason: a partial write of a ledger has no way back.""" - tmp = Path(tempfile.mkdtemp(prefix="batch-collect-")) - try: - copy = tmp / "batches" - shutil.copytree(mind / "batches", copy, symlinks=True) - rehearsal = copy / "rehearsal.md" - rehearsal.write_text(after, encoding="utf-8") - again = read_record(rehearsal.read_text(encoding="utf-8")) - except OSError as e: - return [f"the rehearsal copy could not be made ({e})"] - finally: - shutil.rmtree(tmp, ignore_errors=True) - was = read_record(before) - problems = [] - got = {m["slug"] for m in again["members"]} - for m in was["members"]: - if m["slug"] not in got: - problems.append(f"member `{m['slug']}` no longer parses") - for key in was["keys"]: - if key not in again["keys"]: - problems.append(f"key `{key}` disappeared") - if len(again["unparsable"]) > len(was["unparsable"]): - problems.append("a member line stopped parsing") - return problems - - -# --------------------------------------------------------- the close leg --- -REVIEW_HEAD_RE = re.compile(r"^## (?P.+?)(?:\s+—\s+(?P[A-Z-]+))?$") -REVIEW_KEY_RE = re.compile(r"^- (decision|ruled|note): (.*)$") - - -def read_review(text: str) -> dict: - """`batches/reviews/.md` — what the human ruled, verbatim. - - Read, reported, and never enacted: `batches/reviews/AGENTS.md` gives the - close-out to the orchestrator, and a review never executes its own - follow-ups. - """ - keys: dict[str, str] = {} - members: dict[str, dict] = {} - slug = None - for raw in text.split("\n"): - line = _dash(raw) - head = REVIEW_HEAD_RE.match(line) - if head: - name = head.group("slug").strip() - if name.lower().startswith("follow-up"): - slug = None - continue - slug = name - members[slug] = {"health": head.group("health") or "", - "decision": "", "ruled": "", "note": []} - continue - if slug is None: - m = RECORD_KEY.match(line) - if m: - keys[m.group(1)] = (m.group(2) or "").strip() - continue - m = REVIEW_KEY_RE.match(line) - if m: - if m.group(1) == "note": - members[slug]["note"].append(m.group(2).strip()) - else: - members[slug][m.group(1)] = m.group(2).strip() - elif line.strip() and not line.startswith(""); - lines.push(""); - return lines.join("\n"); - } - - var modal = document.getElementById("submit-modal"); - var preview = document.getElementById("md-preview"); - var ghLink = document.getElementById("btn-github"); - var ghHint = document.getElementById("gh-hint"); - var copyBtn = document.getElementById("btn-copy"); - var dlBtn = document.getElementById("btn-download"); - var currentMd = ""; - - function openModal() { - currentMd = buildMarkdown(); - if (preview) { preview.textContent = currentMd; } - if (ghLink) { - var url = GITHUB_NEW + "?filename=" + encodeURIComponent(REVIEW_PATH) + - "&value=" + encodeURIComponent(currentMd); - /* GitHub's prefilled-new-file URL is the affordance that lands the review - * without a copy-paste; past ~7,500 chars it silently truncates, which - * would commit a review missing its last members. */ - if (!GITHUB_NEW) { - /* The renderer found no GitHub home for this Mind (no origin remote, - * no README link) and names none itself, so there is nothing to link. */ - ghLink.removeAttribute("href"); - ghLink.classList.add("is-disabled"); - ghLink.setAttribute("aria-disabled", "true"); - if (ghHint) { - ghHint.textContent = "No GitHub home resolved for this Mind — use Copy, then paste into a new file at " + REVIEW_PATH + "."; - } - } else if (url.length > 7500) { - ghLink.removeAttribute("href"); - ghLink.classList.add("is-disabled"); - ghLink.setAttribute("aria-disabled", "true"); - if (ghHint) { - ghHint.textContent = "The review is too long for a prefilled GitHub URL — use Copy, then paste into a new file at " + REVIEW_PATH + "."; - } - } else { - ghLink.setAttribute("href", url); - ghLink.classList.remove("is-disabled"); - ghLink.removeAttribute("aria-disabled"); - } - } - if (modal) { modal.hidden = false; } - } - function closeModal() { if (modal) { modal.hidden = true; } } - - var submitBtn = document.getElementById("btn-submit"); - if (submitBtn) { submitBtn.addEventListener("click", openModal); } - var closeBtn = document.getElementById("btn-close"); - if (closeBtn) { closeBtn.addEventListener("click", closeModal); } - if (modal) { - modal.addEventListener("click", function (ev) { - if (ev.target === modal) { closeModal(); } - }); - } - document.addEventListener("keydown", function (ev) { - if (ev.key === "Escape") { closeModal(); } - }); - - function flash(btn, text) { - var old = btn.textContent; - btn.textContent = text; - window.setTimeout(function () { btn.textContent = old; }, 2000); - } - - if (copyBtn) { - copyBtn.addEventListener("click", function () { - if (!guardPrompt(currentMd, copyBtn)) return; - var done = function () { flash(copyBtn, "Copied ✓"); }; - var fallback = function () { - try { - var ta = document.createElement("textarea"); - ta.value = currentMd; - ta.setAttribute("readonly", "readonly"); - ta.style.position = "fixed"; - ta.style.left = "-9999px"; - document.body.appendChild(ta); - ta.select(); - document.execCommand("copy"); - document.body.removeChild(ta); - done(); - } catch (e) { flash(copyBtn, "Copy failed — select the preview"); } - }; - if (navigator.clipboard && navigator.clipboard.writeText) { - navigator.clipboard.writeText(currentMd).then(done, fallback); - } else { fallback(); } - }); - } - - if (dlBtn) { - dlBtn.addEventListener("click", function () { - try { - var blob = new Blob([currentMd], { type: "text/markdown" }); - var a = document.createElement("a"); - a.href = URL.createObjectURL(blob); - a.download = SLOT + "-review.md"; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - window.setTimeout(function () { URL.revokeObjectURL(a.href); }, 5000); - } catch (e) { flash(dlBtn, "Download blocked — use Copy"); } - }); - } - - var links = document.querySelectorAll(".sidenav a[data-nav]"); - if (links.length && "IntersectionObserver" in window) { - var map = {}; - var targets = []; - for (i = 0; i < links.length; i++) { - var key = links[i].getAttribute("data-nav"); - var el = document.getElementById(key); - if (el) { map[key] = links[i]; targets.push(el); } - } - var visible = {}; - var observer = new IntersectionObserver(function (entries) { - for (var j = 0; j < entries.length; j++) { - visible[entries[j].target.id] = entries[j].isIntersecting; - } - var active = null; - for (var k = 0; k < targets.length; k++) { - if (visible[targets[k].id]) { active = targets[k].id; break; } - } - for (var key2 in map) { - if (Object.prototype.hasOwnProperty.call(map, key2)) { - map[key2].classList.toggle("active", key2 === active); - } - } - }, { rootMargin: "-10% 0px -70% 0px", threshold: 0 }); - for (i = 0; i < targets.length; i++) { observer.observe(targets[i]); } - } -}()); diff --git a/bin/branch_sweep.sh b/bin/branch_sweep.sh index 20106a97..49cf68d2 100755 --- a/bin/branch_sweep.sh +++ b/bin/branch_sweep.sh @@ -26,7 +26,7 @@ # * any branch that is the head of an OPEN pull request # * any branch git cannot prove is already contained in the base # * `integration/*` — batch review refs, -# published by `batch collect --integration --push`. These are deliberately +# published by the retired `batch collect --integration --push`. These are deliberately # NOT contained in the base — previewing a merge before it happens is the # whole point — so the containment proof can never clear them, and they # would otherwise be kept forever. They are cleared BY DATE ALONE: the diff --git a/bin/pyauto-brain b/bin/pyauto-brain index 8a70aa4b..5c3dc128 100755 --- a/bin/pyauto-brain +++ b/bin/pyauto-brain @@ -95,7 +95,7 @@ declare -A AGENT_SCRIPT=( ) declare -A AGENT_DESC=( [intake]="File classified prompts; never start development" - [batch]="Propose a review-budgeted batch; collect its results" + [batch]="Propose a review-budgeted shift; brief, watch and digest it" [community]="Triage community threads; human-approved replies and development handoffs" [feature]="Select, size and plan features" [bug]="Classify regressions and plan repairs" diff --git a/skills/COMMANDS.md b/skills/COMMANDS.md index 352d4d7b..2dc01d49 100644 --- a/skills/COMMANDS.md +++ b/skills/COMMANDS.md @@ -30,7 +30,7 @@ readiness gate, or execution — those belong to the organs. | Command | Agent | Chain | |---------|-------|-------| | `/intake` | Intake Agent | `bin/pyauto-brain intake` → files a PyAutoMind prompt (**before** `start_dev`); `census`/`dashboard` = backlog inventory / `PyAutoMind/dashboard.md` | -| `/batch` | Batch Agent | `bin/pyauto-brain batch` → the BatchDecision for one unattended shift, budgeted in review minutes; proposes only — the human's approval in the slot dispatches it; `batch collect` scores what came back | +| `/batch` | Batch Agent | `bin/pyauto-brain batch` → the BatchDecision for one unattended shift, budgeted in review minutes; proposes only — the human's shift brief launches it; the watcher's digest reports what came back | | `/community` | Community Agent | `bin/pyauto-brain community` → scan/triage the Discussions hub + user-filed issues/PRs (read-only surfaces) → session drafts replies for human approval → answer in the thread, or `/start_dev_for_user` for a report with a reproducer | | `/feedback` | Community Agent (session-side drafting) | Current session or explicitly selected logs → user-reviewed feedback draft → human submits to the existing Discussions hub; no CLI scan, new conductor or automatic posting | | `/feature` | Feature Agent | `bin/pyauto-brain feature` → `start_dev` → `ship_*` | diff --git a/skills/batch/batch.md b/skills/batch/batch.md index 1d4d6f03..f72ef9e2 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -1,7 +1,7 @@ # Batch — the slot door -The front door for the batch workflow: **what runs unattended, and what came -back**. Drive it from a chat; nothing here needs a terminal. +The front door for the batch workflow: **what runs unattended**, composed as a +shift brief the watcher runs. Drive it from a chat; nothing here needs a terminal. Read [`../../agents/conductors/batch/AGENTS.md`](../../agents/conductors/batch/AGENTS.md) before acting — it holds the constraints, why each exists, and the full slot @@ -70,31 +70,16 @@ In order: validation") — ask the human for these whenever a member merges into a library; they are the ONLY thing a later "generated by an earlier member" YELLOW classification may match against (`AUTONOMY.md`, leg 4). -2. Write `PyAutoMind/batches/-.md` from the schema in that - folder's `AGENTS.md` — members, planned review-minutes, the reason set, - `expected-effects:` and **`review-at:`** — **before** any session starts; - that file makes the launch auditable. `review-at:` is when the human expects - to be back and where the grant expires: **if they did not say, ask before - dispatching** — never infer it from a schedule, a previous batch, or the time of day. **If they will want to *run* the batch, write `- integration: yes` into the record** (collect then builds the worktree). - **A shift brief** (`brief --new … --out` makes its shift issue; `--check`; push = launch): [`reference.md`](reference.md) "Launching a shift brief". -3. Start one session per member, each carrying `/start_dev --auto` plus - the member-session contract below (the batch record informs a member of the - shift's grant at leg 4, not the dispatch line). Spawn them if this harness - can; otherwise hand the human the lines to paste. **One session per member, - never shared** — sharing serialises them and leaks context. **`local-dev` - members go first** (2026-08-31): their RAL submissions queue while the - laptop is still on; cloud members follow. - - **The member-session contract** (2026-08-31) is in [`reference.md`](reference.md): - members spawn from the orchestrator's template with sources and the bootstrap - preamble, and **END at their deliverable** — no PR watching, no - `subscribe_pr_activity`, no check-ins (`PyAutoMind/policy/end_at_deliverable.md`). -4. **Open the packet at dispatch** (2026-08-31): write the review page to - `PyAutoMind/batches/packets/-.html` with every member present — - dev members as stubs, overnight runs as **PENDING** entries — and stamp it - `generated:`. The human wakes to a live page, not a blank; the morning - collect fills it in. -5. Confirm what was dispatched, and stop. Do not follow the runs. +2. Write the shift brief `PyAutoMind/batches/-.md` — + `brief --new … --out` composes it and makes its shift issue; `brief --check` + validates it; pushing it is the launch: [`reference.md`](reference.md) + "Launching a shift brief". `review-at:` is when the human expects to be back + and where the grant expires: **if they did not say, ask before + dispatching** — never infer it from a schedule, a previous shift, or the + time of day. +3. Confirm what was launched, and stop. Do not follow the runs: the watcher + starts the workers, and each **ends at its deliverable** + (`PyAutoMind/policy/end_at_deliverable.md`). **Brief verbs** (`batch brief --check`, `batch plan --brief`, `batch digest`): [`reference.md`](reference.md). Run the check before pushing a brief; it refuses a live brief without `issue:` or with an expired CLI login. `brief --new` also runs the keep-Heart-green lane: a `## Heart` section and up to 3 bug drafts for fixable Heart reasons (only with `--out` and a non-shared `--mind`; named as tasks only with `--green pick`); it never releases (`batch green` = dry run; `agents/conductors/batch/AGENTS.md`). @@ -110,44 +95,21 @@ watcher starts one independent close-out session that merges it or refuses; each What a tick does, its state, caps and the install commands: `agents/conductors/batch/AGENTS.md` "The watcher". **`/batch watch`** ("how is the shift going?"): run `bin/pyauto-brain batch watch --record --once` and relay it as written; with no slot on this machine, read the status comment on its `issue:` ([`reference.md`](reference.md)). The human steers with their own comment there (`/pause`, `/resume`, `/drop `, `/stop`, `/add `, `/cap merges|workers|sessions|tokens `, `/kill `); never post one for them. `batch watch --stream --record ` prints the shift's event stream (`events.jsonl`, local reads only) until it ends — the cockpit's watch ([`reference.md`](reference.md)). -## When they come back — collect, review, close (2026-08-31) +## When they come back — the digest, review, close -**Collect first, before the human reads anything.** It is one command: +**The digest is the review surface** (2026-11-03): the watcher writes it into +the record and posts it once on the shift's `issue:`; see +[`reference.md`](reference.md). Order: failures first, then anything labelled +`decision-taken`, then clean. -``` -bin/pyauto-brain batch collect --slot - --evidence ev.json --apply -``` - -- **Gather the evidence, then hand it over** — collect has no GitHub of its own; - the web-session (MCP) and laptop (`--fetch`) recipes are in [`reference.md`](reference.md). -- **"I want to run the whole batch."** — `batch collect --slot - - --integration --apply` (laptop only; nothing pushed without `--push`, the - human's call). What it builds and how conflicts read: [`reference.md`](reference.md). -- **What comes back is scored, not summarised.** Six legs per member (pr · - diff · checks · green · witness · adversary), one health word (FAILED · - NOT-DELIVERED · SUSPECT · HEALTHY · PENDING · MERGED), failures at the top. - A leg with no evidence is UNOBSERVABLE and never delivered — a member you - did not look up reaches the human as SUSPECT, not as clean. -- **PENDING entries fill themselves in** on `--apply`, and **science runs are - not batch members** (`/cortex`): [`reference.md`](reference.md). - -**Before reading any PR from a batch, the independent adversary leg must have +**Before reading any PR from a shift, the independent adversary leg must have run** (`AUTONOMY.md` leg 5): `bin/pyauto-brain review --task --witness "" --adversary`, **in a fresh Opus session or sub-agent that did not write the branch** (Fable only when the human asks). A self-run adversary leg is an absent leg, not a weak one, and recording it as run is a false ledger row. If it has not run, say so rather than reviewing as though it had. -**Then the human reviews — on the packet page, not in the chat.** Order: -failures first, then anything labelled `decision-taken`, then clean. They tick, -choose and annotate each member on the page and submit; the submission lands as -`PyAutoMind/batches/reviews/-.md` (or they dictate the same -content in-chat — both are the same review). When they say the review is done, -run `batch collect --slot - --apply` once more: with the review -file present it **refuses to rewrite the packet** — that page is what they -ruled against — and closes the record instead (`reviewed-at:`, -`review-minutes-actual:`, `review:`). It reports their decisions and enacts -none of them; that part is yours, member by member: +The human rules; enacting is yours, member by member: - **merge** — `/prm `; for a science member, write the ruling into the project's own ledger (DECISIONS, harvest table, results summary) verbatim. @@ -159,9 +121,6 @@ none of them; that part is yours, member by member: they are queued for the next batch, never executed inside the review. What "complete" means, and asking for `review-minutes-actual:`: [`reference.md`](reference.md). -**Under a brief, the digest is the review surface** (2026-11-03) — the record -plus one comment on the shift's `issue:`; see [`reference.md`](reference.md). - **`delivered:` is not "green".** A cloud session's green status means it exited without an infrastructure error — not that the task succeeded. A member counts as delivered only with a PR that has a non-empty diff and checks that ran green. diff --git a/skills/batch/reference.md b/skills/batch/reference.md index 3616846b..99294643 100644 --- a/skills/batch/reference.md +++ b/skills/batch/reference.md @@ -4,7 +4,7 @@ Moved word for word from [`batch.md`](batch.md) to keep the skill's mandatory load under its 200-line budget. Read a section when the step that needs it is reached; `batch.md` points here from each one. -## The member-session contract (dispatch step 3) +## The member-session contract **The member-session contract (2026-08-31, both measured that night):** @@ -29,45 +29,11 @@ reached; `batch.md` points here from each one. its deliverable (`PyAutoMind/policy/end_at_deliverable.md`), `/prm` included. Five members self-armed 2–4-hourly check-ins on green PRs overnight and - drained usage with no task active. At collect, the orchestrator deletes - any member-armed routine it finds and archives finished member sessions. - -## Collect: the integration worktree - -- **"I want to run the whole batch."** — - `bin/pyauto-brain batch collect --slot - --integration --apply` - (laptop only). One worktree root per slot under - `~/Code/PyAutoLabs-wt/integration-/`, each affected repo on - `integration/` cut from `origin/main` with every member's head merged - in dispatch order. Hand the human the `source /activate.sh` line: once - it is sourced a **library** member's change is live anywhere (it is on the - `PYTHONPATH`), while a **workspace** member's script must be run from inside - `/`. A member that conflicts is **left out and named with - the conflicting files** — report that as the answer to "how would this - resolve at the end?", not as a failure. Nothing is pushed, no PR is opened, - no remote ref is touched. If the reviewer needs it on another machine or in - CI, add `--push`: one real `integration/` per repo, pushed with the - laptop's own git auth, never forced, never a PR, and swept after the record's - `sweep-after:` date. The first push of a slot is the human's call. - -## Collect: PENDING entries and science runs - -- **The PENDING entries fill themselves in.** `--apply` regenerates each - member's section in place — same path, same id — and stamps the page - `refreshed:`, normally while the human is already reading the finished - members. No other member's markup is touched, so their stored notes and - chips survive. -- **Science runs are not batch members.** Checking in on the science is its - own door — `/cortex`, over `bin/pyauto-brain cortex collect --pull --apply`, - which pulls every active project, scores every `submitted | running` phase - against its pre-registered witness and moves what came back to - `awaiting-ruling`. It needs no record, no slot and no packet. The science - board this conductor once opened (`--kind cortex`) was retired on - 2026-09-03; see `PyAutoBrain/skills/cortex/cortex.md`. + drained usage with no task active. ## Under a brief, the digest is the review surface -**Under a brief, the digest is the review surface** (2026-11-03). Collect +**Under a brief, the digest is the review surface** (2026-11-03). The watcher appends a `## Digest` to the record — brief work, then backlog picks with a one-line reason each, one proof packet per task, then the shift counters — and posts it once as a comment on the shift's `issue:`. The record plus that comment @@ -110,18 +76,6 @@ the `origin/main` ref of the Mind checkout in its env file **without fetching**, so push the brief from that checkout or `git fetch` it before launch; otherwise the watcher idles with "no open brief". -## Collect: gathering the evidence - -- **Gather the evidence, then hand it over.** Collect has no GitHub of its - own. In a web session, read each member's PRs with the GitHub MCP tools - (`pull_request_read` for state and diff counts, the check rollup or - `actions_list` for the checks — `PyAutoBrain/skills/GITHUB_ACCESS.md` maps - each operation) and write them into the evidence JSON that the conductor's - `AGENTS.md` documents under "The collect recipe". On the laptop lane - `--fetch` does the same by running one `gh pr view` per PR. Run it once - without `--apply` to read the report; run it again with `--apply` to write - the packet and stamp the record. - ## When the batch is complete **Review closes the batch; follow-ups never block the next one** (2026-08-31). @@ -129,7 +83,7 @@ Every tweak and follow-up is *queued*, enacted in the next batch the human launches — it is never executed inside the review, and an open follow-up is never a reason to hold the next dispatch. The batch is complete when: accepted PRs are merged, science rulings are in their ledgers, follow-ups sit at the top -of `queue.md`, the packet page is archived in `batches/packets/`, and the batch +of `queue.md`, and the batch record carries `reviewed-at:` (when they actually sat down — the calibration of their own `review-at:` estimate), `delivered:` (`batch.md`: "`delivered:` is not green"), `review:` (the review file's path) and **`review-minutes-actual:`**. That last number is the diff --git a/tests/test_batch_collect.py b/tests/test_batch_collect.py deleted file mode 100644 index 52783bd3..00000000 --- a/tests/test_batch_collect.py +++ /dev/null @@ -1,927 +0,0 @@ -"""tests/test_batch_collect.py — the Batch Agent's collection rules. - -`batches/AGENTS.md` states the rule every test here defends: **a green session -is not a delivered task**. A member counts as delivered only with a PR that has -a non-empty diff and checks that actually ran, and a member that ends green -with no PR is reported not delivered, loudly. So most of these are refusals -too — refusals to call something delivered on evidence that does not say so, -and refusals to invent evidence that is simply not here. -""" - -from __future__ import annotations - -import importlib.util -import json -import re -import sys -from pathlib import Path -from types import SimpleNamespace - -BRAIN = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) -_spec = importlib.util.spec_from_file_location( - "_batch_collect_under_test", - BRAIN / "agents" / "conductors" / "batch" / "_batch.py") -_batch = importlib.util.module_from_spec(_spec) -sys.modules["_batch_collect_under_test"] = _batch -_spec.loader.exec_module(_batch) - -STAMP = "2026-09-03T08:00Z" - -PROMPT = """# Add a resampling info section - -Type: bug -Target: autofit -Witness: the new section appears in search.summary and a unit test pins it - -The bottom of `search.summary` says nothing about resampling, so a run that -resampled heavily looks identical to one that did not. -""" - -ACTIVE = """# Active Tasks - -## resampling-info-summary-section -- issue: https://github.com/ExampleOrg/ExampleFit/issues/1551 -- prompt: active/resampling.md -- status: library-shipped, awaiting-merge -- library-pr: https://github.com/ExampleOrg/ExampleFit/pull/1554 - -## something-else -- prompt: active/other.md -- status: pr-open -- prs: - - https://github.com/ExampleOrg/ExampleArray/pull/9 -""" - -MEMBER = (" - resampling: draft/bug/autofit/resampling.md — glance — 3 — " - "session ended green (exit 0, cloud session, --auto)") - - -def record(*members, keys="", notes=True) -> str: - body = ["# Batch 2026-09-03 pm", "", - "- dispatched: 2026-09-03T17:40Z", - "- review-at: 2026-09-04T08:00Z", - "- lane: any", - "- review-minutes-planned: 3", - "- members:"] - body += list(members) - if keys: - body.append(keys) - if notes: - body += ["- notes: |", - " What actually happened.", - " - delivered: this line is prose, not a key", - " Nothing stalled."] - return "\n".join(body) + "\n" - - -def mini_mind(tmp_path, *members, active=ACTIVE, notes=True, keys="", - review=None) -> Path: - mind = tmp_path / "mind" - (mind / "batches" / "packets").mkdir(parents=True) - (mind / "batches" / "reviews").mkdir(parents=True) - (mind / "draft" / "bug" / "autofit").mkdir(parents=True) - (mind / "active").mkdir(parents=True) - (mind / "batches" / "2026-09-03-pm.md").write_text( - record(*(members or (MEMBER,)), keys=keys, notes=notes), - encoding="utf-8") - (mind / "batches" / "2026-09-03-am.md").write_text( - record(" - other: draft/bug/autofit/resampling.md — glance — 1 — " - "REJECTED by the human at review"), encoding="utf-8") - (mind / "draft" / "bug" / "autofit" / "resampling.md").write_text( - PROMPT, encoding="utf-8") - (mind / "active" / "resampling.md").write_text(PROMPT, encoding="utf-8") - (mind / "active.md").write_text(active, encoding="utf-8") - if review is not None: - (mind / "batches" / "reviews" / "2026-09-03-pm.md").write_text( - review, encoding="utf-8") - return mind - - -def pr(**over) -> dict: - row = {"repo": "ExampleOrg/ExampleFit", "number": 1554, - "url": "https://github.com/ExampleOrg/ExampleFit/pull/1554", - "state": "OPEN", "additions": 86, "deletions": 12, - "changed_files": 3, "mergeable": "MERGEABLE", "merged": False, - "head_ref": "feature/autofit-resampling-info", - "head_sha": "2629933c", "head_repo": "ExampleOrg/ExampleFit", - "checks": [{"name": "tests", "status": "completed", - "conclusion": "success"}]} - row.update(over) - return row - - -def evidence(**over) -> dict: - row = {"prs": [pr()], - "witness": {"holds": True, "evidence": "the new test is green"}, - "adversary": {"ran": True, "model": "gpt-5.1", - "author_model": "claude-opus-4", "verdict": "CLEAN"}} - row.update(over) - return {"resampling": row} - - -def one(d, slug="resampling"): - return next(s for s in d["members"] if s["slug"] == slug) - - -# ------------------------------------------------------ reading the record -- -def test_a_member_outcome_may_contain_the_separator(tmp_path): - """Every one of the nine dev outcomes in the 2026-08-31-pm record contains - spaces and several contain the separator itself. Splitting with maxsplit=3 - keeps the outcome whole; the Cortex conductor's `(?P\\S+)$` does - not, which is why this module does not reuse it.""" - line = (" - resampling: draft/bug/autofit/resampling.md — glance — 3 — " - "DELIVERED (ExampleFit#1554 — 4/4 checks green, mergeable clean)") - row = _batch.parse_member(line) - assert row["slug"] == "resampling" - assert row["path"] == "draft/bug/autofit/resampling.md" - assert row["tier"] == "glance" and row["minutes"] == "3" - assert row["outcome"].endswith("mergeable clean)") - assert "—" in row["outcome"] - - -def test_an_unparsable_member_line_is_a_note_not_a_crash(tmp_path): - """The two science members of the 2026-08-31-pm record have a sentence - where the path goes. Reporting them is right; refusing to collect the slot - because of them is not.""" - science = (" - subhalo-wave: PyAutoCortex phases/subhalo_validation/ " - "(four phases, one per lens) — judge — 15 — REFRESHED, carried") - mind = mini_mind(tmp_path, MEMBER, science) - d = _batch.collect(mind, "2026-09-03-pm") - assert [s["slug"] for s in d["members"]] == ["resampling"] - assert any("does not read as a member line" in n for n in d["notes"]) - assert any("subhalo-wave" in n for n in d["notes"]) - - -def test_the_em_dash_may_be_typed_as_two_hyphens(tmp_path): - row = _batch.parse_member( - " - resampling: draft/bug/autofit/resampling.md -- glance -- 3 -- " - "DELIVERED (ExampleFit#1554)") - assert row and row["tier"] == "glance" and row["minutes"] == "3" - - -def test_a_notes_block_is_never_read_as_members(tmp_path): - """`- notes: |` carries prose that looks exactly like the ledger — the - fixture's block contains a `- delivered:` line on purpose.""" - mind = mini_mind(tmp_path) - rec = _batch.read_record( - (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8")) - assert [m["slug"] for m in rec["members"]] == ["resampling"] - assert "notes" in rec["keys"] - assert "delivered" not in rec["keys"] - - -# --------------------------------------------------------------- the legs -- -def test_no_pr_is_not_delivered_however_green_the_session(tmp_path): - """The record's own first rule. A session's green status means it exited - without an infrastructure error, nothing more.""" - mind = mini_mind(tmp_path) - d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence(prs=[])) - assert one(d)["health"] == "NOT-DELIVERED" - assert d["not_delivered"] == ["resampling"] - assert _batch.main(["collect", "--mind", str(mind), "--slot", - "2026-09-03-pm"]) == 1 - - -def test_an_empty_diff_is_not_delivered(tmp_path): - mind = mini_mind(tmp_path) - d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( - prs=[pr(additions=0, deletions=0, changed_files=0)])) - assert one(d)["health"] == "NOT-DELIVERED" - assert one(d)["legs"]["diff"][0] == _batch.FAIL - - -def test_checks_that_never_ran_are_not_delivered_but_a_red_check_failed(tmp_path): - """Two different findings that a single "checks bad" verdict would blur: - nothing ran (the work never reached CI) versus something ran and went - red (the work is wrong).""" - mind = mini_mind(tmp_path) - never = _batch.collect(mind, "2026-09-03-pm", - evidence=evidence(prs=[pr(checks=[])])) - assert one(never)["health"] == "NOT-DELIVERED" - assert "never ran" in one(never)["legs"]["checks"][1] - red = _batch.collect(mind, "2026-09-03-pm", evidence=evidence(prs=[pr( - checks=[{"name": "tests", "status": "completed", - "conclusion": "failure"}])])) - assert one(red)["health"] == "FAILED" - assert "tests" in one(red)["legs"]["green"][1] - - -def test_a_self_run_adversary_is_an_absent_leg(tmp_path): - """AUTONOMY.md leg 5, verbatim: a self-run adversary leg is an absent leg, - not a weak one, and recording it as run is a false ledger row.""" - mind = mini_mind(tmp_path) - d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( - adversary={"ran": True, "model": "claude-opus-4", - "author_model": "claude-opus-4", "verdict": "CLEAN"})) - verdict, why = one(d)["legs"]["adversary"] - assert verdict == _batch.FAIL - assert "absent leg, not a weak one" in why - - -def test_a_same_model_adversary_passes_only_as_an_independent_session(tmp_path): - """AUTONOMY.md "Adversary model default — 2026-11-22": Opus reads an Opus - branch by default, in a session that did not write it, and the row says so.""" - mind = mini_mind(tmp_path) - row = {"ran": True, "model": "claude-opus-4", "author_model": "claude-opus-4", - "verdict": "CLEAN"} - for flag in ("true", 1, False): # only the JSON `true` counts - d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( - adversary={**row, "independent_session": flag})) - assert one(d)["legs"]["adversary"][0] == _batch.FAIL, flag - d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( - adversary={**row, "independent_session": True})) - verdict, why = one(d)["legs"]["adversary"] - assert verdict == _batch.PASS and "independent session" in why - d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( - adversary={"ran": True, "model": "claude-opus-4", "independent_session": True})) - assert one(d)["legs"]["adversary"][0] == _batch.FAIL # no author named - - -def test_a_missing_witness_is_unobservable_and_makes_the_member_suspect(tmp_path): - (tmp_path / "mind").mkdir(parents=True, exist_ok=True) - mind = mini_mind(tmp_path) - (mind / "draft" / "bug" / "autofit" / "resampling.md").write_text( - PROMPT.replace("Witness: the new section appears in search.summary " - "and a unit test pins it\n", ""), encoding="utf-8") - (mind / "active" / "resampling.md").unlink() - d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence()) - assert one(d)["legs"]["witness"][0] == _batch.UNOBSERVABLE - assert one(d)["health"] == "SUSPECT" - - -def test_a_flagged_decision_keeps_a_green_member_out_of_healthy(tmp_path): - """decide-and-flag: the run made a call it was not licensed to make. Green - checks do not settle that — a human does.""" - mind = mini_mind(tmp_path) - clean = _batch.collect(mind, "2026-09-03-pm", evidence=evidence()) - assert one(clean)["health"] == "HEALTHY" - d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( - flagged=["decide-and-flag: PR opened rather than parked"])) - assert one(d)["health"] == "SUSPECT" - assert "decide-and-flag" in "\n".join( - b for _l, b in one(d)["blocks"]) - - -def test_members_sort_failures_first_and_pending_last(tmp_path): - mind = mini_mind( - tmp_path, - " - clean: draft/bug/autofit/resampling.md — glance — 3 — session ended green", - " - broken: draft/bug/autofit/resampling.md — judge — 20 — session ended green", - " - waiting: draft/bug/autofit/resampling.md — judge — 9 — CARRIED, " - "still running") - ev = {"clean": evidence()["resampling"], - "broken": dict(evidence()["resampling"], - prs=[pr(checks=[{"name": "tests", - "status": "completed", - "conclusion": "failure"}])]), - "waiting": evidence()["resampling"]} - d = _batch.collect(mind, "2026-09-03-pm", evidence=ev) - assert [s["slug"] for s in d["members"]] == ["broken", "clean", "waiting"] - assert one(d, "waiting")["health"] == "PENDING" - - -def test_no_evidence_at_all_is_unobservable_not_delivered(tmp_path): - """The third verdict. Calling these legs PASS would invent evidence; - calling them FAIL would condemn every member of every offline collect.""" - mind = mini_mind(tmp_path) - d = _batch.collect(mind, "2026-09-03-pm") - assert one(d)["health"] == "SUSPECT" - assert all(one(d)["legs"][k][0] == _batch.UNOBSERVABLE - for k in ("pr", "diff", "checks", "green")) - assert d["delivered"] == (0, 1) - - -def test_active_md_is_matched_by_prompt_basename_when_the_slug_differs(tmp_path): - """The record's slug is a dispatch label, the registry's is the task's - name: `autofit-resampling-info` is registered as - `resampling-info-summary-section`.""" - mind = mini_mind(tmp_path) - active = _batch.read_active(mind) - entry, how = _batch.active_for( - {"slug": "autofit-resampling-info", "path": "draft/x/resampling.md"}, - active) - assert entry["slug"] == "resampling-info-summary-section" - assert how == "prompt basename" - assert entry["prs"] == ["https://github.com/ExampleOrg/ExampleFit/pull/1554"] - assert entry["issue"].endswith("/issues/1551") - - -# ------------------------------------------------------------ the packet --- -def packet_of(mind) -> str: - return (mind / "batches" / "packets" / "2026-09-03-pm.html").read_text( - encoding="utf-8") - - -def apply_once(mind, ev=None, stamp=STAMP): - d = _batch.collect(mind, "2026-09-03-pm", evidence=ev or evidence()) - d["stamp"] = stamp - notes = _batch.apply_collect(mind, d, stamp) - return d, notes - - -def test_apply_writes_a_complete_document_and_the_record_keys(tmp_path): - mind = mini_mind(tmp_path) - apply_once(mind) - page = packet_of(mind) - assert page.startswith("") - assert page.rstrip().endswith("") - assert page.count("") == 1 - assert "[hidden] { display: none !important; }" in page - assert "" in page and "charset" in page - record = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") - assert f"- collected: {STAMP}" in record - assert f"- refreshed: {STAMP} — collect (1 member(s))" in record - assert "- delivered: 1/1" in record - assert "- packet: batches/packets/2026-09-03-pm.html" in record - - -def sections(page: str) -> dict: - out = {} - for start, end, mid in _batch._member_spans(page): - out[mid] = page[start:end] - return out - - -def test_a_refresh_regenerates_one_section_and_leaves_the_others_alone(tmp_path): - """TEMPLATE.md: the morning refresh regenerates that section in place, at - the same path, and never touches another member's markup — the human is - reading the page while it happens, and their notes live in it.""" - mind = mini_mind( - tmp_path, - " - clean: draft/bug/autofit/resampling.md — glance — 3 — session ended green", - " - second: draft/bug/autofit/resampling.md — glance — 3 — session ended green") - ev = {"clean": evidence()["resampling"], "second": evidence()["resampling"]} - apply_once(mind, ev) - before = packet_of(mind) - ev["second"] = dict(ev["second"], prs=[pr(checks=[ - {"name": "tests", "status": "completed", "conclusion": "failure"}])]) - apply_once(mind, ev) - after = packet_of(mind) - assert sections(before)["m-clean"] == sections(after)["m-clean"] - assert sections(before)["m-second"] != sections(after)["m-second"] - assert set(sections(before)) == set(sections(after)) - assert (mind / "batches" / "packets" / "2026-09-03-pm.html").is_file() - - -def test_a_pending_member_becomes_a_full_block_on_refresh_with_the_same_id(tmp_path): - mind = mini_mind( - tmp_path, - " - resampling: draft/bug/autofit/resampling.md — glance — 3 — " - "DELIVERED (ExampleFit#1554)") - ev = evidence() - ev["resampling"] = dict(ev["resampling"], pending=True) - apply_once(mind, ev) - before = sections(packet_of(mind))["m-resampling"] - assert "chip-pending" in before and "PENDING" in before - assert "Health evidence" not in before - apply_once(mind, evidence()) - after = sections(packet_of(mind))["m-resampling"] - assert "Health evidence" in after and "chip-pending" not in after - assert 'id="m-resampling"' in after - - -def test_the_submit_markdown_schema_is_parse_stable(tmp_path): - """The orchestrator parses the review on these exact forms; a cosmetic - edit here silently breaks close-out.""" - mind = mini_mind( - tmp_path, - " - clean: draft/bug/autofit/resampling.md — glance — 3 — session ended green", - " - second: draft/bug/autofit/resampling.md — judge — 9 — session ended green") - d, _ = apply_once(mind, {"clean": evidence()["resampling"], - "second": evidence()["resampling"]}) - page = packet_of(mind) - assert '"# Batch review " + SLOT' in page - assert '"- decision: "' in page and '"- ruled: "' in page - assert '"## Follow-ups accepted"' in page - members = json.loads(re.search(r"var MEMBERS = (\[.*?\]);", page, - re.S).group(1)) - assert [m["slug"] for m in members] == [s["slug"] for s in d["members"]] - assert [m["id"] for m in members] == [s["id"] for s in d["members"]] - assert all(m["health"] for m in members) - - -def test_stored_review_state_is_versioned_and_every_access_is_guarded(tmp_path): - """The page is opened from Pages, from a file:// path and from inside an - artifact viewer; two of those can throw on the accessor itself.""" - mind = mini_mind(tmp_path) - apply_once(mind) - page = packet_of(mind) - assert 'var KEY = "slot-review-2026-09-03-pm-v1";' in page - touches = [ln for ln in page.split("\n") - if "window.localStorage" in ln] - assert touches - assert all("try {" in ln for ln in touches) - - -# ------------------------------------------------------------ the record --- -def test_a_ruling_word_outcome_is_never_rewritten(tmp_path): - """The am record's REJECTED/ACCEPTED members are a review that happened. - A machine reading must not overwrite a human's sentence.""" - mind = mini_mind( - tmp_path, - " - ruled: draft/bug/autofit/resampling.md — glance — 3 — REJECTED " - "by the human at review", - " - fresh: draft/bug/autofit/resampling.md — glance — 3 — session ended green " - "into the wave") - apply_once(mind, {"ruled": evidence()["resampling"], - "fresh": evidence()["resampling"]}) - record = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") - assert "REJECTED by the human at review" in record - assert "session ended green" not in record - assert " - fresh: draft/bug/autofit/resampling.md — glance — 3 — HEALTHY" \ - in record - - -def test_the_notes_block_survives_a_record_rewrite_byte_for_byte(tmp_path): - mind = mini_mind(tmp_path) - path = mind / "batches" / "2026-09-03-pm.md" - before = path.read_text(encoding="utf-8") - block = before[before.index("- notes: |"):] - apply_once(mind) - after = path.read_text(encoding="utf-8") - assert after[after.index("- notes: |"):] == block - - -def test_a_second_apply_adds_one_refreshed_line_and_nothing_else(tmp_path): - mind = mini_mind(tmp_path) - path = mind / "batches" / "2026-09-03-pm.md" - apply_once(mind) - first = path.read_text(encoding="utf-8").split("\n") - apply_once(mind, stamp="2026-09-03T09:30Z") - second = path.read_text(encoding="utf-8").split("\n") - added = [ln for ln in second if ln not in first] - assert added == ["- refreshed: 2026-09-03T09:30Z — collect (1 member(s))"] - assert len(second) == len(first) + 1 - assert first.count(f"- collected: {STAMP}") == 1 - assert second.count(f"- collected: {STAMP}") == 1 - - -REVIEW = """# Batch review 2026-09-03-pm - -- packet: PyAutoMind/batches/packets/2026-09-03-pm.html -- reviewed-at: 2026-09-04T08:30Z -- review-minutes-actual: 55 - -## resampling — HEALTHY -- decision: merge -- ruled: yes - -Ship it, the summary block reads well. - -## Follow-ups accepted -""" - - -def test_a_submitted_review_closes_the_record_and_never_rewrites_the_packet(tmp_path): - """`batches/packets/AGENTS.md`: the archived page and the review file are - the audit pair — what was shown, what was ruled. A correction gets a new - dated page, not an edit.""" - mind = mini_mind(tmp_path, review=REVIEW) - d, notes = apply_once(mind) - assert not (mind / "batches" / "packets" / "2026-09-03-pm.html").exists() - assert any("never rewritten after a review" in n for n in notes) - record = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") - assert "- reviewed-at: 2026-09-04T08:30Z" in record - assert "- review-minutes-actual: 55" in record - assert "- review: batches/reviews/2026-09-03-pm.md" in record - assert d["review"]["members"]["resampling"]["decision"] == "merge" - assert d["review"]["members"]["resampling"]["ruled"] == "yes" - # Reported, never enacted. - assert "merge" in _batch.collect_report(d) - - -def test_a_closed_batch_keeps_every_member_line_and_every_value_it_has(tmp_path): - """Found on the live pm record: `PR OPENED AT REVIEW (…)` opens with no - ruling word, and the record's `reviewed-at:` carried a clause about where - the review sat. Once the review has landed the record is history — no - member line changes, and the close leg fills only what is blank.""" - mind = mini_mind( - tmp_path, - " - resampling: draft/bug/autofit/resampling.md — glance — 3 — PR " - "OPENED AT REVIEW (ExampleFit#1554 from the parked branch)", - keys="- reviewed-at: 2026-09-04T08:30 (transcribed; the review sat " - "outside the packet)\n- review-minutes-actual: (not given)\n" - "- delivered: 6/9 cloud members (5 PR sets green + 1 verdict)", - review=REVIEW) - apply_once(mind) - record = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") - assert "- delivered: 6/9 cloud members (5 PR sets green + 1 verdict)" in record - assert "- delivered: 0/1" not in record - assert "PR OPENED AT REVIEW (ExampleFit#1554 from the parked branch)" in record - assert "— HEALTHY" not in record - assert ("- reviewed-at: 2026-09-04T08:30 (transcribed; the review sat " - "outside the packet)") in record - assert "- reviewed-at: 2026-09-04T08:30Z" not in record - assert "- review-minutes-actual: 55" in record - assert "(not given)" not in record - - -def test_review_minutes_not_given_is_not_written_back(tmp_path): - mind = mini_mind(tmp_path, review=REVIEW.replace("55", "(not given)")) - apply_once(mind) - record = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") - assert "review-minutes-actual" not in record - - -# --------------------------------------------------------------- the cli --- -def test_exit_codes(tmp_path, capsys): - mind = mini_mind(tmp_path) - ev_file = tmp_path / "ev.json" - ev_file.write_text(json.dumps({"schema": 1, "members": evidence()}), - encoding="utf-8") - assert _batch.main(["collect", "--mind", str(mind), "--slot", - "2026-09-03-pm", "--evidence", str(ev_file)]) == 0 - bad = tmp_path / "bad.json" - bad.write_text(json.dumps({"members": evidence(prs=[])}), encoding="utf-8") - assert _batch.main(["collect", "--mind", str(mind), "--slot", - "2026-09-03-pm", "--evidence", str(bad)]) == 1 - assert _batch.main(["collect", "--mind", str(mind), - "--slot", "nope"]) == 2 - assert _batch.main(["collect", "--mind", str(tmp_path / "nowhere")]) == 4 - - -def test_malformed_evidence_is_a_usage_error(tmp_path): - mind = mini_mind(tmp_path) - broken = tmp_path / "broken.json" - broken.write_text("{not json", encoding="utf-8") - assert _batch.main(["collect", "--mind", str(mind), "--slot", - "2026-09-03-pm", "--evidence", str(broken)]) == 2 - - -def test_collect_only_flags_are_refused_on_plan(tmp_path): - mind = mini_mind(tmp_path) - assert _batch.main(["plan", "--mind", str(mind), "--apply"]) == 2 - - -def test_the_newest_slot_is_the_default_and_the_sort_is_lexical(tmp_path): - mind = mini_mind(tmp_path) - assert _batch.newest_slot(mind) == "2026-09-03-pm" - (mind / "batches" / "2026-09-03-night.md").write_text(record(MEMBER), - encoding="utf-8") - assert _batch.newest_slot(mind) == "2026-09-03-pm" - - -def test_fetch_without_gh_points_at_the_mcp_tools_and_still_scores( - tmp_path, monkeypatch, capsys): - """`gh` installs in a web session, authenticates, then 403s every - repo-scoped call — so its absence is answered with a pointer, never a - caught error.""" - monkeypatch.setattr(_batch.shutil, "which", lambda _name: None) - mind = mini_mind(tmp_path) - rc = _batch.main(["collect", "--mind", str(mind), "--slot", - "2026-09-03-pm", "--fetch"]) - out = capsys.readouterr().out - assert rc == 1 - assert "no gh here" in out and "--evidence " in out - assert out.count("no gh here") == 1 - assert "## resampling — SUSPECT" in out - - -def test_fetch_records_the_head_branch_of_every_pr(tmp_path, monkeypatch): - """A record names members, never branches, and `active.md`'s PR field has - four spellings — so the PR's own head is the only reliable member -> - (repo, branch) map. It is asked for in the `--json` field list and carried - through onto the row; a fork whose owner is gone reports an empty head - repo rather than guessing `origin`.""" - calls = [] - head = {"headRefName": "feature/x", "headRefOid": "abc", - "headRepository": {"name": "ExampleFit"}, - "headRepositoryOwner": {"login": "ExampleOrg"}} - - def fake(cmd, **_kw): - calls.append(cmd) - body = {"number": 1554, "url": "https://example.invalid/pull/1554", - "state": "OPEN", "additions": 5, "deletions": 1, - "changedFiles": 2, "mergeable": "MERGEABLE", - "mergedAt": None, "statusCheckRollup": [], **head} - return SimpleNamespace(returncode=0, stdout=json.dumps(body), - stderr="") - - monkeypatch.setattr(_batch.shutil, "which", lambda _name: "/usr/bin/gh") - monkeypatch.setattr(_batch.subprocess, "run", fake) - mind = mini_mind(tmp_path) - members = [{"slug": "resampling", "path": "draft/bug/autofit/resampling.md"}] - active = _batch.read_active(mind) - - got, notes = _batch.fetch_evidence(members, active) - - assert notes == [] - assert "headRefName" in _batch.GH_FIELDS - # The flag is what is pinned: a field dropped from the argv is a field the - # evidence silently loses. - assert any("headRefName" in str(arg) for arg in calls[0]) - row = got["resampling"]["prs"][0] - assert row["head_ref"] == "feature/x" - assert row["head_sha"] == "abc" - assert row["head_repo"] == "ExampleOrg/ExampleFit" - - head["headRepositoryOwner"] = None - got, _notes = _batch.fetch_evidence(members, active) - assert got["resampling"]["prs"][0]["head_repo"] == "" - assert got["resampling"]["prs"][0]["head_ref"] == "feature/x" - - -def test_fetch_asks_gh_for_mergedat_because_there_is_no_merged_field( - tmp_path, monkeypatch): - """`gh pr view --json` has no `merged` field. It does not drop an unknown - name — it rejects the WHOLE request ("Unknown JSON field: merged", gh - 2.98), so one wrong word made every PR of every `--fetch` UNOBSERVABLE and - the report blamed the PRs. `mergedAt` is the same fact, and the row's - `merged` is derived from it.""" - assert "mergedAt" in _batch.GH_FIELDS - assert "merged," not in _batch.GH_FIELDS - - rows = [{"number": 1554, "url": "u", "state": "MERGED", "additions": 5, - "deletions": 1, "changedFiles": 2, "mergeable": "UNKNOWN", - "mergedAt": "2026-09-01T19:34:55Z", "statusCheckRollup": [], - "headRefName": "feature/x", "headRefOid": "abc", - "headRepository": {"name": "ExampleFit"}, - "headRepositoryOwner": {"login": "ExampleOrg"}}] - - def fake(cmd, **_kw): - return SimpleNamespace(returncode=0, stdout=json.dumps(rows[0]), - stderr="") - - monkeypatch.setattr(_batch.shutil, "which", lambda _name: "/usr/bin/gh") - monkeypatch.setattr(_batch.subprocess, "run", fake) - mind = mini_mind(tmp_path) - members = [{"slug": "resampling", "path": "draft/bug/autofit/resampling.md"}] - got, notes = _batch.fetch_evidence(members, _batch.read_active(mind)) - assert notes == [] - assert got["resampling"]["prs"][0]["merged"] is True - - rows[0]["mergedAt"] = None - got, _n = _batch.fetch_evidence(members, _batch.read_active(mind)) - assert got["resampling"]["prs"][0]["merged"] is False - - -def test_apply_writes_nothing_that_a_re_read_cannot_recover(tmp_path): - """The rehearsal. A ledger half-written has no way back, so the rewrite is - re-parsed on a throwaway copy before it is written for real.""" - mind = mini_mind(tmp_path) - before = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") - d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence()) - after = _batch.record_update(before, d, STAMP) - assert _batch._rehearse_record(mind, before, after) == [] - broken = after.replace(" - resampling:", " - resampling") - assert _batch._rehearse_record(mind, before, broken) - - -# ------------------------------------------------------ the kinds registry -- -def _fake_score(member, ctx): - legs = {k: (_batch.PASS, "the fake kind says so") for k in _batch.LEGS} - return {"slug": member["slug"], "kind": "fake", "id": f"m-{member['slug']}", - "title": "A phase of a science project", "health": "HEALTHY", - "eyebrow": "cortex · phase 3", "jobs": "342091", - "chip": "witness landed", "est_minutes": 15, "tier": "judge", - "pending": False, "merged": False, "flagged": [], "legs": legs, - "links": [], "notes": [], "path": member["path"], "outcome": "", - "prs": [], "summary": "", "ruling_line": "_(yours to write)_", - "review_chips": [("accept", "Accept"), ("rerun", "Rerun")]} - - -def _fake_blocks(s): - return [("Question", "Does the subhalo show up?"), - ("Ruling", s["ruling_line"])] - - -def test_the_kinds_registry_is_the_extension_point(tmp_path): - """Phase 5 registers a `cortex` kind here. Nothing about the report or the - renderer may need to change for it, which is what this pins.""" - mind = mini_mind( - tmp_path, - " - resampling: draft/bug/autofit/resampling.md — glance — 3 — " - "session ended green", - " - subhalo: phases/subhalo_validation/pl_eff.md — judge — 15 — " - "session ended green") - kinds = dict(_batch.KINDS) - kinds["fake"] = (_fake_score, _fake_blocks, - lambda m, ctx: m["path"].startswith("phases/")) - d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence(), kinds=kinds) - d["stamp"] = STAMP - assert {s["kind"] for s in d["members"]} == {"dev", "fake"} - report = _batch.collect_report(d) - assert "## subhalo — HEALTHY" in report - assert "Does the subhalo show up?" in report - page, notes = _batch.packet_html(d) - assert notes == [] - assert 'id="m-subhalo"' in page - assert "A phase of a science project" in page - assert 'value="rerun"' in page - - -def test_every_interpolated_value_is_escaped(tmp_path): - """A record, a prompt and a check name are all human-written text on a page - served from Pages.""" - mind = mini_mind( - tmp_path, - " - x: draft/bug/autofit/resampling.md — " - "glance — 3 — session ended green") - d = _batch.collect(mind, "2026-09-03-pm") - d["stamp"] = STAMP - page, _notes = _batch.packet_html(d) - assert "" not in page - assert "<script>alert(1)</script>" in page - assert page.count("")) - page, _notes = _batch.packet_html(d) - assert "" in page - assert "" in page - body = region_of(page) - assert "clean" in body and "conflicted" in body and "a.py" in body - assert "source /tmp/wt/integration-x/activate.sh" in body - assert "<script>alert(1)" in body - assert page.count("") == 1 - - -def test_the_panel_says_where_a_workspace_member_has_to_be_run(tmp_path): - """`activate.sh`'s PYTHONPATH covers the libraries only. A workspace member - is a real worktree in the root but is not importable from outside it, and a - human who runs its script from the canonical checkout tests the wrong tree.""" - mind = mini_mind(tmp_path) - page, _n = _batch.packet_html(collected(mind, block_for())) - body = region_of(page) - assert "PYTHONPATH" in body - assert "/tmp/wt/integration-x/<workspace>" in body - - -def test_a_refresh_without_an_integration_leaves_the_region_alone(tmp_path): - """A plain collect must not blank the region the last `--integration` - filled: that merge preview is still true, and the human is reading it.""" - mind = mini_mind(tmp_path) - first, _n = _batch.packet_html(collected(mind, block_for())) - was = region_of(first) - assert "Example/MyRepo" in was - second, _n = _batch.packet_html(collected(mind), first) - assert region_of(second) == was - - -def test_a_cloud_session_says_run_it_from_the_laptop(tmp_path, capsys): - """Mirrors the `--fetch` refusal: real worktrees under `$PYAUTO_WT_ROOT` are - a laptop thing, so a cloud session is pointed at the laptop rather than - failing halfway through building a root it cannot finish.""" - mind = mini_mind(tmp_path) - rc = _batch.main(["collect", "--mind", str(mind), "--slot", SLOT, - "--integration", "--lane", "web-github"]) - out = capsys.readouterr().out - assert rc == 1 - assert out.count("run collect from the laptop") == 1 - assert "## alpha — " in out # the members are still scored - - -def _recorder(monkeypatch) -> list: - calls: list = [] - - def run(members, order, slot, *, lane, push=False): - calls.append({"order": list(order), "slot": slot, "lane": lane, - "push": push}) - return None, [] - - monkeypatch.setattr(_batch, "load_integration", - lambda: SimpleNamespace(run=run)) - return calls - - -def test_the_record_can_ask_for_it_at_dispatch(tmp_path, monkeypatch): - """`- integration: yes` written at dispatch is the human saying "I will want - to run this batch" — it must not need them to remember a flag at collect.""" - calls = _recorder(monkeypatch) - mind = mini_mind(tmp_path, keys="- integration: yes") - _batch.main(["collect", "--mind", str(mind), "--slot", SLOT]) - assert [c["order"] for c in calls] == [["alpha"]] - # The record asks for the LOCAL preview. Putting a ref on GitHub is a - # separate act, and no key in a record may ever perform it. - assert [c["push"] for c in calls] == [False] - - calls.clear() - off = mini_mind(tmp_path / "off", keys="- integration: no") - _batch.main(["collect", "--mind", str(off), "--slot", SLOT]) - assert calls == [] - - -def test_apply_stamps_the_integration_root_on_the_record(tmp_path): - """A SEPARATE key. `- integration: yes` is the human's request and - `- integration-root:` is what happened; writing the second over the first - would erase what they asked for.""" - mind = mini_mind(tmp_path, keys="- integration: yes") - d = collected(mind, block_for()) - before = (mind / "batches" / f"{SLOT}.md").read_text(encoding="utf-8") - after = _batch.record_update(before, d, STAMP) - assert _batch._rehearse_record(mind, before, after) == [] - assert "- integration: yes" in after - assert ("- integration-root: /tmp/wt/integration-x — " - f"integration/{SLOT}; 1 clean, 1 conflicted") in after - - _batch.apply_collect(mind, d, STAMP) - written = (mind / "batches" / f"{SLOT}.md").read_text(encoding="utf-8") - assert "- integration: yes" in written and "- integration-root: " in written - - -def test_the_report_puts_the_source_line_at_the_top(tmp_path): - """The whole point of the leg is that the human can RUN the batch, and a - `source …` line five screens down is a line nobody sources.""" - mind = mini_mind(tmp_path) - body = _batch.collect_report(collected(mind, block_for())) - assert "## Integration branches" in body - assert "source /tmp/wt/integration-x/activate.sh" in body - assert body.index("## Integration branches") < body.index("## alpha") - assert ("- Example/Other — conflicted — " in body - and "collides on a.py — left out" in body) - - -def test_plan_refuses_the_collect_flag(tmp_path): - """`batch plan --integration` means something, and it is not "plan".""" - mind = mini_mind(tmp_path) - (mind / "draft").mkdir(exist_ok=True) - assert _batch.main(["plan", "--mind", str(mind), "--integration"]) == 2 - - -# --------------------------------------------------------- the push, wired -- -def test_push_without_integration_is_a_usage_error(tmp_path, capsys): - """`--push` publishes what `--integration` built. Alone it would either - silently do nothing or push a branch nobody previewed; it is neither.""" - mind = mini_mind(tmp_path) - rc = _batch.main(["collect", "--mind", str(mind), "--slot", SLOT, "--push"]) - assert rc == 2 - assert "pass both" in capsys.readouterr().err - - -def test_plan_refuses_the_push_flag(tmp_path): - """`batch plan --push` means something, and it is not "plan".""" - mind = mini_mind(tmp_path) - (mind / "draft").mkdir(exist_ok=True) - assert _batch.main(["plan", "--mind", str(mind), "--push"]) == 2 - - -def test_a_cloud_session_says_run_the_push_from_the_laptop(tmp_path, capsys): - """A second reason for the same refusal, said instead of the first: a - remote session's GH_TOKEN is a proxy placeholder that cannot write a ref at - all, so "build a worktree on the laptop" would be the wrong advice.""" - mind = mini_mind(tmp_path) - rc = _batch.main(["collect", "--mind", str(mind), "--slot", SLOT, - "--integration", "--push", "--lane", "web-github"]) - out = capsys.readouterr().out - assert rc == 1 - assert "Run it from the laptop" in out - assert "GITHUB_ACCESS.md" in out - assert "## alpha — " in out # the members are still scored - - -def test_apply_stamps_the_remote_branches_and_a_default_sweep_after(tmp_path): - """What was PUBLISHED, per repo, under the name the branch sweep matches - on — and the date after which it may delete them. The default hangs off - `review-at:`, because the review is the branch's reason to exist.""" - mind = mini_mind(tmp_path, keys="- integration: yes") - d = collected(mind, block_for(pushed=True)) - assert d["review_at"] == "2026-09-04T08:00Z" - notes: list = [] - d["integration"]["sweep_after"] = _batch.sweep_after_default( - d["review_at"], notes) - assert notes == [] - - before = (mind / "batches" / f"{SLOT}.md").read_text(encoding="utf-8") - after = _batch.record_update(before, d, STAMP) - assert _batch._rehearse_record(mind, before, after) == [] - assert (f"- integration-remote: MyRepo:integration/{SLOT}, " - f"Other:integration/{SLOT}") in after - assert "- sweep-after: 2026-09-11" in after - assert "- integration: yes" in after and "- integration-root: " in after - - _batch.apply_collect(mind, d, STAMP) - written = (mind / "batches" / f"{SLOT}.md").read_text(encoding="utf-8") - assert "- integration-remote: " in written - assert "- sweep-after: 2026-09-11" in written - - -def test_a_human_written_sweep_after_is_never_overwritten(tmp_path): - """The default is a default. A date the human typed is a decision about - their own review, and a second `- sweep-after:` line would leave the sweep - reading whichever it hit first.""" - mind = mini_mind(tmp_path, - keys="- integration: yes\n- sweep-after: 2026-12-01") - d = collected(mind, block_for(pushed=True)) - assert d["sweep_after"] == "2026-12-01" - d["integration"]["sweep_after"] = d["sweep_after"] - _batch.apply_collect(mind, d, STAMP) - written = (mind / "batches" / f"{SLOT}.md").read_text(encoding="utf-8") - assert "- sweep-after: 2026-12-01" in written - assert written.count("- sweep-after:") == 1 - assert "2026-09-11" not in written - - -def test_an_unreadable_review_at_falls_back_to_today_plus_seven(tmp_path): - """A silently guessed deletion date is the one guess a branch sweep must - never act on unexplained — so the fallback says so in the notes.""" - import datetime as dt - notes: list = [] - got = _batch.sweep_after_default("(not given)", notes) - want = (dt.datetime.now(dt.timezone.utc).date() - + dt.timedelta(days=_batch.SWEEP_DAYS)).isoformat() - assert got == want - assert len(notes) == 1 - assert "does not read as a date" in notes[0] - assert "edit the record to change it" in notes[0] - - -def test_the_panel_and_the_report_name_the_remote_and_the_expiry(tmp_path): - """Written once in `_integ_detail`, so the terminal and the page cannot - report the same publication differently — and the expiry is stated on both, - because a ref with a deletion date the reader never saw is a trap.""" - mind = mini_mind(tmp_path) - block = block_for(pushed=True) - block["sweep_after"] = "2026-09-11" - d = collected(mind, block) - - body = _batch.collect_report(d) - assert f"pushed to origin/integration/{SLOT}" in body - assert "may delete these after **2026-09-11**" in body - assert "Never a PR, never a base." in body - assert "collides on a.py — left out" in body - - page, _n = _batch.packet_html(d) - region = region_of(page) - assert f"pushed to origin/integration/{SLOT}" in region - assert "2026-09-11" in region - assert "Never a PR, never a base." in region - assert "Nothing is pushed" not in region # it no longer is true - assert page.count("") == 1 - assert "data-" not in region - - -def test_an_unpushed_block_still_promises_nothing_is_pushed(tmp_path): - """The default leg's promise is unchanged — and it is the promise, not the - prose, that the flag has to be able to withdraw.""" - mind = mini_mind(tmp_path) - page, _n = _batch.packet_html(collected(mind, block_for())) - region = region_of(page) - assert "Nothing is pushed and nothing is resolved" in region - assert "pushed to origin/" not in region - assert "sweep" not in region diff --git a/tests/test_batch_records.py b/tests/test_batch_records.py new file mode 100644 index 00000000..dbd31eb8 --- /dev/null +++ b/tests/test_batch_records.py @@ -0,0 +1,59 @@ +"""The batch records the planner still reads: the newest slot and what it +carried forward. (The `batch collect` verb that wrote these was retired.)""" +from __future__ import annotations + +import importlib.util +import sys +from pathlib import Path + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) +_spec = importlib.util.spec_from_file_location( + "_batch_records_under_test", + BRAIN / "agents" / "conductors" / "batch" / "_batch.py") +_batch = importlib.util.module_from_spec(_spec) +sys.modules["_batch_records_under_test"] = _batch +_spec.loader.exec_module(_batch) + +RECORD = """# Batch 2026-09-03-pm + +- dispatched: 2026-09-03T17:00Z +- members: + - resampling: draft/bug/autofit/resampling.md — glance — 3 — session ended green +- outcomes: + - resampling: carried + - other: merged +- notes: | + free text +""" + + +def _mind(tmp_path) -> Path: + mind = tmp_path / "mind" + (mind / "batches").mkdir(parents=True) + (mind / "draft").mkdir() + (mind / "batches" / "2026-09-03-am.md").write_text("# Batch\n", encoding="utf-8") + (mind / "batches" / "2026-09-03-pm.md").write_text(RECORD, encoding="utf-8") + return mind + + +def test_flags_of_other_verbs_are_refused_on_plan(tmp_path): + assert _batch.main(["plan", "--mind", str(_mind(tmp_path)), "--apply"]) == 2 + + +def test_collect_is_no_longer_a_verb(tmp_path): + import pytest + with pytest.raises(SystemExit) as e: + _batch.main(["collect", "--mind", str(_mind(tmp_path))]) + assert e.value.code == 2 + + +def test_the_newest_slot_sort_is_lexical(tmp_path): + mind = _mind(tmp_path) + assert _batch.newest_slot(mind) == "2026-09-03-pm" + (mind / "batches" / "2026-09-03-night.md").write_text(RECORD, encoding="utf-8") + assert _batch.newest_slot(mind) == "2026-09-03-pm" + + +def test_previous_carried_reads_the_newest_records_outcomes(tmp_path): + assert _batch.previous_carried(_mind(tmp_path)) == ("2026-09-03-pm", ["resampling"]) diff --git a/tests/test_orchestrator_events.py b/tests/test_orchestrator_events.py index 74021232..b5898148 100644 --- a/tests/test_orchestrator_events.py +++ b/tests/test_orchestrator_events.py @@ -405,12 +405,9 @@ def poster(issue, body_file): assert not orch.mentions_due(slot) and c["event_comments"] == 1 and c["pushes"] == 0 -def test_needs_you_comments_never_raise_the_push_finding(): - c = {"pushes": 1, "event_comments": 6, "workers": [], "picks": {}} - lines = orch._digest.worker_lines(c) - assert not any("pushes this shift" in x for x in lines) - assert "- needs-you event comments: 6 (at most 5 + 1 a shift)" in lines - assert any("2 pushes this shift" in x for x in orch._digest.worker_lines({**c, "pushes": 2})) +def test_needs_you_comments_are_counted_in_the_digest(): + c = {"pushes": 0, "event_comments": 6, "workers": [], "picks": {}} + assert "- needs-you event comments: 6 (at most 5 + 1 a shift)" in orch._digest.worker_lines(c) def test_a_ci_line_comes_again_after_a_change_and_never_repeats_otherwise(tmp_path): diff --git a/tests/test_orchestrator_mentions.py b/tests/test_orchestrator_mentions.py index bfa66246..647fbd7a 100644 --- a/tests/test_orchestrator_mentions.py +++ b/tests/test_orchestrator_mentions.py @@ -1,16 +1,7 @@ -"""PyAutoBrain#611 (M1.6): the @mention machinery on the shift's digest issue -(the human's channel ruling, 2026-11-12). The `gh` call sits behind a fake -`run`, so nothing reaches GitHub; the login comes from the environment or -config, never the code. - -M3.5 (PyAutoBrain#645, Decision H7 a) removed the two triggers this file was -written for: a parked worker and a question now land in the questions inbox -and no longer @-mention anyone. The machinery (markers, one post per worker -per state, retries, the late sweep, the posting identity) stays for other -needs-you triggers, so these tests drive it with a stand-in trigger (a parked -worker, as the old one); the tests marked `real_triggers` pin that the real -ones are gone. -""" +"""Nobody is @-mentioned mid-shift: a parked worker and a question land in the +questions inbox. Also the human's login (environment or config, never the +code) and the watcher's own posting token. The `gh` call sits behind a fake +`run`, so nothing reaches GitHub.""" from __future__ import annotations @@ -29,18 +20,6 @@ NOW = d.NOW -def _stand_in_trigger(counters, held): - """A needs-you trigger for the machinery tests: a parked worker.""" - return [(task, "parked", "blocked on a person" + ( - f" (blocked since {(held.get(task) or {}).get('stalled_since')})" - if (held.get(task) or {}).get("stalled_since") else "")) - for task in counters["parked"]] - - -@pytest.fixture(autouse=True) -def _trigger(request, monkeypatch): - if "real_triggers" not in request.keywords: - monkeypatch.setattr(orch, "_mention_triggers", _stand_in_trigger) ISSUE = "https://github.com/example-org/example-mind/issues/4242" LOGIN = "example-human" PAST_GRACE = NOW + _dt.timedelta(minutes=1, seconds=orch.STALL_GRACE_S) @@ -95,51 +74,6 @@ def _tick(brief, mind, home, now, claude, gh, agents=None): poster=lambda issue, body: orch.gh_comment(issue, body, run=gh)) -def _park(brief, mind, home, slot, claude, gh): - blocked = lambda: d._agents({"t1": "blocked"}, slot) # noqa: E731 - _tick(brief, mind, home, NOW, claude, gh) - _tick(brief, mind, home, NOW + _dt.timedelta(minutes=1), claude, gh, blocked()) - return _tick(brief, mind, home, PAST_GRACE, claude, gh, blocked()) - - -@pytest.mark.usefixtures("shift_held_open") # M3.7c: no early close -def test_a_parked_worker_makes_exactly_one_mention_and_a_second_tick_none(tmp_path, monkeypatch): - mind, brief, home, slot = _shift(tmp_path, monkeypatch) - claude, gh = d.FakeClaude(), FakeGh() - r = _park(brief, mind, home, slot, claude, gh) - assert r["reaped"][0]["event"] == "parked" - assert len(gh.calls) == 1 - argv, body = gh.calls[0] - assert argv[:4] == ["gh", "issue", "comment", ISSUE] - assert body.startswith(f"@{LOGIN} shift `shift`: the worker on `t1` needs you — parked.") - assert "- reason: blocked on a person (blocked since 2026-11-04T09:01:00Z)" in body - assert "session `00000001`" in body and "draft/feature/pyautobrain/t1.md" in body - r = _tick(brief, mind, home, PAST_GRACE + _dt.timedelta(minutes=5), claude, gh, - d._agents({"t1": "blocked"}, slot)) - assert len(gh.calls) == 1 and "mentions" not in r - c = orch.read_counters(slot) - assert c["pushes"] == 1 - text = _digest.build(_brief.parse(brief.read_text())["brief"], slot, c, - health=lambda u: "HEALTHY") - assert "- pushes: 1" in text and "(00000001): spawned/parked" in text - assert "mentioned (parked)" in text - - -@pytest.mark.usefixtures("shift_held_open") # M3.7c: no early close -def test_a_failed_mention_is_retried_on_the_next_tick(tmp_path, monkeypatch): - mind, brief, home, slot = _shift(tmp_path, monkeypatch) - claude, gh = d.FakeClaude(), FakeGh(fail=1) - r = _park(brief, mind, home, slot, claude, gh) - assert r["mentions"] == [{"task": "t1", "state": "parked", "post": "failed", "retry": 1}] - assert orch.read_counters(slot)["pushes"] == 0 - blocked = lambda: d._agents({"t1": "blocked"}, slot) # noqa: E731 - r = _tick(brief, mind, home, PAST_GRACE + _dt.timedelta(minutes=3), claude, gh, blocked()) - assert r["mentions"] == [{"task": "t1", "state": "parked", "post": "posted", "retry": 2}] - assert len(gh.calls) == 2 and gh.calls[0][1] == gh.calls[1][1] # the same comment - _tick(brief, mind, home, PAST_GRACE + _dt.timedelta(minutes=6), claude, gh, blocked()) - assert len(gh.calls) == 2 and orch.read_counters(slot)["pushes"] == 1 - - def test_a_worker_that_finishes_normally_makes_no_mention(tmp_path, monkeypatch): mind, brief, home, slot = _shift(tmp_path, monkeypatch) claude, gh = d.FakeClaude(), FakeGh() @@ -167,7 +101,6 @@ def _question_ops(slot): if json.loads(f.read_text()).get("op") == "question-add"] -@pytest.mark.real_triggers @pytest.mark.usefixtures("shift_held_open") # M3.7c: no early close def test_a_worker_parked_on_its_issue_is_filed_in_the_inbox_not_mentioned(tmp_path, monkeypatch): @@ -205,7 +138,6 @@ def test_only_an_explicit_verdict_is_not_a_push(tmp_path, monkeypatch): "QUESTION https://github.com/o/r/issues/77\n", "verdikt: https://github.com/o/r/issues/77\n", "blocked: https://github.com/o/r/issues/77\n"]) -@pytest.mark.real_triggers @pytest.mark.usefixtures("shift_held_open") # M3.7c: no early close def test_any_issue_not_marked_verdict_is_filed_in_the_inbox(tmp_path, monkeypatch, done): """PyAutoBrain#632 review: the test fails toward the human — a bare URL, a @@ -233,89 +165,19 @@ def test_the_login_comes_from_the_environment_or_config_never_the_code(tmp_path, assert orch.mention_login() == LOGIN monkeypatch.setenv(orch.MENTION_ENV, "not a login; rm -rf") assert orch.mention_login() == "" - mind, brief, home, slot = _shift(tmp_path, monkeypatch, login="") - monkeypatch.delenv(orch.MENTION_ENV, raising=False) - claude, gh = d.FakeClaude(), FakeGh() - _park(brief, mind, home, slot, claude, gh) - body = gh.calls[0][1] - assert "@" not in body.split("\n")[0] and orch.MENTION_ENV in body - - -# --- #611 review ------------------------------------------------------------------- - -@pytest.mark.usefixtures("shift_held_open") # M3.7c: no early close -def test_a_tick_that_died_after_parking_still_mentions_on_the_next(tmp_path, monkeypatch): - """Review item 1: the trigger is durable state, not the parking tick's events.""" - mind, brief, home, slot = _shift(tmp_path, monkeypatch) - claude, gh = d.FakeClaude(), FakeGh() - real = orch._mentions - blocked = lambda: d._agents({"t1": "blocked"}, slot) # noqa: E731 - _tick(brief, mind, home, NOW, claude, gh) - _tick(brief, mind, home, NOW + _dt.timedelta(minutes=1), claude, gh, blocked()) - monkeypatch.setattr(orch, "_mentions", lambda *a, **k: (_ for _ in ()).throw( - RuntimeError("tick died"))) - try: - _tick(brief, mind, home, PAST_GRACE, claude, gh, blocked()) # parks, then dies - except RuntimeError: - pass - assert orch.read_counters(slot)["parked"] == ["t1"] and gh.calls == [] - orch._drop_lock(slot) - monkeypatch.setattr(orch, "_mentions", real) - _tick(brief, mind, home, PAST_GRACE + _dt.timedelta(minutes=3), claude, gh, - d._agents({"t1": "blocked"}, slot)) - assert len(gh.calls) == 1 and "needs you — parked." in gh.calls[0][1] -@pytest.mark.usefixtures("shift_held_open") # M3.7c: no early close -def test_a_failed_mention_is_retried_in_the_late_sweep(tmp_path, monkeypatch): - mind, brief, home, slot = _shift(tmp_path, monkeypatch) - claude, gh = d.FakeClaude(), FakeGh(fail=1) - _park(brief, mind, home, slot, claude, gh) - assert len(gh.calls) == 1 # failed - after = NOW + _dt.timedelta(hours=3) - poster = lambda issue, body: orch.gh_comment(issue, body, run=gh) # noqa: E731 - orch.tick(brief, mind, home=home, now=after, grace_s=0, poster=poster, - agents=d._agents({"t1": "blocked"}, slot), tokens=lambda s: 0, - pr_state=lambda u: None, health=lambda u: "HEALTHY") # digest + finish - r = orch.tick(brief, mind, home=home, now=after + _dt.timedelta(minutes=5), grace_s=0, - poster=poster, agents=d._agents({"t1": "blocked"}, slot), - tokens=lambda s: 0) - assert r["action"] == "late" - assert r["posts"]["mentions"] == [{"task": "t1", "state": "parked", "post": "posted", - "retry": 2}] - mention_calls = [b for _, b in gh.calls if "needs you" in b] - assert len(mention_calls) == 2 and orch.read_counters(slot)["pushes"] == 1 - - -@pytest.mark.usefixtures("shift_held_open") # M3.7c: no early close -def test_a_separate_token_posts_and_a_self_mention_is_warned(tmp_path, monkeypatch): - """Review item 4: PYAUTO_SHIFT_GH_TOKEN is given to the watcher's `gh` as - GH_TOKEN; mentioning the posting account itself is a digest warning.""" - mind, brief, home, slot = _shift(tmp_path, monkeypatch) +def test_the_watchers_gh_calls_carry_its_own_token(monkeypatch): + """PYAUTO_SHIFT_GH_TOKEN is given to the watcher's `gh` as GH_TOKEN.""" monkeypatch.setenv(orch.GH_TOKEN_ENV, "test-token-not-real") - claude, gh = d.FakeClaude(), FakeGh() - envs = [] + gh, envs = FakeGh(), [] def run(argv, **kw): envs.append((kw.get("env") or {}).get("GH_TOKEN")) return gh(argv, **kw) - blocked = lambda: d._agents({"t1": "blocked"}, slot) # noqa: E731 - asked = [] - for now, agents in ((NOW, None), (NOW + _dt.timedelta(minutes=1), blocked), - (PAST_GRACE, blocked), (PAST_GRACE + _dt.timedelta(minutes=3), blocked)): - orch.tick(brief, mind, home=home, now=now, grace_s=0, - spawner=orch.RealSpawner(brief, "auto", run=claude), - agents=agents() if agents else orch.AgentsView([]), tokens=lambda s: 0, - poster=lambda i, b: orch.gh_comment(i, b, run=run), - whoami=lambda: asked.append(1) or LOGIN) - assert envs == ["test-token-not-real"] and asked == [1] # checked once per shift - c = orch.read_counters(slot) - text = _digest.build(_brief.parse(brief.read_text())["brief"], slot, c, - health=lambda u: "HEALTHY") - assert "mention will not notify: posted as the mentioned account" in text - c.update(poster_login="example-bot") - assert "will not notify" not in _digest.build( - _brief.parse(brief.read_text())["brief"], slot, c, health=lambda u: "HEALTHY") + body = Path(__file__) + orch.gh_comment(ISSUE, body, run=run) + assert envs == ["test-token-not-real"] login_calls = [] assert orch.gh_login(run=lambda argv, **kw: login_calls.append((argv, kw["env"]["GH_TOKEN"])) or SimpleNamespace(returncode=0, stdout="example-bot\n")) == "example-bot" diff --git a/tests/test_questions_inbox.py b/tests/test_questions_inbox.py index d6983798..6c833597 100644 --- a/tests/test_questions_inbox.py +++ b/tests/test_questions_inbox.py @@ -145,13 +145,6 @@ def test_a_worker_blocked_past_the_grace_lands_a_blocked_entry_on_the_shift_issu "(session 00000001, since 2026-11-04T09:01") -def test_mention_triggers_no_longer_fire_for_questions_or_parks(): - counters = orch.read_counters(Path("/nonexistent")) - counters["parked"] = ["t1"] - counters["outcomes"] = {"t2": {"questions": [Q1], "issues": [Q1], "prs": [], "merged": []}} - assert orch._mention_triggers(counters, {}) == [] - - def test_the_status_comment_counts_the_inbox(tmp_path): mind, brief, home, slot = _shift(tmp_path, names=("t1",)) claude, gh = d.FakeClaude(), FakeGh() From 14e9a518463e2528e686f68323376a59b67d2508 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:50:31 +0000 Subject: [PATCH 2/6] docs(batch): move incident history out of code comments Comments and docstrings in the batch conductor now say what the code does and why, in the present tense; dates, milestone tags and incident narratives are left to git history. Comment-only: each file's AST with docstrings stripped is unchanged. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016nhQ8NtYMv2K9yt336CnGn --- agents/conductors/batch/_app_token.py | 16 +- agents/conductors/batch/_batch.py | 332 +++--- agents/conductors/batch/_brief.py | 96 +- agents/conductors/batch/_digest.py | 244 +++-- agents/conductors/batch/_events.py | 26 +- agents/conductors/batch/_green.py | 24 +- agents/conductors/batch/_login.py | 11 +- agents/conductors/batch/_merge_slots.py | 19 +- agents/conductors/batch/_mind_writer.py | 198 ++-- agents/conductors/batch/_orchestrator.py | 1167 +++++++++++----------- agents/conductors/batch/_premise.py | 10 +- agents/conductors/batch/_questions.py | 24 +- agents/conductors/batch/_ral.py | 17 +- agents/conductors/batch/_ready.py | 32 +- agents/conductors/batch/_status.py | 15 +- agents/conductors/batch/_steer.py | 39 +- agents/conductors/batch/_sweep.py | 24 +- agents/conductors/batch/_watch.py | 42 +- 18 files changed, 1102 insertions(+), 1234 deletions(-) diff --git a/agents/conductors/batch/_app_token.py b/agents/conductors/batch/_app_token.py index dac0d321..6a87b83d 100644 --- a/agents/conductors/batch/_app_token.py +++ b/agents/conductors/batch/_app_token.py @@ -1,4 +1,4 @@ -"""The shift watcher's own GitHub identity: a minimal GitHub App (PyAutoBrain#630). +"""The shift watcher's own GitHub identity: a minimal GitHub App. The watcher posts its comments (status, mentions, digest, correction) and reads the shift issue's comments as its own App, `pyautolabs-watcher` — Issues @@ -17,13 +17,13 @@ no shell) and mints an installation token (`POST /app/installations//access_tokens`) on the first watcher GitHub call of a tick, reuses it for the rest of that tick, and keeps it **in memory only**: no token is ever written to disk, where a worker -running as the same user could read it (#630 review). A failed mint is -remembered on disk as a timestamp and a reason only (`MINT_FAILURE_FILE`), so -the next mint waits `MINT_BACKOFF_S`. With none set, `PYAUTO_SHIFT_GH_TOKEN` (a -static token) is the fallback, and with neither, `gh`'s own auth, as before. -When the App is configured but no token can be had, the watcher's own GitHub -calls are not made at all: never the human's `gh` auth in their place. No error -message carries the key, a JWT or a token. +running as the same user could read it. A failed mint is remembered on disk as +a timestamp and a reason only (`MINT_FAILURE_FILE`), so the next mint waits +`MINT_BACKOFF_S`. With none set, `PYAUTO_SHIFT_GH_TOKEN` (a static token) is the +fallback, and with neither, `gh`'s own auth. When the App is configured but no +token can be had, the watcher's own GitHub calls are not made at all: never the +human's `gh` auth in their place. No error message carries the key, a JWT or a +token. Runs under the systemd unit's `/usr/bin/python3` (3.10): standard library plus an optional PyJWT. diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 7848085b..640fde03 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -1,21 +1,19 @@ #!/usr/bin/env python3 """agents/conductors/batch/_batch.py — the batch conductor. -Composes what goes into one unattended shift. Thin -by construction: every judgement it uses — consequence tier, review-minutes, -readiness, difficulty — belongs to the sizing faculty, because `ORGANISM.md` -makes faculties the opinion sinks and forbids a conductor consulting a -conductor. This module decides *membership*, which is an act, not an opinion. +Composes what goes into one unattended shift. Thin by construction: every +judgement it uses — consequence tier, review-minutes, readiness, difficulty — +belongs to the sizing faculty, because `ORGANISM.md` makes faculties the +opinion sinks and forbids a conductor consulting a conductor. This module +decides *membership*, which is an act, not an opinion. -The composition rule, and the reason the epic exists: +The composition rule: sum(Review-minutes) over `glance` and `judge` members <= the slot budget -not a task count. The budget is the human's to set per slot (default 45) — a -slot is whenever they come in, not a scheduled hour. Read against the ledger, an -honest review hour holds about three library-touching tasks; a design that plans -by count over-promises capacity roughly threefold and lands the overflow on the -human at 6am. +not a task count: a plan by count over-promises the human's review capacity. +The budget is the human's to set per slot (default 45) — a slot is whenever +they come in, not a scheduled hour. Everything above that budget is the FILL: work costing zero review-minutes (`notify`-tier work, slicing, witness authoring, re-grading, deeper verification @@ -48,15 +46,14 @@ ) sys.path.insert(0, str(Path(__file__).resolve().parent)) import _brief # noqa: E402 -import _green # noqa: E402 — the keep-Heart-green lane (PyAutoBrain#625) -import _login # noqa: E402 — the CLI login probe (M3.6a, PyAutoBrain#659) +import _green # noqa: E402 — the keep-Heart-green lane +import _login # noqa: E402 — the CLI login probe import _ral # noqa: E402 — the unattended-ssh probe for a granted `ral` lane -# The human's goals (goals.md, PyAutoMind#565): `brief --new` copies them. +# The human's goals (goals.md): `brief --new` copies them. from _steer import read_goals # noqa: E402,F401 — re-exported beside read_queue # The close-out guard's reader (intake `looks-shipped`): the live flags minus -# human dismissals. Loaded by path — a plain `import _shipped` would also work -# once intake's directory is on sys.path, but this keeps the batch planner from -# shadowing anything else of that name. +# human dismissals. Loaded by path, so the batch planner shadows nothing else +# of that name. _shipped_spec = importlib.util.spec_from_file_location( "_shipped_for_batch", BRAIN / "agents" / "conductors" / "intake" / "_shipped.py") _shipped = importlib.util.module_from_spec(_shipped_spec) @@ -68,8 +65,8 @@ # docstring. 45 rather than 60 because a slot also has to queue the next batch. DEFAULT_REVIEW_BUDGET = 45 # Above half the cap the review-bearing half is halved; at the cap the batch is -# fill only. Counted in TASKS AWAITING REVIEW, never in PRs: 94 of 332 records in -# 2026-08 named two or more PRs, so a PR-count cap trips on one healthy batch. +# fill only. Counted in TASKS AWAITING REVIEW, never in PRs: one task often +# names two or more PRs, so a PR-count cap would trip on one healthy batch. DEFAULT_BACKPRESSURE_CAP = 8 CHEAP_TIERS = ("notify",) @@ -77,12 +74,11 @@ def detect_lane() -> str: """`local-dev` or `web-github` — where this session is running. - Probed from the environment rather than declared, and deliberately from the - same signal the rest of the organism already uses: a remote session has no - `gh` (measured, documented in `skills/GITHUB_ACCESS.md` — installing one is - a trap that authenticates and then 403s every repo-scoped call). No env var - and no flag decides this; a session that could lie about where it is could - plan `local-dev` work it cannot run. + Probed from the environment rather than declared, from the same signal the + rest of the organism uses: a remote session has no `gh` + (`skills/GITHUB_ACCESS.md`). No env var and no flag decides this; a + session that could lie about where it is could plan `local-dev` work it + cannot run. """ return "local-dev" if shutil.which("gh") else "web-github" @@ -97,10 +93,10 @@ def _lane_ok(record_lane: str, session_lane: str) -> bool: def lane_absent_why(r: dict) -> str: """Why an unattended pick refuses this record for want of a lane, or "". - Fail closed (M2.3, human ruling 2026-11-12): a draft with no valid `Lane:` - is excluded from every unattended or cloud pick, because a lane-less draft - that needs the laptop, RAL or private data would otherwise reach a cloud - worker and burn its run. An attended session still reads it as `any`. + Fail closed: a draft with no valid `Lane:` is excluded from every + unattended or cloud pick, because a lane-less draft that needs the laptop, + RAL or private data would otherwise reach a cloud worker and burn its run. + An attended session still reads it as `any`. Worded without a colon: `emit` groups rejections on the text before one.""" if r.get("lane"): return "" @@ -117,8 +113,8 @@ def declared_repos(p: dict) -> list[str]: `Target:` is not unioned into a declared `Repos:` block: it is often only an epic label (a prompt with `Target: autofit` whose `Repos:` lists only - PyAutoCortex), so adding it made the claim gate report a false conflict - on a repo the prompt never touches (PyAutoBrain#675).""" + PyAutoCortex), and adding it would make the claim gate report a false + conflict on a repo the prompt never touches.""" from _sizing import KNOWN_REPOS # noqa: E402 out = set() block = re.search(r"^Repos:\n((?:- .+\n)+)", p.get("text") or "", re.M) @@ -153,28 +149,27 @@ def grade(path: Path, mind: Path, text: str | None = None) -> dict: "unattended": ready, "why": (why or [""])[0], "ready_why": ready_why, "epic": None, # The DECLARED lane, or None when the header has no valid `Lane:`. - # Absence is no longer read as `any` here (M2.3, AUTONOMY.md "M2 - # rulings — 2026-11-12"): `plan` excludes a lane-less draft from an - # unattended pick and reads it as `any` only when `attended=True`. + # Absence is not read as `any` here (AUTONOMY.md "M2 rulings"): + # `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. + # 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")), - # What it waits for, so a rejection names it (M3.6b: a side task - # orders itself after its epic's phase by `Blocked-by:`). + # What it waits for, so a rejection names it (a side task orders + # itself after its epic's phase by `Blocked-by:`). "blocked_by": list(p.get("blocked_by") or []), } # A prompt whose own header says the work is finished. Mirrors intake's -# DONE_STATUSES: a session that ships the work and writes the outcome into -# `Status:` but leaves the file in `draft/` is a known, recorded failure mode, -# and the file keeps rendering as pickable backlog until someone retires it. -# Dispatching one wastes a whole shift re-doing finished work. +# DONE_STATUSES: a session can ship the work and write the outcome into +# `Status:` but leave the file in `draft/`, where it keeps rendering as +# pickable backlog. Dispatching one wastes a whole shift re-doing finished work. DONE_STATUSES = ("shipped", "superseded", "absorbed", "complete", "completed", "done", "retired") @@ -211,8 +206,8 @@ def _is_done(text: str) -> bool: def _phase_of(text: str) -> float: """`Phase: ` as a sortable number; phase-less members sort last.""" raw = _header_of(text, "phase") - # The leading number: `5a`/`5A` → 5, `6b2` → 6 (M3.6b review). A label - # with no leading number (`C2`) sorts last but is still a declared phase + # The leading number: `5a`/`5A` → 5, `6b2` → 6. A label with no leading + # number (`C2`) sorts last but is still a declared phase # (`_phase_declared`), so the per-epic limit counts it. m = re.match(r"\s*(\d+(?:\.\d+)?)", raw) return float(m.group(1)) if m else float("inf") @@ -227,8 +222,7 @@ def survey(mind: Path) -> list[dict]: one-slice-per-epic rule.""" out = [] # Backpressure from the close-out guard: a draft with strong evidence that - # its work already shipped waits for a human to close or dismiss it. The - # 2026-11-05-am batch proposed two shipped tasks; this is the stop. + # its work already shipped waits for a human to close or dismiss it. flagged = _shipped.flagged_paths(mind) for f in sorted(mind.glob("draft/**/*.md")): if f.name == "README.md": @@ -249,8 +243,8 @@ def survey(mind: Path) -> list[dict]: def grade_text(text: str, rel: str, mind: Path) -> dict: """One `survey` record from a prompt's text as Mind origin/main holds it - (`/add`, PyAutoBrain#644): the canonical working tree nobody pulls - mid-shift may not have it yet. `rel` is its Mind-relative path.""" + (`/add`): the canonical working tree nobody pulls mid-shift may not have + it yet. `rel` is its Mind-relative path.""" g = grade(Path(mind) / rel, Path(mind), text=text) g["path"] = rel g["looks_shipped"] = rel in _shipped.flagged_paths(mind) @@ -273,7 +267,7 @@ def _title_of(text: str) -> str: # `read_queue` (and its grammar) lives in `_steer.py`, so the Mind dashboard -# ranks its read-only stars with this same reader (PyAutoBrain#640). +# ranks its read-only stars with this same reader. from _steer import read_queue # noqa: E402 @@ -282,8 +276,7 @@ def queue_rank(r: dict, queue: list[str]) -> int: Matched on the path, then the basename, because a queue entry is written against `draft/…` and the prompt it names moves to `active/` the moment it - is issued — an entry that stopped matching would silently lose its - priority rather than reporting anything.""" + is issued — a path-only match would silently lose its priority.""" path = r.get("path") or "" if path in queue: return queue.index(path) @@ -329,10 +322,10 @@ def read_epic_ledgers(mind: Path) -> dict[str, str]: def queued_epics(queue: list[str], records: list[dict], epic_ledgers: dict[str, str] | None = None) -> dict[str, int]: """{epic slug: queue index} for every queue entry that names an epic - ledger (PyAutoBrain#696). An entry is an epic when the prompt it names is - a ledger (`ledger` in its survey record: `Epic:`, no `Phase:`, `Status: - campaign map`), or when `epics.md` lists it as an epic's `- ledger:`. - A queued phase or side task queues only itself. The first entry wins.""" + ledger. An entry is an epic when the prompt it names is a ledger (`ledger` + in its survey record: `Epic:`, no `Phase:`, `Status: campaign map`), or + when `epics.md` lists it as an epic's `- ledger:`. A queued phase or side + task queues only itself. The first entry wins.""" by_path = {r.get("path") or "": r for r in records} by_name: dict[str, dict] = {} for r in records: @@ -352,11 +345,11 @@ def queued_epics(queue: list[str], records: list[dict], def queue_standing(r: dict, queue: list[str], epic_ranks: dict[str, int] | None = None) -> tuple[int, str]: """(rank, epic it is queued through or "") — the ONE answer to "is this - record queued?" (PyAutoBrain#696). Queued directly (`queue_rank`), or as - a member of a queued epic ledger, at the ledger's rank, whichever is - higher in the file. `rank == len(queue)` is unqueued. Only the queue - standing changes: every gate of `pool_gate` (phase order, autonomy, - Unattended, Blocked-by) still applies to the member.""" + record queued?". Queued directly (`queue_rank`), or as a member of a + queued epic ledger, at the ledger's rank, whichever is higher in the file. + `rank == len(queue)` is unqueued. Only the queue standing changes: every + gate of `pool_gate` (phase order, autonomy, Unattended, Blocked-by) still + applies to the member.""" direct = queue_rank(r, queue) epic = r.get("epic") or "" via = (epic_ranks or {}).get(epic) if epic and not r.get("ledger") else None @@ -382,18 +375,17 @@ def pool_gate(r: dict, next_phase: dict[str, float]) -> str: Every gate but the lane, which depends on the session. Readiness says the work FITS one run; autonomy says the run may FINISH it. Under `--auto` a `supervised` run's ship checkpoint resolves to decide-and-flag - (AUTONOMY.md, "Decide-and-flag", extended 2026-09-07): it ships to an open - PR rather than parking, so it FINISHES and belongs in the pool. Only - `human-required` would still stop at the ship checkpoint and come back as - a question — which is the failure the whole epic exists to remove.""" + (AUTONOMY.md, "Decide-and-flag"): it ships to an open PR rather than + parking, so it FINISHES and belongs in the pool. Only `human-required` + would still stop at the ship checkpoint and come back as a question.""" if r.get("done"): return "Status: says the work is already done" if r.get("looks_shipped"): return ("looks shipped — confirm (close) or " f"dismiss it ({_shipped.DISMISS_FILE}) first") - # Phase order binds only a task with a `Phase:` number (ruling R5, option - # a, 2026-11-17): a side task of the epic (no `Phase:`) is not a later - # phase, and orders itself by `Blocked-by:` below. + # Phase order binds only a task with a `Phase:` number: a side task of + # the epic (no `Phase:`) is not a later phase, and orders itself by + # `Blocked-by:` below. if r.get("epic") and has_phase(r) and r["phase"] == float("inf") \ and next_phase.get(r["epic"], float("inf")) < float("inf"): return f"epic {r['epic']} phase (unnumbered) is not next" @@ -421,11 +413,11 @@ def has_phase(r: dict) -> bool: 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.""" + """Why a shift never dips this draft, or "": 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}) @@ -438,9 +430,9 @@ def self_organ_why(r: dict) -> str: 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.""" + 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: @@ -461,10 +453,10 @@ def scoped_reach_why(r: dict) -> str: def queued_epic_summary(records: list[dict], epic_ranks: dict[str, int], members: list[dict], rejected: list[tuple[str, str]], queue: list[str]) -> list[dict]: - """One entry per queued epic, in queue order (PyAutoBrain#696): what it - contributes to this plan, or why nothing — its next phase, and each - next-phase member with the planner's reason for leaving it out; or no - draft prompt at all for its next phase. Each entry carries its `line`.""" + """One entry per queued epic, in queue order: what it contributes to this + plan, or why nothing — its next phase, and each next-phase member with + the planner's reason for leaving it out; or no draft prompt at all for + its next phase. Each entry carries its `line`.""" why_of: dict[str, str] = {} for p, w in rejected: why_of.setdefault(p, w) @@ -538,12 +530,11 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, of importance, and the only input here that is a preference rather than a property of the work. `awaiting_review` is the review-queue depth, derived from `active.md` by the caller (`derive_awaiting_review`) unless the human - passed the flag; `awaiting_source` says which, because a number nobody can - trace is a number nobody trusts. + passed the flag; `awaiting_source` says which. `attended` is False for every shift this planner composes (the batch it - proposes runs unattended, and the watcher picks unattended). Two M2.3 rules - (AUTONOMY.md "M2 rulings — 2026-11-12") apply only then: + proposes runs unattended, and the watcher picks unattended). Two rules + (AUTONOMY.md "M2 rulings") apply only then: - a backlog draft with no valid `Lane:` is excluded (`lane_absent_why`); - an EMPTY queue stops the backlog dip: the brief's named tasks still run, @@ -554,10 +545,10 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, With `attended=True` (`batch plan --attended`, a human at the keyboard picking for this session) an absent Lane reads as `any` and an empty queue - falls back to the backlog order, as before. + falls back to the backlog order. A queue entry naming an epic ledger queues the epic's members at the - ledger's rank (`queue_standing`, PyAutoBrain#696); `epic_ledgers` is + ledger's rank (`queue_standing`); `epic_ledgers` is `read_epic_ledgers(mind)`, the `epics.md` fallback for a ledger whose `Epic:` header the survey did not read. `queued_epics` in the result says, per queued epic, what it contributes or why nothing; `withheld` is the @@ -587,8 +578,7 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, # Backpressure RAMPS; it never deadlocks. It measures review-queue DEPTH, # never timing: timing is the human's, declared as `review-at:` at dispatch. - # An academic comes back late and vanishes for conference weeks, and a deep - # queue must shrink the next batch rather than refuse to compose one. + # A deep queue must shrink the next batch rather than refuse to compose one. if awaiting_review >= cap: effective_budget, pressure = 0, "at cap — fill only" elif awaiting_review > cap / 2: @@ -596,16 +586,15 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, else: effective_budget, pressure = budget, "clear" - # A queued epic ledger queues its members at its rank (#696). Read from - # every record, before the brief's scope drops any, so a ledger outside - # the brief's scope still lends its rank. + # A queued epic ledger queues its members at its rank. Read from every + # record, before the brief's scope drops any, so a ledger outside the + # brief's scope still lends its rank. epic_ranks = queued_epics(queue, all_records, epic_ledgers) # An epic's members are worked IN ORDER, so only its lowest un-shipped - # phase is startable. Without this the planner can propose phase 6 while - # phase 3 is still open — the one-slice-per-epic rule below caps how many + # phase is startable — the one-slice-per-epic rule below caps how many # run, not which. Read over every record, the ones the brief's scope or - # the caller kept out included (#696): a phase held by a claim, parked, or + # the caller kept out included: a phase held by a claim, parked, or # outside the brief is still open, so the phase after it is not next. held_out = [w for w, _ in withheld or []] next_phase = next_phases(all_records + held_out) @@ -615,8 +604,8 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, pool, lane_absent, reach, witness_absent = [], [], [], [] 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). - # A task an answer released is the human's word too (M3.6c): no dip gate. + # neither dip gate below applies to it (the brief's `lanes:` still does). + # A task an answer released is the human's word too: 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: @@ -632,9 +621,9 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, elif shift_dip and backlog and self_organ_why(r): rejected.append((r["path"], self_organ_why(r))) elif shift_dip and backlog and not r.get("witness") and not r.get("resume"): - # A shift dips only witnessed drafts (M3.6b): one without a - # `Witness:` is reviewed as `judge`, so it is never cheap fill. - # Counted for the digest; a named task is the human's pick. + # A shift dips only witnessed drafts: one without a `Witness:` + # is reviewed as `judge`, so it is never cheap fill. Counted + # for the digest; a named task is the human's pick. rejected.append((r["path"], "no Witness — a shift dips only witnessed " "drafts (declare one to make it pickable)")) witness_absent.append(r["path"]) @@ -650,9 +639,8 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, # the human's order and outranks everything: a queued prompt beats an # unqueued one, and among queued ones the file's order wins, because moving # an entry up IS the act of prioritising it. Below the queue a declared - # `Priority:` outranks cost (M2.3, 2026-11-12): sorting cheapest first let - # the cheapest review win and broke ties by filename, which picked work the - # human did not want. Cheapest first still decides within a priority. + # `Priority:` outranks cost: cheapest-first alone would pick work the + # human did not ask for. Cheapest first still decides within a priority. for r in pool: r["queue_rank"], via = queue_standing(r, queue, epic_ranks) r["queued"] = r["queue_rank"] < len(queue) @@ -661,17 +649,17 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, pool.sort(key=lambda r: (r["queue_rank"], priority_rank(r), r["review_minutes"], r["path"])) - # `released` (M3.6j, PyAutoBrain#683; first #679): the watcher's own - # picks whose worker has ended (PR open or not) and that wait on no - # question, re-dispatch or restart. They stay members (known, counted, - # never re-dispatched) but hold no library: merges collide, starts do - # not, and the close-out merges a library's shift PRs in PR order (the - # merge-order wait), so the next task on that library may start. + # `released`: the watcher's own picks whose worker has ended (PR open or + # not) and that wait on no question, re-dispatch or restart. They stay + # members (known, counted, never re-dispatched) but hold no library: + # merges collide, starts do not, and the close-out merges a library's + # shift PRs in PR order (the merge-order wait), so the next task on that + # library may start. released = released or set() members, spent, seen_epics, libs = [], 0, set(), {} for r in pool: - # One slice per epic counts only `Phase:` tasks (ruling R5, option a, - # 2026-11-17): a side task of the epic shares the shift with its phase. + # One slice per epic counts only `Phase:` tasks: a side task of the + # epic shares the shift with its phase. if r["epic"] and has_phase(r) and r["epic"] in seen_epics: rejected.append((r["path"], f"epic {r['epic']} already has a phase task in " "this batch (one Phase: task per epic)")) @@ -683,7 +671,7 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, # what downstream suites are re-run against. Workspace, docs and organ # repos are exempt — two docs changes in one shift cost nothing. A # library is held while its worker runs, so two workers never share - # one; its PRs then merge in PR order at the close-out (M3.6j). + # one; its PRs then merge in PR order at the close-out. clash = next((x for x in r["repos"] if x in LIBRARY_REPOS and x in libs), None) if clash: holder = libs[clash] @@ -729,14 +717,14 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, if r["unattended"] == "ready" and not r.get("done")), "brief": brief is not None, "attended": attended, - # The two M2.3 gates, stated rather than buried in `rejected`. + # The two unattended 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. + # The `backlog: scoped` reach rule, stated likewise. "scoped_reach": reach, - # Backlog drafts with no `Witness:`, kept out of a shift's dip (M3.6b). + # Backlog drafts with no `Witness:`, kept out of a shift's dip. "witness_absent": witness_absent, - # Per queued epic ledger, what it gives this plan or why nothing (#696). + # Per queued epic ledger, what it gives this plan or why nothing. "queued_epics": queued_epic_summary( all_records + [w for w in held_out if w.get("path") not in {r.get("path") for r in all_records}], @@ -756,10 +744,9 @@ def _lane_counts(records) -> dict[str, int]: def _dispatch_payload(r: dict) -> str: """The exact text a human pastes into one unattended session. - Written out rather than left to be composed at dispatch time: the launch is - the human's act (AUTONOMY.md, "What a batch launch is"), so the thing they - perform should carry no decisions — everything decided was decided when they - approved the batch. + Written out rather than composed at dispatch time: the launch is the + human's act (AUTONOMY.md, "What a batch launch is"), so the thing they + perform carries no decisions. """ return f"Use the start-dev skill. {r['path']} --auto" @@ -788,7 +775,7 @@ def emit(d: dict) -> None: print("Mode: attended (--attended) — an absent Lane reads as " "any, an empty queue.md falls back to the backlog order") if d.get("queue_stop"): - # M2.3: an empty queue is the human saying nothing beyond the brief. + # An empty queue is the human saying nothing beyond the brief. print("Backlog dip: STOPPED — queue.md is empty, so this unattended " "shift takes the brief's named tasks only") if d.get("lane_absent"): @@ -804,8 +791,8 @@ def emit(d: dict) -> None: f"in flight, and yours to review before anything new") lines = queued_epic_lines(d) if lines: - # One line per queued epic ledger (#696): what it gives this batch, or - # why nothing — read before the long tally of rejections below. + # One line per queued epic ledger: what it gives this batch, or why + # nothing — read before the long tally of rejections below. print("Queued epics:") for line in lines: print(f" {line}") @@ -817,8 +804,8 @@ def emit(d: dict) -> None: rank = r.get("queue_rank", queued) mark = f"q{rank + 1}" if rank < queued else " " # A `supervised` member ships under decide-and-flag rather than - # parking (AUTONOMY.md 2026-09-07); say so on the line, so the - # human approving the batch sees which members carry a flagged + # parking (AUTONOMY.md); say so on the line, so the human + # approving the batch sees which members carry a flagged # decision at review. note = (" (supervised — decide-and-flag at ship)" if r.get("autonomy") == "supervised" else "") @@ -828,11 +815,9 @@ def emit(d: dict) -> None: print(" (no witness — reviewed as `judge`)") elif d["effective_budget"] == 0: # At the cap the batch is fill only — and the human still dispatches it. - # (The FLOOR, a fill-only batch dispatched whether or not they turned - # up, was closed 2026-08-31 and never built.) An empty fill-only batch - # is a finding, not a deadlock: nothing in the backlog costs zero - # review-minutes, which is what the `notify` tier and the witness field - # exist to change. + # An empty fill-only batch is a finding, not a deadlock: nothing in the + # backlog costs zero review-minutes, which is what the `notify` tier and + # the witness field exist to change. print(" (no members — at the backpressure cap, so this batch is FILL") print(" ONLY. Nothing in the backlog currently qualifies as fill,") print(" which is itself the finding — clear the review queue, or") @@ -965,22 +950,20 @@ def read_active(mind: Path) -> dict: #: An `active.md` status that says this task's PRs are open and unmerged. The #: `library-pr:`/`workspace-pr:` keys are the PRIMARY signal — they are the PR #: ledger (PyAutoMind REFERENCE.md, "The PR keys") — and these words are the -#: fallback for rows written before that schema existed. +#: fallback for rows without them. AWAITING_STATUS_WORDS = ("awaiting-merge", "pr open", "pr-open") def derive_awaiting_review(mind: Path) -> int: """How deep the human's review queue already is, read from `active.md`. - The backpressure input used to default to 0 and was never derived, so every - plan composed a shift as though nothing were waiting — the one input that - is supposed to SHRINK a batch could only ever be supplied by hand, and - never was. A task counts when its row names an open PR (`library-pr:` / - `workspace-pr:`) or its `status:` says so in words. + The backpressure input — the one that SHRINKS a batch — must not depend on + a human supplying it by hand. A task counts when its row names an open PR + (`library-pr:` / `workspace-pr:`) or its `status:` says so in words. Deliberately NOT a `gh` call. `active.md` is the ledger; GitHub is the truth about mergeability and nobody should have to be online to plan a - shift (`mind_post_cortex_epic.md`: no live PR state in Mind). + shift. """ n = 0 for entry in read_active(mind).values(): @@ -1075,7 +1058,7 @@ def main(argv=None) -> int: help="brief: print a skeleton shift brief for SLOT (e.g. " "2026-11-14-am) whose goals: come from goals.md; " "needs --review-at; --out FILE writes it instead") - # the keep-Heart-green lane (PyAutoBrain#625): `brief --new` and `green` + # the keep-Heart-green lane: `brief --new` and `green` ap.add_argument("--green", default="", choices=("",) + _green.MODES, help="brief --new / green: the keep-Heart-green lane — off | " "report | file (bug drafts) | pick (file, then name them " @@ -1108,7 +1091,7 @@ def main(argv=None) -> int: ap.add_argument("--home", type=Path, default=None, help="digest / watch: the watcher's state directory " "(default: $PYAUTO_ORCHESTRATOR_HOME, else .orchestrator)") - # ready (M3.3, PyAutoBrain#671) + # ready ap.add_argument("--queue", type=Path, default=None, metavar="SLOT_DIR", dest="queue_slot", help="ready: queue each new ruling as a question-add op in this " "shift slot's Mind-writer ledger (default: a dry run that " @@ -1187,9 +1170,9 @@ def main(argv=None) -> int: def _main_ready(mind: Path, a) -> int: """`batch ready [--queue SLOT_DIR | --apply] [--fetch] [--root DIR]` — the - readiness pass (M3.3, PyAutoBrain#671, `_ready`): every queue.md entry's - next unit(s), their gates, and the rulings it would file. A dry run by - default; the premise check is offline unless `--fetch`.""" + readiness pass (`_ready`): every queue.md entry's next unit(s), their + gates, and the rulings it would file. A dry run by default; the premise + check is offline unless `--fetch`.""" import _ready if a.queue_slot is not None and a.apply: raise BatchUsageError("batch ready: --queue and --apply are exclusive") @@ -1374,7 +1357,7 @@ def _main_digest(mind: Path, a) -> int: def _main_watch(a) -> int: """`batch watch --record [--once] [--interval N]` — a live view of a running shift; writes nothing anywhere (`_watch`). With `--stream`, the - shift's event stream (`_watch.stream`, PyAutoBrain#644).""" + shift's event stream (`_watch.stream`).""" import _watch if isinstance(a.check, str) and a.check: print("batch watch: --check takes no file (the record is --record)", file=sys.stderr) @@ -1408,8 +1391,8 @@ def _main_watch(a) -> int: SLOT_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-(am|pm)$") #: Defaults `brief --new` writes for the keys the human usually leaves alone. #: `merge-cap: 0` is the safe one: nothing merges unattended until raised. -#: RAL is in `lanes:` by default (PyAutoBrain#696): a shift that left it out -#: rejected every `Lane: ral` phase the human had queued. +#: RAL is in `lanes:` by default: a shift that leaves it out rejects every +#: `Lane: ral` phase the human has queued. NEW_BRIEF_DEFAULTS = {"review-minutes": str(DEFAULT_REVIEW_BUDGET), "lanes": "any local-dev ral", "merge-cap": "0", "token-budget": "5000000"} @@ -1456,8 +1439,8 @@ def goals_report(mind: Path) -> list[str]: return L -#: `brief --new`'s scope when no goal names an epic or tag (M3.6b): the tiers -#: a shift may merge, under the 2026-11-16 backlog-reach ruling. +#: `brief --new`'s scope when no goal names an epic or tag: the tiers a shift +#: may merge, under the `backlog: scoped` reach rule. NEW_BRIEF_SCOPED_TIERS = ("notify", "glance") @@ -1475,10 +1458,10 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, `heart` is the keep-Heart-green lane's result (`_green.run`): its picks become a last `heart-green` goal plus named `tasks:`, and its report the - record's `## Heart` section (PyAutoBrain#625). + record's `## Heart` section. - `issue` is the shift issue (`create_shift_issue`), written as `issue:` - (M3.6a, PyAutoBrain#659): `brief --check` refuses a live brief without it.""" + `issue` is the shift issue (`create_shift_issue`), written as `issue:`: + `brief --check` refuses a live brief without it.""" goals = read_goals(mind) now = now or _dt.datetime.now(_dt.timezone.utc) epics: list[str] = [] @@ -1486,7 +1469,7 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, for g in goals: epics += [e for e in g["epics"] if e not in epics] tags += [t for t in g["tags"] if t not in tags] - # A queued epic ledger queues its phases (#696), so its epic is in scope: + # A queued epic ledger queues its phases, so its epic is in scope: # without it a `scoped` brief would keep out the work the queue asks for. goal_scoped = bool(epics or tags) queued = [e for e in queued_epics(read_queue(mind), survey(mind), @@ -1521,9 +1504,8 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, if tags: L.append(f" - tags: {', '.join(tags)}") else: - # No goal names an epic or tag: the backlog-reach ruling (2026-11-16, - # PyAutoBrain#637 item 6) is the default, not `fill-idle` (M3.6b) — - # under `scoped` the planner dips queue.md first, then only small + # No goal names an epic or tag: `scoped`, not `fill-idle`, is the + # default — the planner dips queue.md first, then only small # single-repo tasks, and these tiers are the ones a shift may merge. L += [" - backlog: scoped # tiers a shift may merge; beyond " "queue.md small single-repo only (ruling 2026-11-16)", @@ -1550,7 +1532,7 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, def check_plan(brief: dict, mind: Path) -> tuple[dict, dict[str, str], str]: """(plan, {path: why held}, note) — the watcher's plan under `brief`, as - `brief --check` runs it (M3.6b): the claim gate against Mind's local + `brief --check` runs it: the claim gate against Mind's local `origin/main` (never a fetch), then `plan` unattended on the watcher's lane. `note` says when the claims could not be read.""" import _orchestrator as orch # noqa: E402 — deferred: it imports this module @@ -1576,10 +1558,10 @@ def named_skips(brief: dict, mind: Path, ) -> tuple[dict[str, str], str]: """({named task: why it will not start}, a note when the claims on Mind origin/main could not be read) — the watcher's own gates, run at - `brief --check` (M3.6b, ruling R5): the claim gate against Mind's local - `origin/main` (never a fetch), then `plan` under this brief, unattended, - on the watcher's lane. A task the planner keeps is not listed; one that - resolves to no prompt is `_brief.check`'s warning already.""" + `brief --check`: the claim gate against Mind's local `origin/main` (never + a fetch), then `plan` under this brief, unattended, on the watcher's + lane. A task the planner keeps is not listed; one that resolves to no + prompt is `_brief.check`'s warning already.""" named = _brief.tasks_of(brief) if not named: return {}, "" @@ -1619,9 +1601,9 @@ def mind_repo(mind: Path) -> str: def create_shift_issue(mind: Path, slot: str, review_at: str, run=None) -> tuple[str, str]: """(issue URL, "") or ("", why not): the one `gh issue create` on the Mind - repo that `brief --new --out` makes (M3.6a, PyAutoBrain#659; AUTONOMY.md - "The Brain reads no network", the 2026-11-17 exception). It runs in the - launch chat, never in the watcher.""" + repo that `brief --new --out` makes (AUTONOMY.md "The Brain reads no + network" names the exception). It runs in the launch chat, never in the + watcher.""" repo = mind_repo(mind) if not repo: return "", f"no GitHub `origin` remote in {mind} to make the shift issue on" @@ -1653,8 +1635,8 @@ def _issue_in(path: Path) -> str: def login_findings(top: dict, brief: dict | None) -> tuple[dict, list[str], list[str]]: - """(probe result, errors, warnings) of the CLI login for a launch (M3.6a): - an expired login, or one that lapses before `review-at:`, refuses it. A + """(probe result, errors, warnings) of the CLI login for a launch: an + expired login, or one that lapses before `review-at:`, refuses it. A shadow brief starts no worker and is not probed.""" if brief is None or _brief.is_shadow(brief): return {"state": "skipped", "detail": "shadow shift", "expires_at": ""}, [], [] @@ -1723,9 +1705,9 @@ def _main_brief(mind: Path, a) -> int: "record): " + ", ".join(heart["filed"]), file=sys.stderr) for line in goals_report(mind): print(line, file=sys.stderr) - # The shift issue (M3.6a, PyAutoBrain#659) is made last, just before - # the write, so nothing that can still fail stands between the two. A - # file that already names one keeps it: a re-run never makes a second. + # The shift issue is made last, just before the write, so nothing that + # can still fail stands between the two. A file that already names one + # keeps it: a re-run never makes a second. issue = a.issue.strip() or (_issue_in(Path(a.out)) if a.out else "") made = False if a.out and not issue and \ @@ -1760,8 +1742,8 @@ def _main_brief(mind: Path, a) -> int: "(the digest is `batch digest --record `)", file=sys.stderr) return RC_USAGE res = _brief.check(Path(a.check), mind) - # What only a launch needs (M3.6a, PyAutoBrain#659): the shift issue, and a - # CLI login that holds until review-at. `_brief.check` stays the watcher's. + # What only a launch needs: the shift issue, and a CLI login that holds + # until review-at. `_brief.check` stays the watcher's. try: rec = _brief.parse(Path(a.check).read_text(encoding="utf-8", errors="replace")) except (OSError, _brief.BriefError): @@ -1772,8 +1754,8 @@ def _main_brief(mind: Path, a) -> int: res["login"] = login res["errors"] += errs res["warnings"] += warns - # A granted `ral` lane a worker cannot reach (2026-11-20-am): one - # BatchMode ssh, a warning only. A shadow brief starts no worker. + # A granted `ral` lane a worker cannot reach: one BatchMode ssh, a + # warning only. A shadow brief starts no worker. if rec["brief"] is not None and not _brief.is_shadow(rec["brief"]): res["ral"], warns = _ral.findings(_brief.lanes_of(rec["brief"]), mind) res["warnings"] += warns @@ -1781,8 +1763,8 @@ def _main_brief(mind: Path, a) -> int: warn = goal_one_warning(Path(a.check), mind) if warn: res["warnings"].append(warn) - # M3.6b: every named task that will not start, with the planner's own - # reason, and the organ rule for each one, before the shift opens. + # Every named task that will not start, with the planner's own reason, + # and the organ rule for each one, before the shift opens. res["notes"] = [] if rec is not None and rec["brief"] is not None: planned = check_plan(rec["brief"], mind) @@ -1791,7 +1773,7 @@ def _main_brief(mind: Path, a) -> int: for t, w in why_not.items()] if claim_note: res["warnings"].append(claim_note) - # #696: each queued epic ledger, and why it gives this shift nothing. + # Each queued epic ledger, and why it gives this shift nothing. res["queued_epics"] = planned[0]["queued_epics"] res["warnings"] += [f"queued epic {e['line']}" for e in res["queued_epics"] if not e["taken"]] @@ -1831,7 +1813,7 @@ def _main_brief(mind: Path, a) -> int: #: Where the lane may not write: the shared, canonical Mind checkout other -#: sessions work in (memory: shared-Mind writes go through a temp worktree). +#: sessions work in (shared-Mind writes go through a temp worktree). SHARED_MIND_HOLD = ("--mind is not a linked worktree ({}) — a main checkout is the " "shared canonical Mind; the lane writes drafts only into a " "Mind the caller names that is a temp " @@ -1857,9 +1839,9 @@ def is_linked_worktree(path: Path) -> bool: def write_hold(mind: Path, a, preview: bool) -> str: - """Why the lane may not write here, or "" (review of #625): never in a - preview, never into an implicit Mind, and only into a linked worktree — - the main checkout of any Mind clone is the shared one.""" + """Why the lane may not write here, or "": never in a preview, never into + an implicit Mind, and only into a linked worktree — the main checkout of + any Mind clone is the shared one.""" if preview: return "a preview (no --out) writes nothing" if not getattr(a, "mind_explicit", False) or not is_linked_worktree(mind): diff --git a/agents/conductors/batch/_brief.py b/agents/conductors/batch/_brief.py index 7ef80da1..bd3edc95 100644 --- a/agents/conductors/batch/_brief.py +++ b/agents/conductors/batch/_brief.py @@ -1,10 +1,10 @@ """Shift briefs — parse and validate the `brief:` block of a batch record. -The schema is `PyAutoMind/batches/AGENTS.md` "Shift brief (2026-11-03)"; the -doctrine that makes a brief the launch act is `AUTONOMY.md` "Shift briefs and -unattended `glance`". This module only READS: `check` says whether a brief is +The schema is `PyAutoMind/batches/AGENTS.md` "Shift brief"; the doctrine that +makes a brief the launch act is `AUTONOMY.md` "Shift briefs and unattended +`glance`". This module only READS: `check` says whether a brief is well-formed, and `scope` says which backlog records it admits. Nothing here -dispatches, merges or writes a file — those verbs are phase 3. +dispatches, merges or writes a file. Every error names the key it is about (`brief.lanes: ...`), because the person fixing a brief is reading the file, not this code. @@ -22,29 +22,29 @@ ) BACKLOG_POLICIES = ("none", "fill-idle", "scoped") -#: Optional usage caps (phase 3a) and their defaults when a brief omits them. +#: Optional usage caps and their defaults when a brief omits them. CAP_DEFAULTS = {"max-workers": 4, "max-sessions": 8} -#: Permission modes a real worker may run in (phase 3b). `auto` is the default -#: the human chose 2026-11-03: a worker that still needs a person shows -#: `blocked` and is parked. `bypassPermissions` is never a worker mode. +#: Permission modes a real worker may run in. `auto` is the default: a worker +#: that still needs a person shows `blocked` and is parked. +#: `bypassPermissions` is never a worker mode. 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` 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). -#: A brief's named task is the human's own pick and is not gated. +#: the planner never dips a draft that targets one. 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. +#: The one size `backlog: scoped` may dip beyond `queue.md`: small and +#: single-repo only. SCOPED_REACH_DIFFICULTY = "small" -#: The late window (human ruling H2): the watcher's digest and late sweep run -#: from `review-at:` to this long after it, and then it stops ticking the slot -#: (M3.6a, PyAutoBrain#659). `batch watch --stream` ends at the same time. +#: The late window: the watcher's digest and late sweep run from `review-at:` +#: to this long after it, and then it stops ticking the slot. +#: `batch watch --stream` ends at the same time. LATE_WINDOW_S = 45 * 60 -#: A shift issue: the brief's `issue:` value (M3.6a). +#: A shift issue: the brief's `issue:` value. ISSUE_RE = re.compile(r"https://github\.com/[\w.-]+/[\w.-]+/issues/\d+") _ITEM_RE = re.compile(r"^(\s*)-\s+(.*?)\s*$") @@ -145,7 +145,7 @@ def excluded_of(brief: dict) -> tuple[set[str], dict[str, list[str]]]: #: 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 +#: derived from the budget: 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 @@ -154,8 +154,8 @@ def excluded_of(brief: dict) -> tuple[set[str], dict[str, list[str]]]: def cap_of(brief: dict, key: str) -> int: """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.""" + from it and `max-workers:`, so a fixed session count never stops new + starts while most of the budget is unspent.""" value = _nonneg_int(brief.get(key, {}).get("value", "")) if value is not None: return value @@ -175,16 +175,16 @@ def cap_source(brief: dict, key: str) -> str: return "default" -#: The caps a `/cap` steering command may lower for one shift (#644). +#: The caps a `/cap` steering command may lower for one shift. CAP_KEYS = ("merge-cap", "max-workers", "max-sessions", "token-budget") def effective(brief: dict, counters: dict | None) -> dict: - """The brief as this shift now runs it (PyAutoBrain#644): a copy with each - `/cap` override's value (`counters["caps"]`) swapped in, and each task the - human `/add`ed (`counters["added"]`) appended to `tasks:` and taken out of - `exclude:` — the human's newer word, as a brief that names a task again. - The brief file is never changed; with nothing steered it is `brief` itself.""" + """The brief as this shift now runs it: a copy with each `/cap` override's + value (`counters["caps"]`) swapped in, and each task the human `/add`ed + (`counters["added"]`) appended to `tasks:` and taken out of `exclude:` — + the human's newer word, as a brief that names a task again. The brief + file is never changed; with nothing steered it is `brief` itself.""" caps = (counters or {}).get("caps") or {} added = (counters or {}).get("added") or {} if not brief or not (caps or added): @@ -213,7 +213,7 @@ def worker_mode_of(brief: dict) -> str: def is_shadow(brief: dict) -> bool: - """A shadow shift (phase 4a) plans and records proposals but spawns nothing.""" + """A shadow shift plans and records proposals but spawns nothing.""" return brief.get("shadow", {}).get("value", "").lower() == "yes" @@ -279,12 +279,10 @@ 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.""" + No one pulls the working tree mid-shift, but a check-in pushed from a + linked worktree of the canonical checkout moves the local `origin/main` + ref at once, 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}") @@ -357,7 +355,7 @@ 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. + # `first: glance`: 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)") @@ -407,7 +405,7 @@ def check(path: Path, mind: Path) -> dict: 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). + # The digest, once collect has appended one. import _digest # noqa: E402 — deferred: _digest imports this module errors += _digest.validate(path.read_text(encoding="utf-8", errors="replace")) @@ -415,10 +413,10 @@ def check(path: Path, mind: Path) -> dict: def launch_errors(top: dict, brief: dict | None) -> list[str]: - """What only a launch needs (M3.6a, PyAutoBrain#659): `batch brief --check` - adds these to `check`; the watcher does not. A live brief (not `shadow: - yes`) needs its shift issue: the status comment, the steering commands and - the digest all go there, and shift 2026-11-16-pm had none.""" + """What only a launch needs: `batch brief --check` adds these to `check`; + the watcher does not. A live brief (not `shadow: yes`) needs its shift + issue: the status comment, the steering commands and the digest all go + there.""" if brief is None or is_shadow(brief): return [] issue = (top.get("issue") or {}).get("value", "").strip() @@ -431,7 +429,7 @@ def launch_errors(top: dict, brief: dict | None) -> list[str]: return [] -# --- the organ rule for a named task (M3.6b) ------------------------------------- +# --- the organ rule for a named task --------------------------------------------- #: The shift's own code, per organ it runs on: its watcher and planner (Brain), #: its one Mind writer and lifecycle (Mind) and its release path (all of Hands, @@ -534,11 +532,9 @@ def _classify(parts: list[str], hit: list[str], only_self: bool, organs: dict, def organ_findings(name: str, path: Path, mind: Path) -> tuple[list[str], list[str], list[str]]: """(errors, warnings, notes) of the organ rule for one named task. - The organ rule was a dip rule only (`_batch.self_organ_why`); a named task - is the human's pick, and in shift 2026-11-16-pm the human had to rule in - chat that a renderer is not the watcher, writer or release path. This says - it at launch instead (M3.6b), for a task that targets an organ the shift - runs on: + A named task is the human's pick, so the dip rule (`_batch.self_organ_why`) + does not gate it; this says at launch whether it would change what runs + the shift, for a task that targets an organ the shift runs on: - refused when it names the shift's own code: a path under an organ's `SELF_PATHS` with that organ written in it, under a multi-segment self @@ -617,7 +613,7 @@ def scope(records: list[dict], brief: dict) -> tuple[list[dict], list[tuple[str, ex_paths, ex_keyed = excluded_of(brief) ex_names = {Path(p).name for p in ex_paths} lanes = set(lanes_of(brief)) or {"any"} - # `/add`ed this shift (`effective`, #644): no `exclude:` rule holds it back. + # `/add`ed this shift (`effective`): no `exclude:` rule holds it back. added = set(_csv(brief.get("added", {}).get("value", ""))) kept, rejected = [], [] @@ -628,8 +624,8 @@ 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 - # 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. + # A task an answer released (the inbox) is the human's word, as + # naming it would be: 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)")) @@ -680,8 +676,8 @@ def pick_reason(record: dict, brief: dict) -> str: def rank_note(record: dict) -> str: """The planner's order, as it applied to this record (`_batch.plan`): - queue.md position first; below the queue, priority, then cheapest review - (M2.3, 2026-11-12), then the path — so a tie is alphabetical, and says so.""" + queue.md position first; below the queue, priority, then cheapest review, + then the path — so a tie is alphabetical, and says so.""" parts = [] if record.get("queued"): parts.append(f"queue.md #{record['queue_rank'] + 1}" diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 8718c7d0..bac65b2b 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -1,11 +1,11 @@ -"""The shift digest (phase 3d) — what the human reads at `review-at:`. +"""The shift digest — what the human reads at `review-at:`. The format is `PyAutoMind/batches/AGENTS.md` "Digest" and "Proof packet". The digest is built from what the watcher itself recorded during the shift — the brief, `counters.json` (dispatch picks and their reasons, outcomes, crashes, tokens) and the proof packets the workers wrote — plus one read-only `gh pr checks` per PR, the only GitHub read the watcher's network surface -allows (AUTONOMY.md "The watcher's network surface — 2026-11-03"). It never +allows (AUTONOMY.md "The watcher's network surface"). It never reads a session's own account of itself beyond the `.done` and proof files the worker contract asks for, and it invents nothing: a task with no proof packet gets a stub that says so. @@ -22,10 +22,10 @@ from pathlib import Path import _brief # noqa: E402 -import _merge_slots # noqa: E402 — slot evidence for an in-turn merge (R3, #661) -import _questions # noqa: E402 — the inbox line (M3.5, #645) +import _merge_slots # noqa: E402 — slot evidence for an in-turn merge +import _questions # noqa: E402 — the inbox line -# The one CI judgement (PyAutoBrain#628) lives in bin/, beside its CLI. +# The one CI judgement lives in bin/, beside its CLI. sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "bin")) import ci_verdict # noqa: E402 @@ -37,27 +37,27 @@ #: Every counter, always printed — a zero is a fact, an absent line is a finding. COUNTERS = ("merges", "glance-auto-merges", "reverts", "pushes", "drafts-filed", "packets-sent", "workers-crashed", "tokens", "review-minutes-planned") -#: Counters only phase 4 (unattended merges) and phase 5 (RAL packets) move; -#: they read from `counters.json` and are 0 until then (human, 2026-11-04). +#: Counters only unattended merges and RAL packets move; they read from +#: `counters.json` and are 0 until then. LATER_COUNTERS = {"glance-auto-merges": "glance_auto_merges", "reverts": "reverts", "pushes": "pushes", "drafts-filed": "drafts_filed", "packets-sent": "packets_sent"} PROOFS_DIR = "proofs" NO_PICKS = "- none" -#: What a shadow shift's line and packet section say instead of work (phase 4a). +#: What a shadow shift's line and packet section say instead of work. PROPOSED = "proposed (shadow)" -#: 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. +#: A worker whose lease is still held when the digest is built: 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 PR the worker merged in-turn — after taking a merge slot against the -#: shift's `merge-cap:` (AUTONOMY.md ruling R3, 2026-11-17, PyAutoBrain#661). +#: shift's `merge-cap:` (AUTONOMY.md). IN_TURN_MERGED = "merged in-turn by the worker (merge slot)" #: A PR the worker reported merged in-turn with no merge slot held for its -#: task: past the shift's `merge-cap:` count, and the evidence ruling R3's -#: revert condition reads. +#: task: past the shift's `merge-cap:` count, and the evidence the revert +#: condition reads. IN_TURN_NO_SLOT = "merged in-turn with NO merge slot — R3 revert-condition evidence" -#: A killed worker whose re-dispatch never started (PyAutoBrain#637, item 2): -#: never "not started" — its first worker ran. +#: A killed worker whose re-dispatch never started: 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. @@ -68,8 +68,8 @@ #: An issue URL on a `.done` line, wherever it is hosted. _ISSUE_URL_RE = re.compile(r"/issues/\d+") -#: The pilot ledger (phase 4a). A subfolder, because every `batches/*.md` is -#: read as a batch record (lifecycle.py, `_batch.records`, the calibration rule). +#: The pilot ledger. A subfolder, because every `batches/*.md` is read as a +#: batch record (lifecycle.py, `_batch.records`, the calibration rule). PILOT_PATH = "batches/pilot/pilot.md" PILOT_COLUMNS = ("slot", "mode", "review-minutes-planned", "review-minutes-actual", "merges", "glance-auto-merges", "reverts", "overrules", "pushes", @@ -77,8 +77,8 @@ #: Cells only the human can fill, at check-in. PILOT_HUMAN = ("review-minutes-actual", "overrules") #: In a shadow shift the orchestrator merges nothing, so `merges` is the human's -#: own in the window — the baseline the live shifts are measured against -#: (epic: "the human works as today, minutes are logged"), counted at check-in. +#: own in the window — the baseline the live shifts are measured against — +#: counted at check-in. PILOT_HUMAN_SHADOW = ("merges",) PILOT_HEADER = ("| " + " | ".join(PILOT_COLUMNS) + " |\n" + "|" + "|".join("---" for _ in PILOT_COLUMNS) + "|\n") @@ -88,10 +88,10 @@ # --- outcomes ------------------------------------------------------------------ -#: The `.done` words that say why a worker ended on an issue (#632, F2). Only -#: an explicit `verdict:` (its deliverable) keeps the human un-mentioned; a +#: The `.done` words that say why a worker ended on an issue. Only an +#: explicit `verdict:` (its deliverable) keeps the human un-mentioned; a #: `question:`, a bare issue URL or any other marker is a push — the push -#: test fails toward the human, never toward silence (#632 review). +#: test fails toward the human, never toward silence. DONE_VERDICT = "verdict" _URL_RE = re.compile(r"https?://\S+") _MARKER_RE = re.compile(r"^\s*([A-Za-z-]*)\s*:?\s*$") @@ -104,8 +104,8 @@ def parse_done(text: str) -> dict: `obsolete ` when its premise check stopped it. Markers are read in any case, with or without the colon or the space after it. An issue URL goes in `issues`, never in `prs`: `prs` is what CI, a close-out and the - merge count read (PyAutoBrain#610). `verdicts` holds only the URLs an - explicit `verdict:` marked — every other issue URL is a push (#632).""" + merge count read. `verdicts` holds only the URLs an explicit `verdict:` + marked — every other issue URL is a push.""" prs, merged, issues, obsolete = [], [], [], None questions, verdicts = [], [] for line in text.splitlines(): @@ -150,20 +150,20 @@ def urls_of(outcome: dict | None) -> list[str]: def pr_health(url: str, run=None) -> str: - """One read-only `gh pr checks --json`, judged by `bin/ci_verdict.py` - (PyAutoBrain#628) — the one CI judgement `/prm` and the close-out run too. + """One read-only `gh pr checks --json`, judged by `bin/ci_verdict.py` — the + one CI judgement `/prm` and the close-out run too. The watcher's network surface is `gh pr checks` only (AUTONOMY.md "The watcher's network surface"), so this keeps that read and hands its rows to `ci_verdict.judge` with mergeability not read; the close-out session runs the full `pyauto-brain ci-verdict`, which reads it. The words map from the verdict: GREEN is HEALTHY (at least one completed check, every completed - check green — PyAutoHeart#343); a failed, cancelled or timed-out check is - FAILED (`gh pr checks`' exit code counts a cancelled check as skipped, so - the exit code alone is not the verdict); a bucket the judge does not know - is UNKNOWN (fail closed); a pending check is RUNNING; no checks, or only - skipped ones, is NO-CHECKS, which the close-out refuses — that PR is the - human's merge.""" + check green); a failed, cancelled or timed-out check is FAILED (`gh pr + checks`' exit code counts a cancelled check as skipped, so the exit code + alone is not the verdict); a bucket the judge does not know is UNKNOWN + (fail closed); a pending check is RUNNING; no checks, or only skipped + ones, is NO-CHECKS, which the close-out refuses — that PR is the human's + merge.""" if "/pull/" not in url: return "PARKED-ON-ISSUE" run = run or subprocess.run @@ -206,9 +206,9 @@ def task_state(task: str, counters: dict, health, *, live: bool = False, digest and `batch watch` share, so the live view and the digest never disagree. Only the live view passes `live=True` (with the task's `lease` and the `agents` view). The digest passes a lease only for a worker still - out at `review-at:`, which reads `STILL_OUT`, never "not started" - (PyAutoBrain#634, N1); the late sweep reports how it ends. A task the - human dropped by `/drop` (PyAutoBrain#622) says so first.""" + out at `review-at:`, which reads `STILL_OUT`, never "not started"; the + late sweep reports how it ends. A task the human dropped by `/drop` says + so first.""" state, tiered = _task_state(task, counters, health, live=live, lease=lease, agents=agents) if task not in (counters.get("dropped") or {}): @@ -243,8 +243,7 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, if skipped: return "not started — skipped: " + skipped, False # Neither claimed nor rejected, yet never started: the spawn gate - # refused it (2026-11-20-am: a named task waited on `max-workers` - # all shift and its entry said only "not started"). + # refused it, and the entry says why rather than "not started". 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: @@ -266,8 +265,8 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, elif url in out.get("issues", []): state = "PARKED-ON-ISSUE" elif url in out["merged"]: - # Which path each merge took (R3, #661): a close-out, or the - # worker in-turn after taking a merge slot. + # Which path each merge took: a close-out, or the worker + # in-turn after taking a merge slot. if co.get("state") == "merged": state = "merged unattended (close-out, " + co.get("model", "?") + ")" else: @@ -275,9 +274,9 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, if co.get("state") == "merged" and co.get("cleanup"): state += f" — worktree: {co['cleanup']}" elif url in (counters.get("merge_waits") or {}): - state = wait_state(url, counters) # merge order (M3.6j, #683) + state = wait_state(url, counters) # merge order elif url in (counters.get("sweep_waits") or {}): - state = sweep_wait_state(url, counters) # unknown sweep (M3.7e, #694) + state = sweep_wait_state(url, counters) # unknown sweep elif co.get("settled"): state = co.get("why") or SETTLED elif co.get("state") == "refused": @@ -315,7 +314,7 @@ def is_settled(task: str, counters: dict) -> bool: return bool(out.get("carried_from") and urls) and set(urls) <= settled_prs(counters) -#: A PR's states in the merge order (M3.6j, PyAutoBrain#683). +#: A PR's states in the merge order. UPDATING = "close-out updating the branch from main" UPDATED = "branch updated from main" CURRENT = "branch already up to date with main" @@ -346,8 +345,8 @@ def _order_word(url: str, counters: dict) -> str: def sweep_wait_state(url: str, counters: dict) -> str: - """A PR held while the sweep's run list is unreadable (M3.7e, #694): since - when the sweep is unknown, from the wait's `why`.""" + """A PR held while the sweep's run list is unreadable: since when the + sweep is unknown, from the wait's `why`.""" wait = (counters.get("sweep_waits") or {}).get(url) or {} _, sep, since = str(wait.get("why") or "").partition(" since ") since = (since if sep else "") or wait.get("since") or "?" @@ -356,7 +355,7 @@ def sweep_wait_state(url: str, counters: dict) -> str: def wait_state(url: str, counters: dict) -> str: """A PR waiting in merge order: behind which PRs, what they are doing, and - which one to merge first (M3.6j, PyAutoBrain#683).""" + which one to merge first.""" behind = ((counters.get("merge_waits") or {}).get(url) or {}).get("behind") or [] return ("waits behind " + ", ".join(f"{pr_ref(b)} ({_order_word(b, counters)})" for b in behind) @@ -364,10 +363,10 @@ def wait_state(url: str, counters: dict) -> str: def merge_order_lines(counters: dict) -> list[str]: - """The `### Merge order` block (M3.6j, PyAutoBrain#683): for each library - repo where a PR of this shift waits behind an earlier one, its open PRs - in PR-number order, ▶ on the one that needs your /prm now; and how many - branch updates conflicted with main. Empty when nothing waits.""" + """The `### Merge order` block: for each library repo where a PR of this + shift waits behind an earlier one, its open PRs in PR-number order, ▶ on + the one that needs your /prm now; and how many branch updates conflicted + with main. Empty when nothing waits.""" waits = counters.get("merge_waits") or {} if not waits: return [] @@ -405,7 +404,7 @@ def number(u): return out -#: The heading of the PRs that waited behind a /prm-bound PR (S7, M3.7c). +#: The heading of the PRs that waited behind a /prm-bound PR. WAITED_HEADING = "### Waited behind your /prm" @@ -416,7 +415,7 @@ def _hhmm(iso: str) -> str: def closed_early_lines(counters: dict) -> list[str]: - """One line when the shift closed before `review-at:` (M3.7c, #690).""" + """One line when the shift closed before `review-at:`.""" at = counters.get("closed_early") if not at: return [] @@ -426,11 +425,11 @@ def closed_early_lines(counters: dict) -> list[str]: def waited_lines(counters: dict) -> list[str]: """The PRs that waited in merge order behind an earlier PR bound for the - human's /prm (S7, M3.7c, PyAutoBrain#690): one line per library repo and - set of blockers, from `merge_waits` at close and the refused close-outs — + human's /prm: one line per library repo and set of blockers, from + `merge_waits` at close and the refused close-outs — `autogalaxy: #8, #9 waited behind #7 (/prm-bound: decision-taken)` — after a count; and how many PRs were refused because their labels could not be - read (S7). Empty when there is neither.""" + read. Empty when there is neither.""" cos = counters.get("closeouts") or {} refused = {u: co for u, co in cos.items() if co.get("state") == "refused" and not co.get("settled")} @@ -452,7 +451,7 @@ def num(u): return int(m.group(2)) if m else 0 n = sum(len(v) for v in groups.values()) out = ["", WAITED_HEADING] + ([f"- {n} PR(s) waited behind a /prm-bound PR"] if n else []) - if unread: # review round 1: label reads that never succeeded (S7) + if unread: # label reads that never succeeded out.append(f"- {len(unread)} PR(s) refused: labels unreadable (at most one read a " "tick, refused after 3 misses over 15 minutes) — " + ", ".join(pr_ref(u) for u in unread)) @@ -474,7 +473,7 @@ def has_slot(counters: dict, task: str, url: str) -> bool: def no_slot_merges(counters: dict) -> list[str]: """In-turn merges a worker reported with no merge slot for its task — - each one a merge `merge-cap:` did not count (R3, #661).""" + each one a merge `merge-cap:` did not count.""" closeouts = counters.get("closeouts", {}) return [url for task, o in counters.get("outcomes", {}).items() for url in o.get("merged") or [] @@ -484,9 +483,8 @@ def no_slot_merges(counters: dict) -> list[str]: 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, a park in an earlier shift (#637), or the - planner's own reason for a named task (M3.6b: epic, budget, Blocked-by) — - or "".""" + repo on Mind origin/main, a park in an earlier shift, or the planner's + own reason for a named task (epic, budget, Blocked-by) — or "".""" gates = counters.get("backlog_gates") or {} for key in ("origin", "parked", "named"): for path, why in (gates.get(key) or {}).items(): @@ -507,9 +505,9 @@ def redispatch_why(task: str, counters: dict) -> str: #: `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 -#: held their leases for 40 minutes, read as alive). An unknown word is still -#: read as alive; add it here once seen. `_orchestrator` reaps by this set. +#: write one late, so it gets no grace and must not hold its lease as if +#: alive. An unknown word is still read as alive. `_orchestrator` reaps by +#: this set. ENDED_STATES = frozenset({"failed", "error", "errored", "killed", "stopped", "crashed", "cancelled", "canceled", "exited"}) @@ -532,7 +530,7 @@ def _lease_state(lease: dict, agents) -> str: return f"running (agent {agent}, {state}, since {since})" -# --- links and the two-line task entry (PyAutoBrain#634) --------------------------- +# --- links and the two-line task entry --------------------------------------------- #: A prompt moves at most draft/ → active/ → complete/YYYY/MM/ in a shift; #: a few more hops are tolerated, never an unbounded walk. @@ -544,13 +542,13 @@ class MindLinks: """Where a task's Mind prompt and its work issue are, read at render time from the watcher's own Mind checkout: local git on its `origin/main` ref, which the watcher's one fetch and the Mind writer's pushes keep current. - It makes no network call of its own (PyAutoBrain#634). + It makes no network call of its own. A prompt moves draft/ → active/ → complete/YYYY/MM/ during a shift, often - renamed, so the `blob/main/draft/...` link the first live shift wrote was - dead by the time the digest was read. The prompt link here follows the - moves and is pinned to a commit sha, so it does not go dead later. When it - cannot read something it returns "", and the caller drops the link.""" + renamed, so a `blob/main/draft/...` link would be dead by the time the + digest is read. The prompt link here follows the moves and is pinned to a + commit sha, so it does not go dead later. When it cannot read something + it returns "", and the caller drops the link.""" def __init__(self, mind=None, issue: str = "", ref: str = "origin/main", run=None): m = _ISSUE_RE.match(issue or "") @@ -629,7 +627,7 @@ def work_issue(self, task: str, prompt: str) -> str: def work_link(task: str, counters: dict, links: MindLinks | None = None) -> str: """What a task's title links to: its PR, else the work repo's issue (the one its `.done` named, else the one its claim in `active.md` names), - else "" — the title is then plain text. Never a Mind path (#634).""" + else "" — the title is then plain text. Never a Mind path.""" out = counters.get("outcomes", {}).get(task) or {} urls = urls_of(out) if urls: @@ -641,8 +639,8 @@ def work_link(task: str, counters: dict, links: MindLinks | None = None) -> str: def label(task: str, pick: dict | None, url: str = "") -> str: """How a pick is named in a technical list: its title (linked to `url`, the work itself, when there is one), the task slug in backticks, then - size and repos. A pick recorded before titles were (or with none) falls - back to the bare slug.""" + size and repos. A pick with no recorded title falls back to the bare + slug.""" pick = pick or {} title = pick.get("title") if not title: @@ -652,9 +650,9 @@ def label(task: str, pick: dict | None, url: str = "") -> str: return f"{head} (`{task}`" + (f"; {details}" if details else "") + ")" -#: A task's outcome in plain words (PyAutoBrain#634), read from one part of -#: its `task_state`; the first match wins. The exact state stays on the -#: entry's second line, so nothing is lost by the short form. +#: A task's outcome in plain words, read from one part of its `task_state`; +#: the first match wins. The exact state stays on the entry's second line, so +#: nothing is lost by the short form. _PLAIN = ( (IN_TURN_NO_SLOT, "Merged with NO merge slot — needs you"), ("merged", "Merged"), @@ -712,10 +710,10 @@ def plain_outcome(state: str) -> str: def entry_lines(task: str, pick: dict | None, state: str, tiered: bool, tier: str, link: str = "", *, why: str = "", extra=(), mind_url: str = "") -> list[str]: - """One task as the human reads it (PyAutoBrain#634): the outcome in plain - words and the title, linked to the work itself; then a second, smaller - line with the slug, tier, size, repos, the exact state, any `extra`, the - Mind prompt and, last, the `why:` (`validate` reads it from the end).""" + """One task as the human reads it: the outcome in plain words and the + title, linked to the work itself; then a second, smaller line with the + slug, tier, size, repos, the exact state, any `extra`, the Mind prompt + and, last, the `why:` (`validate` reads it from the end).""" pick = pick or {} title = pick.get("title") or task head = f"- **{plain_outcome(state)}** — " + (f"[{title}]({link})" if link else title) @@ -769,7 +767,7 @@ def _packet(task: str, slot: Path, counters: dict) -> str: def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, health=None, issue: str = "", mind=None) -> str: """The `## Digest` block for one shift, as Markdown. `mind` is the - watcher's Mind checkout, read locally for the prompt links (#634).""" + watcher's Mind checkout, read locally for the prompt links.""" tiers = tiers or {} health = health or pr_health try: # the slot file is the merge evidence; fresh at build time @@ -784,14 +782,14 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, lines = [DIGEST_HEADING, ""] lines += closed_early_lines(counters) - # The one notice of the shift's parked questions (M3.5, #645, Decision - # H7 a): no @mention mid-shift, one line here; the asks live in the inbox. + # The one notice of the shift's parked questions: no @mention mid-shift, + # one line here; the asks live in the inbox. inbox = [x for x in [_questions.inbox_line(counters, Path(slot).name, mind)] + _questions.unfiled_lines(counters) if x] lines += inbox + [""] if inbox else [] lines += ["### Brief work"] links = MindLinks(mind, issue) - # A worker still out at review-at keeps its lease (#634, N1). + # A worker still out at review-at keeps its lease. held = {t: l for t, l in held_leases(slot).items() if l.get("state") != "parked"} lines += [_line(t, counters, tiers.get(t, picks.get(t, {}).get("tier", "?")), health, links, lease=held.get(t)) for t in named] or [NO_PICKS] @@ -823,7 +821,7 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, lines += sweep_lines(counters) lines += report_lines(slot) lines += identity_lines(counters) - # The readiness pass's count is the digest's last line (M3.3, #671). + # The readiness pass's count is the digest's last line. try: import _ready # noqa: E402 — deferred: it imports the batch conductor lines += _ready.digest_lines(counters) @@ -835,7 +833,7 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, SWEEP_HEADING = "### Workspace sweep" -#: The prefix of the close-out refusal a sweep block gives (M3.7e): red, or unknown. +#: The prefix of the close-out refusal a sweep block gives: red, or unknown. SWEEP_RED_WHY = "workspace sweep " @@ -846,10 +844,10 @@ def _sweep_own(sweep: dict, at: str) -> dict | None: def sweep_lines(counters: dict) -> list[str]: - """The shift-end cloud sweep (M3.7e, PyAutoBrain#692): the shift's own - dispatch and its run, what the latest green sweep verified per library, - and a red sweep's block, refusals and bug draft. The digest is never held - for the sweep. Nothing when the sweep is off.""" + """The shift-end cloud sweep: the shift's own dispatch and its run, what + the latest green sweep verified per library, and a red sweep's block, + refusals and bug draft. The digest is never held for the sweep. Nothing + when the sweep is off.""" sweep, disp = counters.get("sweep") or {}, counters.get("sweep_dispatch") or {} if not sweep and not disp: return [] @@ -907,7 +905,7 @@ def sweep_lines(counters: dict) -> list[str]: "conflict": "warning: CONFLICT — Mind ledger op set aside, not committed", "held": "warning: Mind ledger op held pending, retried every tick", "withheld": "warning: Mind ledger op withheld with its task, not committed", - # A set-aside whose `needs` is mechanical (#660): already true on main. + # A set-aside whose `needs` is mechanical: already true on main. "mechanical": "note: Mind ledger op set aside (mechanical — already true on main, " "no action)", } @@ -927,9 +925,9 @@ def report_line(e: dict) -> str: def report_lines(slot: Path) -> list[str]: - """PyAutoBrain#632: every note, set-aside, conflict and held op the one - Mind writer reported this shift (`ledger/report.jsonl`) — never only in - tick.log. Nothing when there is none.""" + """Every note, set-aside, conflict and held op the one Mind writer reported + this shift (`ledger/report.jsonl`) — never only in tick.log. Nothing when + there is none.""" f = Path(slot) / "ledger" / "report.jsonl" out = [] for line in (f.read_text(encoding="utf-8").splitlines() if f.is_file() else ()): @@ -941,8 +939,8 @@ def report_lines(slot: Path) -> list[str]: def identity_lines(counters: dict) -> list[str]: - """PyAutoBrain#630: the watcher's App identity failed, so its GitHub writes - were held — never made under the human's own gh auth instead.""" + """The watcher's App identity failed, so its GitHub writes were held — + never made under the human's own gh auth instead.""" auth = counters.get("github_auth") or {} if not auth.get("error"): return [] @@ -956,9 +954,9 @@ def identity_lines(counters: dict) -> list[str]: def backlog_gate_lines(counters: dict) -> list[str]: - """What the M2.3 gates kept out of the backlog dip (AUTONOMY.md "M2 - rulings — 2026-11-12"), as of the watcher's last tick. Not bullets: a - `- ` line in this section is read as a pick and must carry a `why:`.""" + """What the planner's gates kept out of the backlog dip (AUTONOMY.md "M2 + rulings"), as of the watcher's last tick. Not bullets: a `- ` line in + this section is read as a pick and must carry a `why:`.""" gates = counters.get("backlog_gates") or {} out = [] if gates.get("queue_stop"): @@ -986,8 +984,8 @@ def names(paths): for p, w in sorted(repo_held.items())[:SUMMARY_NAMES])) parked = gates.get("parked") or {} if parked: - # The inbox's word on each, by Q-id (M3.5, #645), so "why wasn't X - # picked" answers itself; a park from before the inbox names none. + # The inbox's word on each, by Q-id, so "why wasn't X picked" answers + # itself; a park with no inbox entry names none. inboxed = {p: w for p, w in parked.items() if _QID_RE.search(w)} 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): " @@ -1028,7 +1026,7 @@ def names(urls): 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)) - # One line per queued epic ledger (#696): what it gave the shift, or why + # One line per queued epic ledger: what it gave the shift, or why # nothing. `· ` rather than an indent: an indented line would read as the # continuation of the pick above it. epics = gates.get("queued_epics") or [] @@ -1043,13 +1041,13 @@ def names(urls): return [""] + out if out else [] -# --- per-worker exits, GitHub merges, tokens (PyAutoBrain#610) ----------------- +# --- per-worker exits, GitHub merges, tokens ------------------------------------ WORKERS_HEADING = "### Workers" #: A worker's exit path is words joined by `/` — `spawned/crashed`, #: `spawned/parked/late/finished`. `launch-failed` stands alone: no session #: started. `ended` is a parked worker that ended without a `.done`. -#: `killed` is a worker the human stopped by `/kill` (#644): it is re-dispatched +#: `killed` is a worker the human stopped by `/kill`: it is re-dispatched #: as a crash is, but it is not a crash, so it is not in `CRASH_WORDS`. CRASH_WORDS = ("crashed", "launch-failed") @@ -1067,23 +1065,23 @@ def worker_lines(counters: dict, links: MindLinks | None = None) -> list[str]: out.append(line) events = int(counters.get("event_comments") or 0) if events: - # Needs-you event comments (#644) have their own cap, 5 + 1 a shift, - # and are not pushes for the finding above. + # Needs-you event comments have their own cap, 5 + 1 a shift, and + # are not pushes for the finding above. out.append(f"- needs-you event comments: {events} (at most 5 + 1 a shift)") return out REFUSALS_HEADING = "### Refusals" #: Refusal reasons that carry a running figure, keyed by their class so one -#: refusal is one entry however the figure moves (PyAutoBrain#632, F3). +#: refusal is one entry however the figure moves. _REFUSAL_CLASSES = ( (re.compile(r"^(token-budget \d+) spent\b"), r"\1 spent"), (re.compile(r"^(token-budget \d+): \d+ committed \+ (\d+) reserved per worker"), r"\1: committed + \2 reserved per worker would pass it"), (re.compile(r"^token usage unavailable\b"), "token usage unavailable"), (re.compile(r"^spawn failed\b"), "spawn failed"), - # Close-out refusals, so the event stream's `cls` is stable (#644). The - # public-name check's wording is #641's (`bin/public_names.py` `reason`). + # Close-out refusals, so the event stream's `cls` is stable. The + # public-name check's wording is `bin/public_names.py` `reason`'s. (re.compile(r"^public name added/renamed\b"), "public name added or renamed: a human /prm"), (re.compile(r"^public-name check could not tell\b"), "public-name check could not tell: a human /prm"), @@ -1092,7 +1090,7 @@ def worker_lines(counters: dict, links: MindLinks | None = None) -> list[str]: r"token spend reached \1"), ) #: Refusals whose reason is the shift's, not the task's — summarised in one -#: line for every task they held back (#632, F3 and review). +#: line for every task they held back. SHIFT_WIDE_RE = re.compile(r"^(max-workers \d+ reached|max-sessions \d+ reached" r"|token-budget \d+|token usage unavailable)") #: Tasks a summary line names before `+N more`. @@ -1111,7 +1109,7 @@ def refusal_class(why: str) -> str: def note_refusals(counters: dict, refused: list[dict], at: str) -> None: """Record one tick's refusals: one entry per (task, reason class), with - its count, first and last time and the latest full reason (#632, F3).""" + its count, first and last time and the latest full reason.""" index = {(r.get("task"), r.get("class") or refusal_class(r.get("why", ""))): r for r in counters.setdefault("refusals", [])} for r in refused: @@ -1121,18 +1119,16 @@ def note_refusals(counters: dict, refused: list[dict], at: str) -> None: old = {"task": r.get("task"), "class": cls, "count": 0, "at": at} counters["refusals"].append(old) index[(r.get("task"), cls)] = old - # An entry from before #632 (no `count`) stood for one refusal. + # An entry with no `count` stands for one refusal. old.update(why=r.get("why", ""), last=at, count=int(old.get("count", 1)) + 1) def refusal_lines(counters: dict) -> list[str]: """Every spawn the watcher refused: one line per task and reason class, with how many ticks refused it, from when to when, and the latest figure - where the reason carries one; every `max-workers` refusal in one line - (#610 review, #632 F3); every shift-wide reason (`max-workers`, + where the reason carries one; every shift-wide reason (`max-workers`, `max-sessions`, a token reason) is one line for all the tasks it held - back. A refusal recorded one entry per tick (before - #632) folds into the same lines.""" + back. Entries recorded one per tick fold into the same lines.""" seen: dict[tuple[str, str], dict] = {} for r in counters.get("refusals", []): cls = r.get("class") or refusal_class(r.get("why", "?")) @@ -1169,9 +1165,9 @@ def refusal_lines(counters: dict) -> list[str]: def cap_lines(counters: dict) -> list[str]: - """A cap the human lowered (or raised back) by `/cap` this shift (#644), - one line each: `merge-cap 2 → 1 (/cap by at 18:02Z)`. Not a - counter column, so the pilot rows keep their shape.""" + """A cap the human lowered (or raised back) by `/cap` this shift, one line + each: `merge-cap 2 → 1 (/cap by at 18:02Z)`. Not a counter + column, so the pilot rows keep their shape.""" out = [] for key, ov in sorted((counters.get("caps") or {}).items()): if not isinstance(ov, dict): @@ -1184,7 +1180,7 @@ def cap_lines(counters: dict) -> list[str]: def workers_crashed(counters: dict) -> int: """Workers whose exit path holds a crash (or whose launch failed); a slot - recorded before per-worker exits falls back to its crash tally.""" + with no per-worker exits recorded falls back to its crash tally.""" workers = counters.get("workers") or [] if not workers: return counters.get("crashes", 0) @@ -1241,8 +1237,8 @@ def counter_values(brief: dict, counters: dict) -> dict: budget = brief.get("token-budget", {}).get("value", "?") parts = token_parts(counters) tokens = f"{parts['measured']} of {budget}" - # Close-outs may pass the budget but count against it (AUTONOMY.md, ruling - # 2026-11-14, #632 F5): their share is named, and so is an overrun. + # Close-outs may pass the budget but count against it (AUTONOMY.md): + # their share is named, and so is an overrun. over = str(budget).isdigit() and parts["measured"] > int(budget) extra = ([f"close-outs {parts['closeouts']}"] if parts["closeouts"] else []) \ + ([f"over budget by {parts['measured'] - int(budget)}"] if over else []) \ @@ -1321,7 +1317,7 @@ def _sections(text: str) -> dict[str, list[str]]: def _items(lines: list[str]) -> list[str]: """A section's bullets, each joined with its indented continuation lines - (the second line of a #634 entry).""" + (the second line of a two-line entry).""" items: list[str] = [] for line in lines: if line.startswith("- "): @@ -1331,13 +1327,13 @@ def _items(lines: list[str]) -> list[str]: return items -#: A #634 entry names its task first on its second line. +#: A two-line entry names its task first on its second line. _SUB_SLUG_RE = re.compile(r"(?m)^\s+`([^`]+)`") _WHY_RE = re.compile(r"(?m)(?: — | · )why: (.*?)\s*(?:)?\s*$") def _slug(item: str) -> str: - """The task a digest bullet is about: the slug on a #634 entry's second + """The task a digest bullet is about: the slug on a two-line entry's second line, else the backticked slug a titled pick carries on its one line, else the bullet's first word (a pick recorded without a title).""" m = _BULLET_RE.match(item) @@ -1352,7 +1348,7 @@ def _slug(item: str) -> str: def validate(text: str) -> list[str]: """Errors in a record's `## Digest`; empty when there is none, or it is whole. - Reads both the one-line entries of shifts before #634 and the two-line ones.""" + Reads both one-line entries and two-line ones (`entry_lines`).""" if DIGEST_HEADING not in text: return [] errs = [] diff --git a/agents/conductors/batch/_events.py b/agents/conductors/batch/_events.py index c313aa94..d25f1fab 100644 --- a/agents/conductors/batch/_events.py +++ b/agents/conductors/batch/_events.py @@ -1,5 +1,5 @@ -"""The shift's event stream (M3.4, PyAutoBrain#644): one append-only -`events.jsonl` per slot, beside `counters.json` and `tick.log`. +"""The shift's event stream: one append-only `events.jsonl` per slot, beside +`counters.json` and `tick.log`. The watcher calls `record_tick` inside its tick lock, once per tick that did work, with the tick's result. It renders each new event as one plain sentence @@ -171,14 +171,14 @@ def count(self, prefix: str) -> int: def _inboxed(counters: dict, task: str, issue: str | None = None) -> bool: """Whether this tick's reap filed `task`'s question (on `issue`) in the - questions inbox (M3.5, PyAutoBrain#645: `counters["inbox"]`).""" + questions inbox (`counters["inbox"]`).""" return any(q.get("task") == task and (issue is None or q.get("issue") == issue) for q in counters.get("inbox") or []) def _outcome(event: dict, counters: dict) -> dict: - """A `done` reap's outcome: the event's own fields (#644 adds them), else - the task's outcome in `counters` (an old `tick.log` replay).""" + """A `done` reap's outcome: the event's own fields, else the task's + outcome in `counters` (a replayed `tick.log` event without them).""" fields = ("prs", "merged", "questions", "obsolete", "verdicts", "issues") if any(k in event for k in fields): return {k: event[k] for k in fields if k in event} @@ -227,8 +227,8 @@ def _reaped(b: _Batch, result: dict, counters: dict) -> None: f"{task} merged {ref(pr)} in-turn (notify).", task=task, pr=pr) questions = [] if "obsolete" in o else list(o.get("questions") or []) for q in questions: - # "Added to your inbox" only when the watcher filed it (#645): - # a merged task's question, or one it could not file, is not. + # "Added to your inbox" only when the watcher filed it: a merged + # task's question, or one it could not file, is not. filed = _inboxed(counters, task, q) b.add("question", f"question:{task}:{q}", f"{task} parked with a question on {ref(q)}." @@ -342,7 +342,7 @@ def _closeouts(b: _Batch, result: dict, counters: dict, info: dict) -> None: f"{cls.removesuffix(' this shift')}: later green PRs wait for /prm.", cls=cls) continue - # Merge order (M3.6j, #683): later PRs of the shift wait behind it. + # Merge order: later PRs of the shift wait behind it. later = sum(1 for w in (counters.get("merge_waits") or {}).values() if pr in (w.get("behind") or [])) tail = f"; {later} later PR(s) wait behind it" if later else "" @@ -381,7 +381,7 @@ def _impaired(b: _Batch, result: dict) -> None: b.add("impaired", f"impaired:ledger-error:{why[:80]}", f"Mind write failed: {why}.", needs_you=True) # A mechanical set-aside (already true on main) is a digest line only; - # a worker's human set-asides are one NEEDS YOU per task (#660). + # a worker's human set-asides are one NEEDS YOU per task. by_task: dict = {} per_op = [] for x in ledger.get("set_aside") or []: @@ -411,9 +411,9 @@ def _impaired(b: _Batch, result: dict) -> None: def _login_expired(b: _Batch, result: dict) -> None: - """The CLI login has expired (M3.6a, PyAutoBrain#659): its own needs-you - event, once per episode (keyed by when the tick first saw it) — never read - as a worker blocked on a person.""" + """The CLI login has expired: its own needs-you event, once per episode + (keyed by when the tick first saw it) — never read as a worker blocked + on a person.""" login = result.get("login") or {} if login.get("state") != "expired": return @@ -439,7 +439,7 @@ def _digest_event(b: _Batch, result: dict, counters: dict) -> None: if filed else f" {len(parked)} task{'s' if len(parked) != 1 else ''} parked on a question." if parked else "") - # An early close (M3.7c, #690) says so: the shift ended before review-at. + # The shift ended before review-at: the line says so. closed = "Shift closed early." if counters.get("closed_early") else "Shift closed." if post.get("url"): b.add("digest", "digest", f"{closed} Digest: {post['url']}.{tail}", url=post["url"]) diff --git a/agents/conductors/batch/_green.py b/agents/conductors/batch/_green.py index fe72b14d..73f18ef1 100644 --- a/agents/conductors/batch/_green.py +++ b/agents/conductors/batch/_green.py @@ -1,8 +1,6 @@ -"""The keep-Heart-green lane (PyAutoBrain#625) — runs at brief time. +"""The keep-Heart-green lane — runs at brief time. -The human, 2026-11-13: "having the autonomous agent constantly trying to -ensure its green (without having it be overly eager doing releases)". So at -`batch brief --new` (and `batch green`, its dry run) this reads Heart's +At `batch brief --new` (and `batch green`, its dry run) this reads Heart's verdict, sorts every RED, YELLOW and STALE reason into one of four classes by the transparent RULES table below, and for the `fixable-dev` ones files at most `cap` bug drafts and, on the human's opt-in (`pick`), offers them as @@ -16,10 +14,10 @@ only when the caller allows it (never in a preview, never into the shared canonical Mind: `_batch.write_hold`); return text for the brief. What it never does: release, rehearse, dispatch any workflow, force, touch a freeze, add a -quarantine entry (that needs a human-filed bug task, ruling 2026-11-12 — it -may only PROPOSE one), write `queue.md`, or edit another prompt. It imports -no process or network module: Heart is read through `bin/heart_feed.py` -(published feed or `pyauto-heart readiness --json`, nothing else), and +quarantine entry (that needs a human-filed bug task — it may only PROPOSE +one), write `queue.md`, or edit another prompt. It imports no process or +network module: Heart is read through `bin/heart_feed.py` (published feed or +`pyauto-heart readiness --json`, nothing else), and `tests/test_batch_green.py` pins that. """ @@ -41,7 +39,7 @@ MODES = ("off", "report", "file", "pick") MODE_ENV = "PYAUTO_HEART_GREEN" #: `file` by default; `pick` (naming drafts as the brief's tasks) is the -#: human's opt-in, `--green pick` or `$PYAUTO_HEART_GREEN=pick` (review of #625). +#: human's opt-in, `--green pick` or `$PYAUTO_HEART_GREEN=pick`. DEFAULT_MODE = "file" DEFAULT_CAP = 3 MAX_AGE_HOURS = 6.0 @@ -50,9 +48,9 @@ KEY_MARK = "" #: Manifest legs that judge TRACKED repo content on main, and so are a dev fix. -#: Empty on purpose: every leg Heart reports today runs `repos_sync.py` over -#: the checkouts on disk, other sessions' worktrees included (the 2026-11-13 -#: "tenant firewall — 40 mismatch(es)" were all in one session's worktree). +#: Empty on purpose: every leg Heart reports runs `repos_sync.py` over the +#: checkouts on disk, other sessions' worktrees included, so a mismatch there +#: is not evidence about main. MANIFEST_FIXABLE: tuple[str, ...] = () _CI = r"(?Pfailure|cancelled|timed_out|startup_failure|action_required|error)" @@ -326,7 +324,7 @@ def draft_text(f: dict, heart: dict, today: str) -> str: head = [f"# {title}", "", "Type: bug", f"Target: {repo or 'workspaces'}"] head += ["Repos:", f"- {repo}"] if repo else [] # No `Difficulty:` (sizing derives it, `_file`) and no `Unattended:`: the - # lane never grades its own drafts ready (review of #625). + # lane never grades its own drafts ready. head += ["Autonomy: supervised", f"Priority: {'high' if f['severity'] == 'red' else 'normal'}", "Status: draft", f"Filed: {today}", "Consequence: judge", diff --git a/agents/conductors/batch/_login.py b/agents/conductors/batch/_login.py index 58fcab6e..41caaaa1 100644 --- a/agents/conductors/batch/_login.py +++ b/agents/conductors/batch/_login.py @@ -1,9 +1,8 @@ -"""The CLI login probe (M3.6a, PyAutoBrain#659). +"""The CLI login probe. -Shift 2026-11-16-pm lost its first workers to an expired `claude` login, and -the watcher read them as "blocked on a person". This asks the CLI itself, -with `claude auth status --json` — a local read of the stored login, no model -call — and says one of: +A worker that dies on an expired `claude` login must not be read as "blocked +on a person". This asks the CLI itself, with `claude auth status --json` — a +local read of the stored login, no model call — and says one of: - `ok` — logged in, and the login has not expired; - `expired` — `loggedIn: false`, a `loginExpiresAt` already passed, or the CLI @@ -14,7 +13,7 @@ `batch brief --check` refuses a launch on `expired` (or a login that lapses before `review-at:`); the watcher holds spawning on it (AUTONOMY.md "The -watcher's network surface", Login probe — 2026-11-17). +watcher's network surface", Login probe). """ from __future__ import annotations diff --git a/agents/conductors/batch/_merge_slots.py b/agents/conductors/batch/_merge_slots.py index 7990c3da..29e3793f 100644 --- a/agents/conductors/batch/_merge_slots.py +++ b/agents/conductors/batch/_merge_slots.py @@ -1,13 +1,12 @@ -"""One merge-slot counter per shift (PyAutoBrain#661, ruling R3 of 2026-11-17). +"""One merge-slot counter per shift. Inside a shift every merge counts against the brief's `merge-cap:`: a worker's -in-turn `notify` merge and the watcher's close-outs alike. Shift 2026-11-16-pm -read "2 merged of merge-cap 1" because the workers never asked. A worker runs +in-turn `notify` merge and the watcher's close-outs alike. A worker runs `pyauto-brain merge-slot take ` (`bin/merge_slot.py`) as its own bare call before its bare `gh pr merge`; so does a merge close-out session, immediately -before its merge (M3.7b, PyAutoBrain#688, decision A). The watcher takes a slot -only before it spawns a branch-update session; before a merge close-out it only -reads whether one is free (`room`). All write the same file. +before its merge. The watcher takes a slot only before it spawns a +branch-update session; before a merge close-out it only reads whether one is +free (`room`). All write the same file. The file is `merge_slots.json` in the shift's slot directory, read and written under an exclusive `fcntl.flock` on `merge_slots.lock` beside it, and written @@ -166,10 +165,10 @@ def take(slot: Path, pr: str, by: str, task: str = "") -> tuple[bool, str]: def room(slot: Path, pr: str, task: str, pending: int = 0) -> tuple[bool, str]: """(free, why) — whether `take(pr, task)` would succeed now, read only: - nothing is taken and no refusal recorded (M3.7b, decision A: the watcher - reads this before a merge close-out; the session takes its slot itself, - immediately before the merge). `pending` is the slots already promised to - close-outs still running without one, so the cap is never oversold.""" + nothing is taken and no refusal recorded. The watcher reads this before a + merge close-out; the session takes its slot itself, immediately before + the merge. `pending` is the slots already promised to close-outs still + running without one, so the cap is never oversold.""" key = pr_key(pr) if key is None: return False, (f"{pr!r} is not a https://github.com///pull/ URL " diff --git a/agents/conductors/batch/_mind_writer.py b/agents/conductors/batch/_mind_writer.py index ff6c54cd..f414c79e 100644 --- a/agents/conductors/batch/_mind_writer.py +++ b/agents/conductors/batch/_mind_writer.py @@ -1,13 +1,13 @@ -"""One Mind writer per shift (AUTONOMY.md, 2026-11-03) — the orchestrator's side. +"""One Mind writer per shift (AUTONOMY.md) — the orchestrator's side. Workers never commit to PyAutoMind. They describe each change as an *op file* in the shift's `ledger/` directory (`bin/shift_ledger.py` writes them); the orchestrator applies every pending op in a **temporary detached worktree** on `origin/main`, commits once, and pushes. A rejected push means someone else -moved `main` (another session, the dashboard self-heal bot): the ops are -replayed on the new `origin/main` — a rebase of operations, not of diffs — at -most `PUSH_TRIES` times. The canonical checkout's working tree is never read -or written, nothing is reset, and nothing is forced. +moved `main`: the ops are replayed on the new `origin/main` — a rebase of +operations, not of diffs — at most `PUSH_TRIES` times. The canonical +checkout's working tree is never read or written, nothing is reset, and +nothing is forced. Ops (one JSON object per file, applied in file-name order): @@ -29,91 +29,53 @@ (kind `ruling`, from the readiness pass: `gate` required, `issue` optional) {"op": "question-retire", "path": "questions.md", "prompt": "x.md", "day": "YYYY-MM-DD", "by": "…"} -`queue-retire` moves every live `queue.md` entry whose `ref:` names the -prompt file `prompt` to the `## Retired` footer with `shipped-as:`, using -PyAutoMind's own `lifecycle.py` `queue_retire_text`, the function -`lifecycle.py close` runs. It is loaded from the tree being written, so -the rule is Mind's, never a copy. An unattended close-out queues it with -its complete record, and the watcher queues it again when it reaps the -merge (PyAutoBrain#634: after the first unattended merge its entry -stayed live, and `lifecycle.py check` then failed on the dangling ref). No -live entry naming the prompt is the usual case, and it is silent. - -`question-add` lands one parked worker's question in the human's inbox -(M3.5, PyAutoBrain#645) through PyAutoMind's own `scripts/questions_edit.py` -`add_text`, loaded from the tree being written as `queue-retire` loads -`lifecycle.py` — so the id (the file's highest plus 1, worked out in that -tree) is right on a replay over a moved main, and an entry whose `(shift, -task, issue)` is already there is a skipped note. A question whose prompt is -in neither `draft/` nor `active/` any more is set aside, with its reason; -any other failure (a Mind main without the script) holds it pending. -`question-retire` answers the merged task's Open and Deferred questions -(`lifecycle.questions_close_text`, what `lifecycle.py close` runs), queued -beside every `queue-retire`: an unattended close-out never runs `close`. - -`jsonl-upsert` keeps one JSON line per `row[key]`: the line with that key is -replaced (its other fields kept), else the row is appended. `table-upsert` -does the same for a Markdown table row keyed by its first cell, keeping any -old cell where the new one is `?` (the human's cells), and writes `header` -first into a missing file. Both are how the shift watcher writes its one pilot -row per shift and amends it on a late arrival (PyAutoBrain#610). - -`record-key` sets one top-level `- key: value` line of a batch record — the -key's own line replaced, else inserted after `- issue:` (else `- review-at:`). -The watcher writes the dashboard's `- live:` status line this way -(PyAutoBrain#622); a record no longer on main is skipped, like `set-header`. - -`write` only creates; `edit` changes a file that exists, replacing `old`, -which must appear in it exactly once, with `new` — an expected-base check, so -an edit never clobbers a concurrent change (M3.6d, PyAutoBrain#660: shift -2026-11-16-pm's `write` edits to existing drafts were set aside). - -A worker's ops carry their `task` (`shift_ledger.py --task`). A task's -*closing* ops (`_closing`: its `complete/` record, `drop-section`, the -`active/` prompt's `remove`, `queue-retire`, `question-retire`, and any op on -a path one of them creates) apply after every other op, one group per task, -and are *withheld* — set aside with the task, never retried — when any -sibling op of that task was set aside for a human, this run or earlier in -the shift (a group that fails part-way is rolled back first); while a sibling -is *held* the group stays pending beside it. Mind never records a task -shipped while one of its changes is missing. A `drop-section` paired with -an `append` of the same task re-adding that `## slug` to the same path is an -*update* of the task's own claim, not a close (PyAutoBrain#681): the drop -applies directly before its append, the two as one unit, and only when main's -section is this shift's own (`_own_section`) — else a conflict, set aside. -An op that fails only because it is already true on main -(`MechanicalError`: an edit already applied, a write of the text the file -has, a remove of a file that is gone) is set aside as `needs: mechanical` — -a digest line, not a "needs you". `shift_ledger.py` refuses at queue time -what would fail (`queue_refusals`), so the worker can still switch. - -`set-header` sets one `Key: value` line in a prompt's header block (replacing -the key's line if present) — how a shift worker records the premise check's -`Verified:` stamp (`batch premise --record`) without touching the file itself. +- `write` only creates; `edit` replaces `old`, which must appear exactly + once, with `new` — an expected-base check, so an edit never clobbers a + concurrent change. +- `set-header` sets one `Key: value` line in a prompt's header block; + `record-key` sets one top-level `- key: value` line of a batch record. + Either is skipped when its file is no longer on main. +- `jsonl-upsert` keeps one JSON line per `row[key]` (other fields of a + replaced line kept); `table-upsert` does the same for a Markdown row keyed + by its first cell, keeping an old cell where the new one is `?`, and writes + `header` first into a missing file. +- `queue-retire`, `question-add` and `question-retire` run PyAutoMind's own + `lifecycle.py` / `questions_edit.py` functions, loaded from the tree being + written, so the rule is Mind's and ids are right on a replay over a moved + main. A question whose prompt is in neither `draft/` nor `active/` is set + aside; any other failure holds it pending. Every path must be *ledger* by PyAutoMind's own rule (`scripts/ledger_merge.py` `is_ledger_path`, default deny), so a worker cannot route code through here. -One bad op never strands the rest (PyAutoBrain#632, B1 — a re-dispatched -worker re-queued its claim's `draft→active` move and every later op of the -shift stayed pending): - -- a *repeat* is a skipped note — only a re-dispatched task's own claim (the - caller names those tasks, `own_tasks`) whose earlier op this shift already - committed (`ledger/committed/`) and whose content on main matches it: a - `move` whose source is gone and destination present, a `## slug` section an - `active.md` append already finds there; +A worker's ops carry their `task`. A task's *closing* ops (`_closing`, and any +op on a path one of them creates) apply after every other op, one group per +task, and are *withheld* — set aside with the task, never retried — when any +sibling op of that task was set aside for a human, this run or earlier in the +shift; while a sibling is *held* the group stays pending beside it, and a +group that fails part-way is rolled back. Mind never records a task shipped +while one of its changes is missing. A `drop-section` paired with an `append` +of the same task re-adding that `## slug` to the same path is an *update* of +the task's own claim, not a close: the two apply as one unit, and only when +main's section is this shift's own (`_own_section`). + +One bad op never strands the rest: + +- a *repeat* is a skipped note — only a re-dispatched task's own claim + (`own_tasks`) whose earlier op this shift already committed + (`ledger/committed/`) and whose content on main matches it; - the same shape from anyone else is a *conflict*, set aside loudly; +- an op that is already true on main (`MechanicalError`) is set aside as + `needs: mechanical` — a digest line, not a "needs you"; - any other worker op that fails validation or cannot apply is *set aside* — moved to `ledger/set_aside/` with its reason — and the rest still commit; -- a *critical* op (`CRITICAL_OPS`: the digest and late lines on a batch - record, the pilot row, the live line, a stage-2 row) is never set aside: it - is *held* pending and retried on every tick. - -Every note, set-aside, conflict and first hold is appended to -`ledger/report.jsonl`, which the digest and the late sweep read: none of them -lives only in `tick.log`. Only a push rejected `PUSH_TRIES` times leaves every -op pending. +- a *critical* op (`is_critical`) is never set aside: it is *held* pending + and retried on every tick. + +`shift_ledger.py` refuses at queue time what would fail (`queue_refusals`), +so the worker can still switch. Every note, set-aside, conflict and first hold +is appended to `ledger/report.jsonl`, which the digest and the late sweep +read. Only a push rejected `PUSH_TRIES` times leaves every op pending. """ from __future__ import annotations @@ -137,8 +99,8 @@ #: The keys a `question-add` entry carries; all strings but `options`. QUESTION_KEYS = ("task", "issue", "kind", "ask", "options", "shift", "asked", "worker", "gate") -#: A `ruling` (the readiness pass's, M3.3, PyAutoBrain#671) needs `gate` and -#: may have no `issue`; every other kind needs `issue` and has no `gate`. +#: A `ruling` (the readiness pass's) needs `gate` and may have no `issue`; +#: every other kind needs `issue` and has no `gate`. QUESTION_RULING = "ruling" #: What a watcher-run queue retirement says in the footer, in place of the #: `lifecycle.py close` it did not run. @@ -152,23 +114,23 @@ #: Ops that could not apply (or were invalid), kept for the human with their #: reason (`.why`) — never retried, never blocking the others. SET_ASIDE_DIR = "set_aside" -#: What the writer did besides commit, one JSON line each (#632 review). +#: What the writer did besides commit, one JSON line each. REPORT_FILE = "report.jsonl" #: Op kinds only the watcher writes, and an `append` to a batch record: the #: shift's own record (digest, late lines), pilot row, live line and stage-2 -#: rows. Never set aside — held pending and retried (#632 review). +#: rows. Never set aside — held pending and retried. CRITICAL_KINDS = ("record-key", "jsonl-upsert", "table-upsert", "table-append", - # The questions inbox (#645): a question or its retirement - # is never lost to a passing fault (a Mind main without - # questions_edit.py yet) — held and retried; only a task - # whose prompt is gone sets a question aside (`GoneError`). + # A question or its retirement is never lost to a + # passing fault (a Mind main without questions_edit.py) + # — held and retried; only a task whose prompt is gone + # sets a question aside (`GoneError`). "question-add", "question-retire") def is_critical(op) -> bool: """A watcher op (never set aside, held pending). A worker's own `table-append` (its calibration row, tagged with its `task`) is not: a - bad one is set aside and told, never retried every tick (#660).""" + bad one is set aside and told, never retried every tick.""" if not isinstance(op, dict): return False if op.get("op") == "table-append" and op.get("task"): @@ -210,8 +172,7 @@ class GoneError(MindWriteError): def fetch(mind_repo: Path, remote: str = "origin", branch: str = "main") -> None: """The writer's one network read: `git fetch` of Mind `main` (refs and - objects only — the working tree is never touched). The watcher also calls - it once per shift before its first plan (#632, F4).""" + objects only — the working tree is never touched).""" _git(Path(mind_repo), "fetch", "-q", remote, branch) @@ -354,8 +315,8 @@ def validate_op(op: dict, lm) -> list[str]: #: 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). +#: and the keys a worker might write in their place: a bare `pr:` makes +#: `lifecycle.py check` drift and leaves /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) @@ -379,7 +340,7 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None: `record-key` on a file no longer on main (a stamp must not hold the shift), a `table-append` whose `unique` key a row already carries, and a re-dispatched task's own repeat of a claim this shift already committed - (`ctx`: {"own": task names, "prior": this shift's committed ops}, #632).""" + (`ctx`: {"own": task names, "prior": this shift's committed ops}).""" target = tree / op["path"] kind = op["op"] ctx = ctx or {"own": set(), "prior": []} @@ -411,8 +372,8 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None: elif kind == "move": dest = tree / op["to"] if not target.exists() and dest.exists(): - # A re-dispatched worker re-queues its predecessor's claim (#632): - # a repeat only when this shift itself committed that very move. + # A re-dispatched worker re-queues its predecessor's claim: a repeat + # only when this shift itself committed that very move. task = Path(op["path"]).stem if task in ctx["own"] and any( p.get("op") == "move" and p.get("path") == op["path"] @@ -451,7 +412,7 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None: elif kind == "table-append": text = target.read_text(encoding="utf-8") if target.exists() else "" if op.get("unique") and _section_has(text, op["heading"], op["unique"]): - # A row re-queued after a crash between queue and counters (#632). + # A row re-queued after a crash between queue and counters. return f"table-append: a row with {op['unique']!r} is already there — skipped" target.write_text(table_append(text, op["heading"], op["row"]), encoding="utf-8") elif kind == "queue-retire": @@ -518,8 +479,7 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None: def edit_text(text: str, path: str, old: str, new: str) -> str: """`text` with its one `old` replaced by `new`. `MechanicalError` when the edit is already there (a non-empty `new` present and every `old` inside - it); - `MindWriteError` when `old` is not there exactly once (the base moved).""" + it); `MindWriteError` when `old` is not there exactly once (the base moved).""" n, done = text.count(old), (text.count(new) if new else 0) if done and n == done * new.count(old): raise MechanicalError(f"edit: {path} already has the new text on main") @@ -577,8 +537,8 @@ def get(p): def queue_refusals(mind: Path, op: dict, ledger_dir: Path) -> list[str]: """Why `shift_ledger.py` refuses to queue `op`, checked against Mind `origin/main` and this shift's queued ops — so the worker, still running, - can switch (#660). Empty when it may be queued, and when git cannot be - read: then apply time is the backstop.""" + can switch. Empty when it may be queued, and when git cannot be read: + then apply time is the backstop.""" kind, path = op.get("op"), op.get("path") if kind not in ("write", "edit", "table-append") or not isinstance(path, str): return [] @@ -663,7 +623,7 @@ def _new_sections(old: str, text: str, path: str, lm, no `## ` section is appended as it is. A section already there is a repeat only when its task is a re-dispatch of this shift (`ctx["own"]`) and main's section is exactly the one this shift committed before - (`ctx["prior"]`); any other is a ConflictError (#632 review).""" + (`ctx["prior"]`); any other is a ConflictError.""" pre, entries = lm.split_entries(text) if not entries: return text, None @@ -689,8 +649,7 @@ def _new_sections(old: str, text: str, path: str, lm, def _update_pairs(ops: list) -> dict: """{append file: (drop file, drop op)} — each task's `drop-section` whose `## slug` an `append` of the same task re-adds to the same path: an update - of its own claim (PyAutoBrain#681), not a closing op. A lone drop stays - closing.""" + of its own claim, not a closing op. A lone drop stays closing.""" pairs = {} for f, op in ops: if op.get("op") != "drop-section" or not op.get("task"): @@ -710,7 +669,7 @@ def _own_section(tree: Path, op: dict, lm, ctx: dict) -> None: """ConflictError unless main's `## section` (the one an update pair drops) is this shift's own: exactly a section this shift committed earlier (`ctx["prior"]`), or its `- session:` names this slot's shift worker. A - section that is not there is left to the drop's own error (#681).""" + section that is not there is left to the drop's own error.""" target, heading = tree / op["path"], f"## {op['section']}" if not target.is_file(): return @@ -1021,20 +980,11 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, """Commit every pending op in `/ledger/` to PyAutoMind as one commit. Returns {"committed": sha | None, "ops": n, "tries": k, "skipped": notes, - "set_aside": [{file, op, path, why, kind, needs, task?}], "held": [...]}. `own_tasks` - are the tasks this shift re-dispatched: only their repeated claims may be - skipped as already done (#632 review). A worker op that is invalid or - cannot apply is set aside (a claim already on main from someone else as a - `conflict`); a critical op is held pending instead. Only a push rejected - `PUSH_TRIES` times raises, with every op left pending. - - A task's closing ops (`_closing`, and any op on a path one of them - creates) apply after every other op, task by task, as one group: when one - of the task's ops was set aside for a human (this run or in an earlier - `report`) or is in conflict, the group is `withheld` — set aside with it, - not retried; when one of them is *held* (retried), the group stays pending - beside it. A group that fails part-way is rolled back, so a record never - lands without the rest of its group. + "set_aside": [{file, op, path, why, kind, needs, task?}], "held": [...]}. + `own_tasks` are the tasks this shift re-dispatched: only their repeated + claims may be skipped as already done. Set-aside, held and withheld ops + follow the module docstring's rules; only a push rejected `PUSH_TRIES` + times raises, with every op left pending. """ mind_repo = Path(mind_repo) files = pending_ops(slot) @@ -1056,7 +1006,7 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, continue ops.append((f, op)) # A drop + append of the task's own `## slug` is an update, applied as - # one unit where the append stands (#681); the drop is not closing. + # one unit where the append stands; the drop is not closing. pairs = _update_pairs(ops) paired = {f for f, _op in pairs.values()} ops = [x for x in ops if x[0] not in paired] @@ -1095,7 +1045,7 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, if isinstance(task, str): blocked.setdefault(task, f.name) for f, op in ops: - if f in pairs: # an update of the task's own claim (#681) + if f in pairs: # an update of the task's own claim unit = [pairs[f], (f, op)] try: _own_section(tree, pairs[f][1], lm, ctx) diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 5859298a..95289a43 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -13,26 +13,26 @@ 5. ask the planner what the brief admits (`plan(..., brief=...)`); 6. for each candidate: the caps, then an exclusive-create lease, then spawn. -Workers are fake stubs (`PYAUTO_ORCHESTRATOR_FAKE=1`, phase 3a) or real -`claude --bg` sessions from one session template (phase 3b). A real worker's -liveness is its `claude agents --json` state; one left `blocked` past a grace -is parked for a human — never killed, never re-dispatched. Workers never -commit to PyAutoMind (phase 3c): they queue ledger ops (`bin/shift_ledger.py`) -and each tick commits them from a temporary worktree (`_mind_writer.py`); a -git hook injected through the worker's environment refuses a direct commit. -Nothing here commits, merges or arms a timer: the systemd timer that calls -`bin/orchestrator_watch.py` is installed by the human. Its only GitHub writes -are the comments AUTONOMY.md "The watcher's network surface" lists — the -digest, one correction for a late arrival (#610) and one live status -comment, then only edited (#622) — each claimed by marker first. A parked -worker's question no longer @-mentions the human (M3.5, #645): it lands in -PyAutoMind `questions.md` through the one Mind writer, and the digest counts -it. Each open tick also reads the -shift issue's comments once, for the human's `/pause` `/resume` `/drop` -`/stop` (#622), `/add` `/cap` `/kill` (#644) and `/clear-sweep` (M3.7e). Every -tick that does work appends what it did to the slot's `events.jsonl` (`_events`, #644), which -`batch watch --stream` prints; a needs-you event is also one short comment on -the shift issue, at most `EVENT_COMMENTS_MAX` a shift. +Workers are fake stubs (`PYAUTO_ORCHESTRATOR_FAKE=1`) or real `claude --bg` +sessions from one session template. A real worker's liveness is its +`claude agents --json` state; one left `blocked` past a grace is parked for a +human — never killed, never re-dispatched. Workers never commit to PyAutoMind: +they queue ledger ops (`bin/shift_ledger.py`) and each tick commits them from +a temporary worktree (`_mind_writer.py`); a git hook injected through the +worker's environment refuses a direct commit. Nothing here commits, merges or +arms a timer: the systemd timer that calls `bin/orchestrator_watch.py` is +installed by the human. + +Its only GitHub writes are the comments AUTONOMY.md "The watcher's network +surface" lists — the digest, one correction for a late arrival and one live +status comment, then only edited — each claimed by marker first. A parked +worker's question does not @-mention the human: it lands in PyAutoMind +`questions.md` through the one Mind writer, and the digest counts it. Each +open tick also reads the shift issue's comments once, for the human's steering +commands (`COMMANDS`). Every tick that does work appends what it did to the +slot's `events.jsonl` (`_events`), which `batch watch --stream` prints; a +needs-you event is also one short comment on the shift issue, at most +`EVENT_COMMENTS_MAX` a shift. """ from __future__ import annotations @@ -50,11 +50,11 @@ import _brief # noqa: E402 import _digest # noqa: E402 import _events # noqa: E402 -import _login # noqa: E402 — the CLI login probe (M3.6a, PyAutoBrain#659) -import _merge_slots # noqa: E402 — one merge-cap count per shift (R3, #661) +import _login # noqa: E402 — the CLI login probe +import _merge_slots # noqa: E402 — one merge-cap count per shift import _mind_writer # noqa: E402 import _questions # noqa: E402 -import _sweep # noqa: E402 — the shift-end cloud sweep (M3.7e, PyAutoBrain#692) +import _sweep # noqa: E402 — the shift-end cloud sweep STOP_FILE = "STOP" LOCK_FILE = "tick.lock" @@ -67,40 +67,38 @@ LOCK_TTL_S = 600 #: A worker whose process is gone keeps its lease this long before it is #: declared dead — room for a worker that writes its `.done` marker late. At -#: least two measured tick intervals (median 184 s over 566 ticks to -#: 2026-11-09; PyAutoBrain#603), so one slow tick never outlives a lease. +#: least two tick intervals, so one slow tick never outlives a lease. LEASE_GRACE_S = 420 #: A real worker missing from `claude agents` is a crash only after this many #: consecutive unlisted reads (and the grace) — or a positive ended state. 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. +#: Sessions a re-dispatch may start beyond the brief's `max-sessions:` — 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. STALL_GRACE_S = 900 -#: Sessions that ended without succeeding — reaped as crashes (`_digest`, #592). +#: Sessions that ended without succeeding — reaped as crashes (`_digest`). ENDED_STATES = _digest.ENDED_STATES #: The worker prompt every real worker starts from (never a bare session). WORKER_TEMPLATE = Path(__file__).with_name("worker_template.md") CLOSEOUT_TEMPLATE = Path(__file__).with_name("closeout_template.md") -#: The branch-update session's prompt (M3.6j, PyAutoBrain#683): one -#: `gh pr update-branch` after an earlier PR of the shift on the same library -#: merged, then end — never a merge, never a wait. +#: The branch-update session's prompt: one `gh pr update-branch` after an +#: earlier PR of the shift on the same library merged, then end — never a +#: merge, never a wait. UPDATE_TEMPLATE = Path(__file__).with_name("closeout_update_template.md") -#: The model and effort every spawned worker starts on — the human's ruling of -#: 2026-11-18 (PyAutoBrain#672): Opus at medium effort, whatever the effort of -#: the session that composed the shift. +#: The model and effort every spawned worker starts on, whatever the effort +#: of the session that composed the shift. WORKER_MODEL = "opus" WORKER_EFFORT = "medium" -#: The close-out session's model (phase 4b). The same model as the workers — -#: the human's call 2026-11-04 (AUTONOMY.md "Stage-2 adversary amendment"): a -#: fresh, independent session that runs the witness itself is the leg. Its -#: effort follows the workers too (2026-11-18). Stage-2 rows record this name. +#: The close-out session's model. The same model as the workers (AUTONOMY.md +#: "Stage-2 adversary amendment"): a fresh, independent session that runs the +#: witness itself is the leg. Its effort follows the workers too. Stage-2 +#: rows record this name. CLOSEOUT_MODEL = WORKER_MODEL STAGE2_HEADING = "## Unattended `glance` sub-window (stage 2)" #: A merged close-out that did not say what became of the task's worktree. @@ -170,23 +168,23 @@ def read_counters(slot: Path) -> dict: c.setdefault("picks", {}) # task → {prompt, why, tier}, at dispatch (3d) c.setdefault("outcomes", {}) # task → {prs, merged}, from its `.done` (3d) c.setdefault("closeouts", {}) # PR url → {task, state, why, …} (4b) - # PR url → {task, behind, since}: waiting in merge order (M3.6j, #683) + # PR url → {task, behind, since}: waiting in merge order c.setdefault("merge_waits", {}) - # M3.7b (#688): when the watcher first saw each PR (the NO-CHECKS grace), - # and each PR's changed files, read once per shift (the S6 overlap rule). + # When the watcher first saw each PR (the NO-CHECKS grace), and each + # PR's changed files, read once per shift (the file-overlap rule). c.setdefault("pr_seen", {}) c.setdefault("pr_files", {}) c.setdefault("glance_auto_merges", 0) - # PyAutoBrain#610: tokens per session (replaced each read, never added), - # the sessions whose usage could not be read this tick, one exit record - # per worker, and GitHub's merge state per PR at `review-at:`. + # Tokens per session (replaced each read, never added), the sessions + # whose usage could not be read this tick, one exit record per worker, + # and GitHub's merge state per PR at `review-at:`. c.setdefault("usage", {}) c.setdefault("usage_unavailable", []) c.setdefault("workers", []) c.setdefault("github", {}) - c.setdefault("pushes", 0) # @mentions sent (PyAutoBrain#611) - # PyAutoBrain#622: tasks the human dropped, and every steering command - # enacted with its acknowledgement (`paused` is present only while paused). + c.setdefault("pushes", 0) # @mentions sent + # Tasks the human dropped, and every steering command enacted with its + # acknowledgement (`paused` is present only while paused). c.setdefault("dropped", {}) c.setdefault("commands", []) return c @@ -284,8 +282,8 @@ def pr_files(self, url: str) -> None: return None -#: Prepended to a re-dispatched worker's prompt (PyAutoBrain#632, B1): the -#: crashed worker may already have claimed the task through the ledger. +#: Prepended to a re-dispatched worker's prompt: the crashed worker may +#: already have claimed the task through the ledger. REDISPATCH_NOTE = """\ This is a RE-DISPATCH: an earlier worker on this task crashed. Its claim may already be on PyAutoMind main — the `{task_path}` → `active/` move and the @@ -299,7 +297,7 @@ def pr_files(self, url: str) -> None: #: Prepended to the prompt of a task resumed after the human answered the -#: question an earlier shift parked it on (M3.5, PyAutoBrain#645, Decision H11). +#: question an earlier shift parked it on. RESUME_NOTE = """\ This task parked on a question in shift `{shift}` and the human has answered it ({ids}): see "## Answers from the human" in your prompt{comments}. The @@ -315,8 +313,8 @@ def pr_files(self, url: str) -> None: #: Prepended to the prompt of a worker whose library already has open PRs -#: from this shift (M3.6j, PyAutoBrain#683): its start no longer waits for -#: them to merge, so it must not build on them, and its merge waits for them. +#: from this shift: its start does not wait for them to merge, so it must +#: not build on them, and its merge waits for them. SIBLING_NOTE = """\ Open sibling PRs: this shift already has these PRs OPEN on the same library repo, and they merge BEFORE yours (the close-out merges a library's shift PRs @@ -353,9 +351,9 @@ def worker_prompt(task: str, prompt_path: str, brief_path: Path, lease_dir: Path redispatch: bool = False, resume: dict | None = None, siblings: list[str] | None = None) -> str: """The session template filled in for one task; a re-dispatch is told - that its predecessor's claim may already exist (#632), a resumed task - that the human answered its question (M3.5, #645), and a task whose - library has open PRs from this shift which merge first (M3.6j, #683).""" + that its predecessor's claim may already exist, a resumed task that the + human answered its question, and a task whose library has open PRs from + this shift that they merge first.""" head = REDISPATCH_NOTE.format(task=task, task_path=prompt_path) if redispatch else "" head += resume_note(resume) if resume else "" head += sibling_note(siblings) if siblings else "" @@ -379,12 +377,11 @@ def pr_repos(pr_url: str) -> str: def after_step(after: list[str] | None = None, before: list[str] | None = None, disjoint: list[str] | None = None) -> str: - """The close-out's merge-order step (M3.6j, PyAutoBrain#683), or "" when - no earlier PR of the shift shares this PR's library: every earlier PR - must no longer be OPEN, and every one merged after this branch was cut - must be in it (the update session merged `main` in) — except those whose - changed files are disjoint from this PR's (S6, M3.7b), which are named - and not checked.""" + """The close-out's merge-order step, or "" when no earlier PR of the shift + shares this PR's library: every earlier PR must no longer be OPEN, and + every one merged after this branch was cut must be in it (the update + session merged `main` in) — except those whose changed files are disjoint + from this PR's, which are named and not checked.""" if not (after or before or disjoint): return "" out = ["4b. Merge order (M3.6j, PyAutoBrain#683): this shift's earlier PRs on this\n" @@ -413,18 +410,18 @@ def after_step(after: list[str] | None = None, before: list[str] | None = None, def update_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, lease_dir: Path, after: list[str]) -> str: - """The branch-update session's template filled in (M3.6j, #683).""" + """The branch-update session's template filled in.""" return UPDATE_TEMPLATE.read_text(encoding="utf-8").format( task=task, pr_url=pr_url, task_path=prompt_path, brief_path=brief_path, lease_dir=lease_dir, after="\n".join(f"- {u}" for u in after)) #: How long a close-out started at PR-open waits in-turn for CI before it -#: refuses (`CI not finished by → /prm`; ruling S5, M3.7b). The -#: deadline is never later than `review-at:`. +#: refuses (`CI not finished by → /prm`). The deadline is never +#: later than `review-at:`. CLOSEOUT_CI_WAIT_S = 1800 #: The CI deadline ends this long before `review-at:`, leaving room for the -#: `/prm` run after GREEN, so no close-out merges after `review-at:` (#632 F1). +#: `/prm` run after GREEN, so no close-out merges after `review-at:`. CLOSEOUT_MERGE_MARGIN_S = 300 @@ -432,15 +429,13 @@ def closeout_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, lease_dir: Path, after: list[str] | None = None, before: list[str] | None = None, disjoint: list[str] | None = None, ci_until: str = "") -> str: - """The close-out session template filled in for one PR (phase 4b). Its - Heart check is the scoped development-ship gate for the PR's repo (leg 4, - PyAutoHeart#340): only `green` merges. Its CI check is `pyauto-brain - ci-verdict --until ` on the PR (PyAutoBrain#628; the in-turn - wait of ruling S5, M3.7b): only `GREEN` merges. Its public-name check is - `pyauto-brain public-names` (PyAutoBrain#641): an added or renamed public - library name, or a diff it cannot read, refuses. It runs no full affected - smoke (ruling S2). `ci_until` is the watcher's deadline; without one it is - CLOSEOUT_CI_WAIT_S from now.""" + """The close-out session template filled in for one PR. Its Heart check is + the scoped development-ship gate for the PR's repo: only `green` merges. + Its CI check is `pyauto-brain ci-verdict --until ` on the PR: + only `GREEN` merges. Its public-name check is `pyauto-brain public-names`: + an added or renamed public library name, or a diff it cannot read, + refuses. It runs no full affected smoke. `ci_until` is the watcher's + deadline; without one it is CLOSEOUT_CI_WAIT_S from now.""" ci_until = ci_until or _iso(_now() + _dt.timedelta(seconds=CLOSEOUT_CI_WAIT_S)) repos = pr_repos(pr_url) heart_cmd = (f"bash -c 'source \"{COMMON_SH}\"; consult_vitals_verdict --repos {repos}'" @@ -464,7 +459,7 @@ def closeout_command(task: str, pr_url: str, prompt_path: str, brief_path: Path, ci_until: str = "") -> list[str]: """The argv that starts one close-out session: its own name, the close-out model at the workers' effort, the brief's worker mode. The prompt is last. - With `update_after` it is the branch-update session instead (M3.6j).""" + With `update_after` it is the branch-update session instead.""" if mode not in _brief.WORKER_MODES: raise OrchestratorError(f"worker mode {mode!r} is not one of " + ", ".join(_brief.WORKER_MODES)) @@ -478,16 +473,16 @@ def closeout_command(task: str, pr_url: str, prompt_path: str, brief_path: Path, disjoint, ci_until)] -#: The variable that names the kick file to every session (M3.7c, #690). +#: The variable that names the kick file to every session. KICK_ENV = "PYAUTO_SHIFT_KICK" def kick_path(env: dict | None = None) -> Path: """The kick file `pyauto-orchestrator.path` watches: systemd's `%S` for a user unit — `$XDG_STATE_HOME`, else `~/.local/state` — then - `pyauto/orchestrator.kick` (M3.7c, PyAutoBrain#690). A session appends a - line to it after its verdict file, so the next tick starts at once; the - 60-second timer is the backstop. Local only: no network act.""" + `pyauto/orchestrator.kick`. A session appends a line to it after its + verdict file, so the next tick starts at once; the 60-second timer is the + backstop. Local only: no network act.""" env = os.environ if env is None else env state = str(env.get("XDG_STATE_HOME") or "").strip() if not state or not os.path.isabs(state): @@ -512,10 +507,9 @@ def worker_env(lease_dir: Path, base: dict | None = None) -> dict: PyAutoMind is refused whatever tool makes it. The watcher's own GitHub identity never reaches a worker or close-out: not its static token (`PYAUTO_SHIFT_GH_TOKEN`), not its App settings (`PYAUTO_SHIFT_APP_*`, - the key's path among them, PyAutoBrain#630), and no variable carrying - either token or an App installation token it minted; the human's own gh - auth stays (#611 re-review). `PYAUTO_SHIFT_KICK` names the kick file - (`kick_path`, M3.7c).""" + the key's path among them), and no variable carrying either token or an + App installation token it minted; the human's own gh auth stays. + `PYAUTO_SHIFT_KICK` names the kick file (`kick_path`).""" env = dict(os.environ if base is None else base) secrets = {env.pop(GH_TOKEN_ENV, "").strip()} | _auth().secrets() for key in _app_token.APP_ENVS: @@ -540,7 +534,7 @@ def session_command(task: str, prompt_path: str, brief_path: Path, lease_dir: Pa """The exact argv that starts one worker — named, on `WORKER_MODEL` at `WORKER_EFFORT`, moded, templated; the prompt is the last element. - No `--session-id`: `claude --bg` (2.1.316) assigns its own, so the worker is + No `--session-id`: `claude --bg` assigns its own, so the worker is tracked by the short id the launch prints.""" if mode not in _brief.WORKER_MODES: raise OrchestratorError(f"worker mode {mode!r} is not one of " @@ -563,24 +557,22 @@ def session_command(task: str, prompt_path: str, brief_path: Path, lease_dir: Pa def scope_command(argv: list[str], task: str, env: dict | None = None, which=shutil.which) -> list[str]: """`argv` wrapped in its own transient systemd user scope, when the watcher - runs inside a systemd unit and `systemd-run` is on PATH (PyAutoBrain#634). + runs inside a systemd unit and `systemd-run` is on PATH. The first `claude --bg` starts the per-user background-session daemon - (`claude daemon run`, `origin=transient`) and its `bg-pty-host` spares. - They inherit the cgroup of whoever launched them. Launched from the - watcher's oneshot `pyauto-orchestrator.service`, they lived in that - unit's cgroup, outlived each tick, and systemd logged "Found left-over - process" on every tick of the first live shift (211 lines). In a scope - of their own (`app.slice/run-*.scope`) they never share the unit's - cgroup, and the scope goes away when its last process exits: the daemon - already quits on its own 5 s after its last client. A daemon some other + (`claude daemon run`) and its `bg-pty-host` spares, which inherit the + cgroup of whoever launched them. Launched from the watcher's oneshot + `pyauto-orchestrator.service` they would outlive each tick inside that + unit's cgroup ("Found left-over process" on every tick). In a scope of + their own (`app.slice/run-*.scope`) they never share the unit's cgroup, + and the scope goes away when its last process exits. A daemon some other session already runs is only connected to; the scope then holds the short-lived client and closes at once. Nothing here stops anything. `--scope` runs the command as systemd-run's own child, so the worker's environment and working folder pass through unchanged. Outside a unit (no `INVOCATION_ID`: a hand-run tick, CI, macOS) or without - `systemd-run`, the argv comes back unchanged — spawned as before.""" + `systemd-run`, the argv comes back unchanged.""" env = os.environ if env is None else env if not env.get("INVOCATION_ID") or not which("systemd-run"): return list(argv) @@ -590,7 +582,7 @@ def scope_command(argv: list[str], task: str, env: dict | None = None, def run_scoped(run, argv: list[str], task: str, **kw): """Run `argv` through `scope_command`; if systemd-run itself could not - make the scope (no user bus), run it plain, exactly as before #634.""" + make the scope (no user bus), run it plain.""" wrapped = scope_command(argv, task, kw.get("env")) res = run(wrapped, **kw) if wrapped != argv and res.returncode != 0 and _SCOPE_FAILED_RE.search(res.stderr or ""): @@ -605,10 +597,9 @@ def run_scoped(run, argv: list[str], task: str, **kw): def public_names_gate(pr_url: str, check=None) -> str: """The deterministic public-name check (AUTONOMY.md "Public-name - narrowing of `glance` — 2026-11-16", PyAutoBrain#641) on one PR, run by - the watcher before a close-out session spawns: '' to go on, else the - refusal's `why`. A repo outside the ruled libraries goes on; a hit or a - check that cannot tell refuses.""" + narrowing of `glance`") on one PR, run by the watcher before a close-out + session spawns: '' to go on, else the refusal's `why`. A repo outside the + ruled libraries goes on; a hit or a check that cannot tell refuses.""" try: if check is None: sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "bin")) @@ -620,7 +611,7 @@ def public_names_gate(pr_url: str, check=None) -> str: class RealSpawner: - """`claude --bg` workers from the session template (phase 3b).""" + """`claude --bg` workers from the session template.""" real = True @@ -633,11 +624,11 @@ def __init__(self, brief_path: Path, mode: str, cwd: Path | None = None, run=Non self.public_names = public_names or public_names_gate def pr_state(self, url: str) -> dict | None: - """GitHub's word on a PR — the merge truth for a close-out (#603).""" + """GitHub's word on a PR — the merge truth for a close-out.""" return self.gh(url) def pr_files(self, url: str) -> list[str] | None: - """A PR's changed files — the branch-update decision (S6, M3.7b).""" + """A PR's changed files — the branch-update decision.""" return self.files(url) def spawn(self, task: str, prompt_path: str, lease_dir: Path, @@ -665,8 +656,8 @@ def spawn_closeout(self, task: str, pr_url: str, prompt_path: str, lease_dir: Pa before: list[str] | None = None, disjoint: list[str] | None = None, ci_until: str = "") -> dict: # The public-name check runs here, deterministically, before any - # session (#641): a hit or a cannot-tell is this PR's refusal, written - # as the verdict a close-out would write, and nothing is spawned. + # session: a hit or a cannot-tell is this PR's refusal, written as + # the verdict a close-out would write, and nothing is spawned. why = self.public_names(pr_url) if why: verdict = {"result": "refused", "pr": pr_url, "why": why, @@ -676,8 +667,8 @@ def spawn_closeout(self, task: str, pr_url: str, prompt_path: str, lease_dir: Pa argv = closeout_command(task, pr_url, prompt_path, self.brief_path, lease_dir, self.mode, update_after=update_after, after=after, before=before, disjoint=disjoint, ci_until=ci_until) - # The same scoped route as a worker (#634): a close-out may be the - # session that starts the daemon. + # The same scoped route as a worker: a close-out may be the session + # that starts the daemon. env = worker_env(lease_dir) _ensure_kick_dir(env) res = run_scoped(self.run, argv, task, cwd=self.cwd, capture_output=True, text=True, @@ -712,7 +703,7 @@ class AgentsView: A read that fails, times out or prints something other than a JSON list is *unknown* (`known()` is False) — never an empty list, which would declare - every worker gone (PyAutoBrain#603).""" + every worker gone.""" def __init__(self, sessions: list[dict] | None = None, run=None): self._sessions, self._run = sessions, run or subprocess.run @@ -741,9 +732,9 @@ def _find(self, agent_id: str) -> dict | None: return next((s for s in self._load() or [] if s.get("id") == agent_id), None) def state(self, agent_id: str) -> str | None: - """The CLI's state word — `working` while it runs (2.1.316), `blocked` - waiting on a person, `done` — or None if unlisted. Anything but - `blocked` / `done` / None is read as alive.""" + """The CLI's state word — `working` while it runs, `blocked` waiting on + a person, `done` — or None if unlisted. Anything but `blocked` / `done` + / None is read as alive.""" s = self._find(agent_id) return None if s is None else (s.get("state") or "running") @@ -761,12 +752,11 @@ def _liveness_known(agents) -> bool: def gh_pr_state(url: str, run=None) -> dict | None: """One read-only `gh pr view`: {state, mergedAt, mergedBy, head, - mergeable} as GitHub has it, or None when GitHub could not say (#603: the - merge truth). `head` (the head sha) tells an updated branch's CI from an - older head's (M3.6j); `mergeable` (`MERGEABLE`, `CONFLICTING` or - `UNKNOWN`) sends a conflicting PR to its branch update (S6, M3.7b); - `labels` (their names) refuses a `decision-taken` PR at PR-open (S7, - M3.7c) — one more field of the same read.""" + mergeable, labels} as GitHub has it, or None when GitHub could not say. + `head` (the head sha) tells an updated branch's CI from an older head's; + `mergeable` (`MERGEABLE`, `CONFLICTING` or `UNKNOWN`) sends a conflicting + PR to its branch update; `labels` (their names) refuses a + `decision-taken` PR at PR-open.""" run = run or subprocess.run try: res = run(["gh", "pr", "view", url, "--json", @@ -795,9 +785,9 @@ def gh_pr_state(url: str, run=None) -> dict | None: def gh_pr_files(url: str, run=None) -> list[str] | None: """One read-only `gh pr view --json files`: the PR's changed paths, or - None when GitHub could not say or the list may be truncated (S6, M3.7b: - the branch-update decision; AUTONOMY.md "The watcher's network surface", - amendment 2026-11-19). The watcher reads it at most once per PR per shift.""" + None when GitHub could not say or the list may be truncated (the + branch-update decision; AUTONOMY.md "The watcher's network surface"). + The watcher reads it at most once per PR per shift.""" run = run or subprocess.run try: res = run(["gh", "pr", "view", url, "--json", "files"], @@ -821,7 +811,7 @@ def gh_pr_files(url: str, run=None) -> list[str] | None: ("cache_read", "cache_read_input_tokens")) _USAGE_KEYS = ("total", "input", "output", "cache_creation", "cache_read", "subagents") #: Consecutive unreadable reads after which one session stops refusing every -#: spawn: its reservation stands in for its usage and it is `unmeasured` (#610). +#: spawn: its reservation stands in for its usage and it is `unmeasured`. UNREADABLE_READS = 3 @@ -845,11 +835,11 @@ def transcript_usage(session_id: str, root: Path | None = None) -> dict | None: reads — no network): input, output, cache creation and cache read, with `total` = input + output + cache creation (cache reads are reported, not counted). A transcript repeats one assistant message on several lines with - the same usage, so usage is taken once per message id (PyAutoBrain#610: - summing every line read about 1.6× high). The session's subagents write - their own transcripts under `/subagents/agent-*.jsonl`; they are - included, deduped the same way, and `subagents` reports their share of - `total`. None when there is no transcript or one cannot be read — never 0.""" + the same usage, so usage is taken once per message id. The session's + subagents write their own transcripts under + `/subagents/agent-*.jsonl`; they are included, deduped the same way, + and `subagents` reports their share of `total`. None when there is no + transcript or one cannot be read — never 0.""" root = root or Path.home() / ".claude" / "projects" main = list(root.glob(f"*/{session_id}.jsonl")) subs = list(root.glob(f"*/{session_id}/subagents/agent-*.jsonl")) @@ -892,12 +882,12 @@ def _as_usage(raw) -> dict | None: def _measure(counters: dict, key: str, sid: str | None, tokens, *, kind: str, task: str, final: bool = False) -> None: - """Read one session's usage and store it **replacing** the last read - (PyAutoBrain#610) — so a re-read never adds twice. An unreadable usage - keeps the last value and marks the session unavailable for this tick, - which refuses the next spawn; it is never stored as 0. After - `UNREADABLE_READS` unreadable reads in a row the session is `unmeasured`: - it stops refusing spawns, and its reservation counts as its usage.""" + """Read one session's usage and store it **replacing** the last read — so + a re-read never adds twice. An unreadable usage keeps the last value and + marks the session unavailable for this tick, which refuses the next + spawn; it is never stored as 0. After `UNREADABLE_READS` unreadable reads + in a row the session is `unmeasured`: it stops refusing spawns, and its + reservation counts as its usage.""" entry = counters["usage"].setdefault(key, {"kind": kind, "task": task, "total": None}) usage = _as_usage(tokens(sid)) if sid else None if usage is None: @@ -938,19 +928,17 @@ 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, or the - measured spend of a finished worker when that is larger (#637, item 8). + measured spend of a finished worker when that is larger. 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.""" + reservations of budget/N fit the budget exactly, whatever the workers + really spend. 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. + # Never above half the budget: one outlier worker must not refuse the + # first spawn. Never below the share. return max(share, min(int(estimate or 0), budget // 2)) @@ -990,8 +978,8 @@ def worker_token_estimate(slot: Path, counters: dict, budget: int | None = 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.""" + """An earlier shift's `token-budget:` — recorded in its `counters.json`, + 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: @@ -1008,7 +996,7 @@ def slot_budget(slot: Path, mind: Path | None = None) -> int | 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).""" + note on stderr, never a planner crash.""" try: c = read_counters(slot) for key in ("outcomes", "usage"): @@ -1070,9 +1058,8 @@ def task_id(prompt_path: str) -> str: def lease_files(slot: Path) -> list[Path]: """The lease files of a slot. A parked worker's `{task}.question.json` - sidecar shares the folder and is not a lease: read as one it had no pid, - `_alive(0)` called it running, and it held a worker slot to `review-at:` - (2026-11-20-am: four sidecars filled `max-workers 4`, 11 tasks waited).""" + sidecar shares the folder and is not a lease: read as one it would have + no pid, count as running, and hold a worker slot to `review-at:`.""" return [f for f in sorted((Path(slot) / "leases").glob("*.json")) if not f.name.endswith(_questions.SIDECAR_SUFFIX)] @@ -1117,13 +1104,13 @@ def _reap(slot: Path, counters: dict, now: _dt.datetime, grace_s: float, Every transition is written to `counters.json` as it happens, and a lease or `.done` marker is deleted only after that write — a tick that fails - later never forgets a reap (PyAutoBrain#603). A parked worker keeps its - lease (`state: parked`), so its late `.done` is still read here. + later never forgets a reap. A parked worker keeps its lease + (`state: parked`), so its late `.done` is still read here. Every real session's usage is read on every tick, live, parked or - finishing, and stored per session (PyAutoBrain#610). Each transition is - also written to the worker's exit record (`spawned/…`); `late` (the late - sweep) marks what arrives after `review-at:`. + finishing, and stored per session. Each transition is also written to the + worker's exit record (`spawned/…`); `late` (the late sweep) marks what + arrives after `review-at:`. """ events = [] lease_dir = slot / "leases" @@ -1182,9 +1169,9 @@ def mark(word, rec=rec): # The digest reads these at review-at, long after the marker is gone. counters["outcomes"][task] = _digest.parse_done( done_marker.read_text(encoding="utf-8", errors="replace")) - # Each question lands in the inbox (M3.5, #645): one Mind writer - # op per issue, queued before the counters write; a replay after a - # crash is a silent repeat in `questions_edit.add_text`. + # Each question lands in the inbox: one Mind writer op per issue, + # queued before the counters write; a replay after a crash is a + # silent repeat in `questions_edit.add_text`. done = counters["outcomes"][task] if done.get("questions") and "obsolete" not in done and not done.get("merged"): for url in done["questions"]: @@ -1197,15 +1184,15 @@ def mark(word, rec=rec): 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. + # retire its live queue.md entry as an unattended merge does. + # 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) - # Its inbox questions are moot once merged (#645 review): - # answered as `(task completed)`, as `lifecycle.py close` would. + # Its inbox questions are moot once merged: answered as + # `(task completed)`, as `lifecycle.py close` would. _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, question_retire_op(counters, task, now, by="the shift worker, in-turn")) @@ -1267,7 +1254,7 @@ def mark(word, rec=rec): if real: path.write_text(json.dumps(lease, sort_keys=True)) # the unlisted count continue # gone, but inside the grace for a late `.done` - # A worker the human stopped by `/kill` (#644) ends as `killed`, not + # A worker the human stopped by `/kill` ends as `killed`, not # `crashed`: it counts for the re-dispatch rule, not as a crash. killed = (counters.get("killed") or {}).get(task) or {} by_kill = bool(killed) and killed.get("key") == rec.get("key") @@ -1290,18 +1277,18 @@ def mark(word, rec=rec): def land_question(slot: Path, counters: dict, lease: dict, task: str, issue: str, kind: str, ask: str, options: list, worker: str, now: _dt.datetime) -> bool: - """Queue one `question-add` op for the Mind writer (M3.5, #645) and note - it in `counters["inbox"]`. Nothing without the task's prompt or an issue - (a lease from before M3.5 carries no shift issue: held as before). The - watcher never reads the issue: the ask is the worker's sidecar, else - `see the question on the issue`. True when it was queued.""" + """Queue one `question-add` op for the Mind writer and note it in + `counters["inbox"]`. Nothing without the task's prompt or an issue (a + lease that carries no shift issue: held). The watcher never reads the + issue: the ask is the worker's sidecar, else `see the question on the + issue`. True when it was queued.""" prompt = lease.get("prompt") or (counters["picks"].get(task) or {}).get("prompt") or "" why = ("no prompt recorded for the task" if not prompt else "no shift issue on its lease (spawned before M3.5)" if not issue else f"issue `{str(issue)[:80]}` is not an https URL" if not str(issue).startswith("https://") else "") if why: - # Never silent (#645 review): the digest names what was not filed. + # Never silent: the digest names what was not filed. unfiled = counters.setdefault("inbox_unfiled", []) if not any(u.get("task") == task and u.get("kind") == kind for u in unfiled): unfiled.append({"task": task, "kind": kind, "why": why}) @@ -1332,8 +1319,7 @@ def brief_open(brief_path: Path, mind: Path, now: _dt.datetime) -> tuple[bool, s if now >= at: return False, f"review-at {rec['top']['review-at']['value']} has passed", None # The shift is `dispatched:` → `review-at:`. Landing the brief early is - # allowed; it grants nothing until its start (PyAutoBrain#589 — shadow - # shift 1 opened on landing, a day early). + # allowed; it grants nothing until its start. start = _brief._iso(rec["top"]["dispatched"]["value"]) if now < start: return False, f"not yet open: opens at dispatched {rec['top']['dispatched']['value']}", None @@ -1341,9 +1327,9 @@ def brief_open(brief_path: Path, mind: Path, now: _dt.datetime) -> tuple[bool, s def late_owed(slot: Path) -> bool: - """What the watcher still owes a shift once its late window has closed - (M3.6a review): the digest not yet claimed, a digest or correction post - that failed with tries left, or a queued Mind op. Local reads only.""" + """What the watcher still owes a shift once its late window has closed: + the digest not yet claimed, a digest or correction post that failed with + tries left, or a queued Mind op. Local reads only.""" slot = Path(slot) return (not (slot / DIGEST_MARKER).exists() or post_due(slot / DIGEST_MARKER) or post_due(slot / CORRECTION_MARKER) or bool(_mind_writer.pending_ops(slot))) @@ -1351,7 +1337,7 @@ def late_owed(slot: Path) -> bool: def _late_closed(brief_path: Path, now: _dt.datetime) -> str: """When the late window closed (`review-at:` + `_brief.LATE_WINDOW_S`) as - ISO, if it has; else "" (M3.6a, PyAutoBrain#659). Local reads only.""" + ISO, if it has; else "". Local reads only.""" try: top = _brief.parse(Path(brief_path).read_text(encoding="utf-8"))["top"] except (OSError, _brief.BriefError): @@ -1371,10 +1357,10 @@ def _default_pr_state(): def tick(brief_path: Path, mind: Path, *, home: Path | None = None, now: _dt.datetime | None = None, auth=None, **kw) -> dict: """One watcher tick, with its GitHub identity bound for the tick's own - `gh` calls (PyAutoBrain#630): a `_app_token.WatcherAuth` over the state - directory — the App's installation token, minted when the tick's first - watcher GitHub call needs it and held in memory for this tick only — - unless a test passes its own `auth`.""" + `gh` calls: a `_app_token.WatcherAuth` over the state directory — the + App's installation token, minted when the tick's first watcher GitHub + call needs it and held in memory for this tick only — unless a test + passes its own `auth`.""" global _AUTH now = now or _now() prev = _AUTH @@ -1396,15 +1382,14 @@ def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, """One watcher tick. Returns what it did; also appended to `tick.log`. `pr_state` and `pr_files` are the `gh pr view` seams (a PR's state, and - its changed files for the branch-update decision, S6); unset, the - spawner's. + its changed files for the branch-update decision); unset, the spawner's. `github` is the `run` seam for the live status comment and the steering - read (PyAutoBrain#622) — a test's fake `gh`; unset, the real one. + read — a test's fake `gh`; unset, the real one. - After `review-at:` the one remaining act is the digest (phase 3d), once — - then the late sweep, while a worker is still out, an op is queued or a - failed post is due its retry.""" + After `review-at:` the one remaining act is the digest, once — then the + late sweep, while a worker is still out, an op is queued or a failed post + is due its retry.""" now = now or _now() brief_path = Path(brief_path) slot = slot_dir(brief_path, home) @@ -1415,11 +1400,11 @@ def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, is_open, why, brief = brief_open(brief_path, mind, now) if not is_open: - # The late window has closed and nothing is owed (M3.6a, - # PyAutoBrain#659): the digest is out with no retry due and no Mind op - # is queued. The shift is over for the watcher: no lock, no reap, no - # lease renewed, no log line — a worker still out is the human's, by - # the digest. Anything still owed is caught up first, below. + # The late window has closed and nothing is owed: the digest is out + # with no retry due and no Mind op is queued. The shift is over for the + # watcher: no lock, no reap, no lease renewed, no log line — a worker + # still out is the human's, by the digest. Anything still owed is + # caught up first, below. closed = _late_closed(brief_path, now) if closed and not late_owed(slot): return {"action": "idle", "reason": f"late window closed at {closed} " @@ -1459,9 +1444,9 @@ def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, return {"action": "idle", "reason": why} if (slot / DIGEST_MARKER).exists(): - # Closed early (M3.7c, #690): the digest is out before `review-at:`. - # As after `review-at:`, the late sweep runs while something is - # still owed; nothing is spawned, closed out or posted again. + # Closed early: the digest is out before `review-at:`. As after + # `review-at:`, the late sweep runs while something is still owed; + # nothing is spawned, closed out or posted again. return _after_early_close(brief_path, mind, slot, now, spawner=spawner, grace_s=grace_s, agents=agents, tokens=tokens, poster=poster, pr_state=pr_state) @@ -1496,8 +1481,8 @@ def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, def _fetch_once(mind: Path, counters: dict, now: _dt.datetime) -> None: """One `git fetch` of Mind per shift, before its first plan, through the - one Mind writer's own fetch (#632 review; AUTONOMY.md "The watcher's - network surface"). A failed fetch is recorded and the local ref read.""" + one Mind writer's own fetch (AUTONOMY.md "The watcher's network + surface"). A failed fetch is recorded and the local ref read.""" if counters.get("origin_fetch"): return try: @@ -1508,9 +1493,9 @@ def _fetch_once(mind: Path, counters: dict, now: _dt.datetime) -> None: _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). +#: An answer restarts its task this shift only with more than this left. INSHIFT_RESTART_S = 30 * 60 -#: The bounded re-fetch for an in-shift answer: at most this often (M3.6c). +#: The bounded re-fetch for an in-shift answer: at most this often. ANSWER_FETCH_EVERY_S = 10 * 60 @@ -1525,12 +1510,12 @@ def _open_parks(counters: dict) -> list[str]: 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`.""" + """The shift's one fetch (`_fetch_once`), then (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) @@ -1552,16 +1537,16 @@ def _fetch_for_answers(mind: Path, counters: dict, now: _dt.datetime, 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.""" + inbox has answered, while more than `INSHIFT_RESTART_S` remain: the task + restarts this shift instead of the next. + + Idempotent and durable: 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() @@ -1598,12 +1583,12 @@ def _spawned_release(counters: dict, task: str, now: _dt.datetime) -> None: 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 (a merge-order wait among - them), updated from main but not yet closed out (M3.6j), 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, + """Carry-over at a shift's first tick: the newest earlier slot's late + `glance`/`notify` PRs — never closed out (a merge-order wait among them), + updated from main but not yet 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: @@ -1625,13 +1610,13 @@ def carry_in(slot: Path, counters: dict, now: _dt.datetime) -> dict: 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). + # recorded for it (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. continue # A PR still waiting in merge order, or whose branch was updated - # but not yet closed out (M3.6j), carries too. + # but not yet closed out, carries too. 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 @@ -1644,7 +1629,7 @@ def carry_in(slot: Path, counters: dict, now: _dt.datetime) -> dict: counters["outcomes"][task] = {"prs": prs, "merged": [], "issues": [], "carried_from": rec["from"]} # What each waited behind comes along, so a carried PR never - # merges ahead of an earlier one that was not carried (M3.6j). + # merges ahead of an earlier one that was not carried. behind = [b for u in prs for b in ((prev.get("merge_waits") or {}).get(u) or {}).get("behind") or []] if behind: @@ -1662,16 +1647,16 @@ def carry_in(slot: Path, counters: dict, now: _dt.datetime) -> dict: 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`. + """What Mind `origin/main` holds, read locally and read-only: its `draft/` + paths and the `## slug` sections of its `active.md`. Never a pull. `fetch` (the writer's own `git fetch`, once per shift) runs first; after it, the one Mind writer fetches and pushes through this checkout on every commit, so the local `origin/main` ref holds every claim this watcher committed — the claims a stale canonical `draft/` - hides. None when `mind` is not a git - checkout (a scratch Mind: nothing to read); `{"error": …}` when it is one - and the ref cannot be read — the caller then fails closed.""" + hides. None when `mind` is not a git checkout (a scratch Mind: nothing to + read); `{"error": …}` when it is one and the ref cannot be read — the + caller then fails closed.""" def git(*args): return subprocess.run(["git", "-C", str(mind), *args], capture_output=True, text=True, timeout=60) @@ -1688,9 +1673,9 @@ def git(*args): except (OSError, subprocess.SubprocessError) as e: return {"error": f"git could not run: {e}"[:200]} 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). + # No claims read is not "no claims": 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: " @@ -1700,7 +1685,7 @@ def git(*args): "repos": claimed_repos(sections), "sections": sections} -#: A claim that records human-authorized sharing of its repos (#637, item 4). +#: A claim that records human-authorized sharing of its repos. _COORDINATION_RE = re.compile(r"^- (coordination|conflict-override):\s*\S", re.M) _CLAIM_REPO_RE = re.compile(r"^\s+- ([A-Za-z0-9_.-]+)") _COORDINATION_LINE_RE = re.compile(r"(?m)^- (?:coordination|conflict-override):(.*)$") @@ -1712,11 +1697,9 @@ def _slug_form(text: str) -> str: def coordinated_for(sec: dict, task: str) -> bool: """Whether a claim's `coordination:` / `conflict-override:` line frees its - repos for `task` (ruling R2, 2026-11-17): only when it names the task, by - its slug or prompt stem (`-` and `_` alike). Such a line records sharing - the human approved with one named task — in shift 2026-11-16-pm a task was - dispatched onto a claim whose override named another task — never a free - pass for any.""" + repos for `task`: only when it names the task, by its slug or prompt stem + (`-` and `_` alike). Such a line records sharing the human approved with + one named task — never a free pass for any other.""" text = _slug_form(sec.get("coordination") or "") name = _slug_form(task or "") return bool(name) and bool(re.search(rf"(? str: def _library_key(pr_url: str) -> str: """The library repo key a PR URL belongs to (`_repo_key` of its repo), - or "" when its repo is not a library — only library PRs merge in order - (ruling f, 2026-11-19).""" + or "" when its repo is not a library — only library PRs merge in order.""" from _sizing import LIBRARY_REPOS # noqa: E402 — the batch conductor's path repo = pr_repos(pr_url) key = _repo_key(repo) if repo else "" @@ -1780,9 +1762,9 @@ def _library_key(pr_url: str) -> str: def sibling_prs(counters: dict, repos) -> list[str]: - """This shift's PRs not yet merged on one of `repos`' library repos - (M3.6j, #683), in PR-number order: the PRs a new worker on that library - must not stack on, and whose merges come before its own.""" + """This shift's PRs not yet merged on one of `repos`' library repos, in + PR-number order: the PRs a new worker on that library must not stack on, + and whose merges come before its own.""" libs = {_repo_key(r) for r in repos} out = [] for o in (counters.get("outcomes") or {}).values(): @@ -1835,7 +1817,7 @@ def claimed_repos(sections: dict[str, dict]) -> dict[str, tuple[str, str]]: #: A claim's `- session:` that names a shift worker, in exactly the wording #: `worker_template.md` pins: `shift worker ()`. Anything #: else (a desktop session, a human who took the task over and rewrote the -#: line, the free wording of the first shifts) is not resumed unattended. +#: line, free wording) is not resumed unattended. SHIFT_WORKER_SESSION_RE = _mind_writer.SHIFT_WORKER_SESSION_RE @@ -1857,13 +1839,12 @@ def claim_of(sections: dict[str, dict], task: str) -> tuple[str, dict] | None: def released_picks(counters: dict, live: set[str] | None = None) -> set[str]: """This shift's own picks that no longer hold their library repos for a - START (M3.6j, PyAutoBrain#683; first PyAutoBrain#679): a library is held - only while a worker on it is live. A pick that finished (done or - abandoned) releases it, PR open or not: work does not collide, merges do, - and the close-out serialises merges in PR order (`_merge_blockers`). - Still holding: a live lease, a park on a question or a person (ruling d), - an outcome with an open question, a pending re-dispatch (`/kill` or a - crash: the re-dispatch reuses its PR) or an answered park waiting to + START: a library is held only while a worker on it is live. A pick that + finished (done or abandoned) releases it, PR open or not: work does not + collide, merges do, and the close-out serialises merges in PR order + (`_merge_blockers`). Still holding: a live lease, a park on a question or + a person, an outcome with an open question, a pending re-dispatch (`/kill` + or a crash: the re-dispatch reuses its PR) or an answered park waiting to restart. A task the human `/drop`ped holds nothing once no worker of it is live (`live`, the tick's active leases), started or not.""" hold = {*(counters.get("parked") or []), *(counters.get("pending_redispatch") or []), @@ -1890,23 +1871,21 @@ def on_origin(records: list[dict], mind: Path, own: set[str], `## ` section in its `active.md`. A task this shift already picked 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}). - - `resumes` are the tasks an answer released (M3.5, #645, Decision H11): a - resume task already claimed is kept, at its `active/` path, but only when - its claim's `- session:` is `shift worker ()` for a slot of - this home that picked it — a claim an interactive session owns, or one a - human took over, is the human's work and is left alone. Its own claim - never counts against its repos; every other claim on them does. - - `released` (PyAutoBrain#679) are this shift's own picks that hold no - library start any more (`released_picks`: finished, PR may still be - open). A claim one of them left behind — the close-out drops it only - after the merge, and a set-aside op, a failed push or a close-out that - skipped it leaves the section — holds nothing, when - its `- session:` is this shift's own worker (`slot_name`). Any other - claim still holds.""" + coordination. Returns (kept, {path: why}). + + `resumes` are the tasks an answer released: a resume task already claimed + is kept, at its `active/` path, but only when its claim's `- session:` is + `shift worker ()` for a slot of this home that picked it — a + claim an interactive session owns, or one a human took over, is the + human's work and is left alone. Its own claim never counts against its + repos; every other claim on them does. + + `released` are this shift's own picks that hold no library start any more + (`released_picks`: finished, PR may still be open). A claim one of them + left behind — the close-out drops it only after the merge, and a + set-aside op, a failed push or a close-out that skipped it leaves the + section — holds nothing, when its `- session:` is this shift's own worker + (`slot_name`). Any other claim still holds.""" claims = origin_claims(mind, fetch=fetch) if claims is None: return records, {} @@ -1965,8 +1944,8 @@ def on_origin(records: list[dict], mind: Path, own: set[str], def _held_for(sections: dict[str, dict], task: str, repos, ignore=frozenset()) -> tuple[str, str] | None: """(repo as written, claiming slug) of the first claim on one of `repos` - that does not free it for `task` (R2: a coordination line frees a repo - only for the task it names), or None. A slug in `ignore` holds nothing.""" + that does not free it for `task` (a coordination line frees a repo only + for the task it names), or None. A slug in `ignore` holds nothing.""" mine = {_repo_key(x) for x in repos} return next(((repo, slug) for slug, sec in sections.items() if slug not in ignore and not coordinated_for(sec, task) @@ -1977,23 +1956,21 @@ def parked_elsewhere(slot: Path, inbox: dict | None = None, resumes: dict | None = None) -> 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. - - `inbox` is `questions.md` on Mind origin/main (`_questions.read_origin`, - M3.5 #645). Per task parked in shift `d`: every inbox entry for it from - `d` answered → released, and recorded in `resumes` (`{task: {shift, ids, - comments}}`); one dropped → held, shelved (Decision H9 a); one open or - deferred → held, waiting on it; none (a park from before M3.5), or an - unreadable inbox (None) → held as before (fail closed). + or blocked on a person past the grace — and that no later shift finished: + a prompt still in `draft/` with no claim must not be picked again. Read + from the slots' own `counters.json`: local files, no network. + + `inbox` is `questions.md` on Mind origin/main (`_questions.read_origin`). + Per task parked in shift `d`: every inbox entry for it from `d` answered → + released, and recorded in `resumes` (`{task: {shift, ids, comments}}`); + one dropped → held, shelved; one open or deferred → held, waiting on it; + none, or an unreadable inbox (None) → held (fail closed). A release is used up by the first later shift that picks the task: if that worker is still out at its review-at, crashes or is abandoned, the task is held again, never resumed twice on one claim. Only an answer given after that pick (a re-answer, or a new question answered) releases - it again; a brief that names it is the human's word, as before.""" + it again; a brief that names it is the human's word.""" out: dict[str, str] = {} released: dict[str, dict] = {} picked_in: dict[str, list[str]] = {} @@ -2058,7 +2035,7 @@ def park(task: str, why: str, d=d, held=held, freed=freed, touched=touched) -> N "not resumed again until a new answer (or name it in a " "brief)") except (AttributeError, TypeError, ValueError) as e: - # One malformed file holds nothing and releases nothing (#637 review). + # One malformed file holds nothing and releases nothing. print(f"orchestrator: {d.name}/{COUNTERS_FILE} has the wrong shape ({e}) — " "read as no hold", file=sys.stderr) continue @@ -2079,9 +2056,9 @@ def park(task: str, why: str, d=d, held=held, freed=freed, touched=touched) -> N def resume_records(records: list[dict], mind: Path, resumes: dict, ref: str = "origin/main") -> list[dict]: """`records` with each released task that a shift already claimed graded - from its `active/.md` on Mind origin/main (M3.5, #645): `survey` - reads only `draft/`, and the canonical checkout nobody pulls mid-shift may - still show the stale draft, which `on_origin` would drop. A task still in + from its `active/.md` on Mind origin/main: `survey` reads only + `draft/`, and the canonical checkout nobody pulls mid-shift may still + show the stale draft, which `on_origin` would drop. A task still in `draft/` on origin keeps its draft record. Each resume record carries `resume` (its ids) for the pick's `why:`. Local git only.""" import _batch # noqa: E402 — deferred, as in `_tick_body` @@ -2121,8 +2098,8 @@ def active_leases(slot: Path) -> dict[str, dict]: def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, tokens, health=None, pr_state=None, *, poster=None, shift=None, token_reserve=None, whoami=None, github=None, pr_files=None) -> dict: - """The tick under its lock, then the live status (PyAutoBrain#622): one - `claude agents` view and one set of `gh pr checks` reads serve both.""" + """The tick under its lock, then the live status: one `claude agents` view + and one set of `gh pr checks` reads serve both.""" shift = shift or {} agents = agents or AgentsView() health = _TickHealth(health) @@ -2135,8 +2112,8 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, if status: out["status"] = status if health.seen: - # Every CI verdict this tick read, for the event stream's `ci` line - # (#644): no read of its own — the close-outs made these. + # Every CI verdict this tick read, for the event stream's `ci` line: + # no read of its own — the close-outs made these. out["health"] = dict(health.seen) _note_auth_file(slot, now) return out @@ -2147,7 +2124,7 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, def _named_reasons(brief: dict, d: dict, planned: dict) -> dict[str, str]: - """{named task: why it did not start} for the digest (M3.6b): the plan's + """{named task: why it did not start} for the digest: the plan's rejection, or — for a named task neither picked, rejected, held by a claim nor parked — that it has no draft prompt to start.""" named = _brief.tasks_of(brief) @@ -2173,27 +2150,27 @@ 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) - # A task the human added by `/add` (#644) is graded from Mind - # origin/main when it is added: a prompt filed mid-shift is in no - # survey of the canonical checkout, which nobody pulls mid-shift. + # A task the human added by `/add` is graded from Mind origin/main + # when it is added: a prompt filed mid-shift is in no survey of the + # canonical checkout, which nobody pulls mid-shift. have = {r["path"] for r in recs} recs = recs + [a["record"] for a in (counters.get("added") or {}).values() if isinstance(a.get("record"), dict) and a["record"].get("path") not in have] surveyed = list(recs) - # 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. + # Parked on a question by an earlier shift: 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)} - # The inbox releases a hold once its questions are answered (M3.5, - # #645): read from Mind origin/main after the shift's one fetch. + # The inbox releases a hold once its questions are answered: read + # from Mind origin/main after the shift's one fetch. resumes: dict = {} 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). + # This shift's own parks an answer released with time left. here = released_here(slot, counters, inbox, now, review_at) resumes.update(here) _write_counters(slot, counters) @@ -2203,20 +2180,20 @@ def plan() -> dict: and Path(r["path"]).name not in named} recs = [r for r in recs if r["path"] not in planned["parked"]] # A task this shift picked is never resumed from an earlier park — - # except one this shift's own answer just released (M3.6c). + # except one this shift's own answer just released. 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. - # 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. + # pulls mid-shift: a draft another shift already claimed is never + # picked again, nor one whose repo a claim holds. A carried task + # 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] - # A pick whose worker has ended frees its library for a start - # (M3.6j, #683); its PR's merge waits in order at the close-out. + # A pick whose worker has ended frees its library for a start; + # its PR's merge waits in order at the close-out. freed = released_picks(counters, live=set(active_leases(slot))) - carried recs, claimed = on_origin(recs, mind, set(counters["picks"]) - carried, fetch=lambda: _fetch_once(mind, counters, now), @@ -2225,9 +2202,9 @@ def plan() -> dict: planned["resume"] = {t: v for t, v in resumes.items() if any(task_id(r["path"]) == t for r in recs)} # Unattended by construction: an absent Lane is excluded and an - # empty queue.md stops the backlog dip (M2.3, AUTONOMY.md "M2 - # rulings — 2026-11-12"). Recorded each tick so the digest can say so. - # Kept out above, with why: read only by the queued-epic lines (#696). + # empty queue.md stops the backlog dip (AUTONOMY.md "M2 rulings"). + # Recorded each tick so the digest can say so. Kept out above, with + # why: read only by the queued-epic lines. kept = {r["path"] for r in recs} why_out = {**planned["parked"], **(claimed or {})} withheld = [(r, why_out.get(r["path"], "kept out before planning " @@ -2243,20 +2220,20 @@ def known(task: str) -> bool: named = {task_id(p) for p in _brief.tasks_of(brief)} return task in named or task in {task_id(m["path"]) for m in plan()["members"]} - # The cloud sweep (M3.7e): one run-list read a tick, before steering, so a + # The cloud sweep: one run-list read a tick, before steering, so a # `/clear-sweep` this tick clears the red run this tick reads. if not _brief.is_shadow(brief): _sweep_read(slot, counters, now) - # The human steers from the shift issue (#622): read once, before anything - # this tick starts, so a /pause or /drop binds on the tick that reads it. + # The human steers from the shift issue: read once, before anything this + # tick starts, so a /pause or /drop binds on the tick that reads it. ctx = {"brief": brief, "now": now, "mind": mind, "review_at": _brief._iso((shift or {}).get("review_at") or "")} commands = _steer(slot, counters, shift or {}, now, github, whoami, known, ctx=ctx) _write_counters(slot, counters) if any(c["command"] in ("add", "cap") for c in commands): planned.clear() # an /add or /cap changes what this tick's plan admits - # `/cap` overrides and `/add`ed tasks (#644), from here on in this tick: - # every later reader (the spawn gates, the close-out gates) sees them. + # `/cap` overrides and `/add`ed tasks, from here on in this tick: every + # later reader (the spawn gates, the close-out gates) sees them. written = brief brief = _brief.effective(brief, counters) if (slot / STOP_FILE).exists(): @@ -2277,7 +2254,7 @@ def known(task: str) -> bool: 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) + carry_in(slot, counters, now) # the shift's first tick _write_counters(slot, counters) closeouts = _closeouts(slot, brief, counters, spawner, now, agents, health, pr_state, tokens=tokens, pr_files=pr_files, @@ -2302,12 +2279,12 @@ def known(task: str) -> bool: "parked": planned.get("parked") or {}, "resumed": planned.get("resume") or {}, "scoped_reach": sorted(d.get("scoped_reach") or []), - # M3.6b: why each named task did not start (the - # digest's "Not started" reason), and the backlog - # drafts kept out for want of a `Witness:`. + # Why each named task did not start (the digest's + # "Not started" reason), and the backlog drafts + # kept out for want of a `Witness:`. "named": _named_reasons(brief, d, planned), "witness_absent": sorted(d.get("witness_absent") or []), - # #696: one line per queued epic ledger. + # One line per queued epic ledger. "queued_epics": _batch.queued_epic_lines(d)} paused = bool(counters.get("paused")) if _brief.is_shadow(brief): @@ -2326,7 +2303,7 @@ def known(task: str) -> bool: # a `/cap tokens` lowered for this shift. counters["token_budget"] = written_budget # 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 + # usage passes it, so the budget binds on the first tick. A fake # (dry-shift) worker spends nothing. reserve = 0 if getattr(spawner, "real", False): @@ -2334,16 +2311,16 @@ def known(task: str) -> bool: else default_token_reserve(budget, max_sessions, worker_token_estimate(slot, counters, budget, mind)) spawned, refused = [], [] - # A re-dispatch goes first (#637, item 1): a backlog dip never takes the - # worker slot a killed task is waiting for. + # A re-dispatch goes first: 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"], - # `first: glance` (M3.6c): spawn order only — - # the plan's selection is unchanged. + # `first: glance`: 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". + # The CLI login: 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" @@ -2353,7 +2330,7 @@ def settled(task: str, member: dict) -> bool: return bool(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"]) - # What could still start on a later tick (M3.7c early close): a launch + # What could still start on a later tick (for the early close): a launch # that failed, a spend that could not be read, a login to renew. A task # held by a library, `max-workers` with nobody live, `max-sessions` or # the token budget cannot; neither can a parked or dropped one. @@ -2367,8 +2344,8 @@ def settled(task: str, member: dict) -> bool: released = member.get("resume") and task in (counters.get("inshift_pending") or {}) if settled(task, member): continue - # Never two workers on one library (M3.6j review F2): a live, parked - # or re-dispatch-pending task holds its library repos whatever the + # Never two workers on one library: a live, parked or + # re-dispatch-pending task holds its library repos whatever the # plan's rank order made of it this tick. holder = _library_holder(counters, live, task, member.get("repos") or []) if holder: @@ -2380,9 +2357,9 @@ def settled(task: str, member: dict) -> bool: refused.append({"task": task, "why": f"max-workers {max_workers} reached"}) final.add(task) continue - # 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. + # A re-dispatch may pass `max-sessions` by REDISPATCH_SESSIONS, so a + # killed worker is not left "awaiting re-dispatch" once early dips + # have used every session. redo = task in counters["pending_redispatch"] limit = max_sessions + (REDISPATCH_SESSIONS if redo else 0) if counters["sessions"] >= limit: @@ -2413,20 +2390,20 @@ def settled(task: str, member: dict) -> bool: "expires": _iso(now + _dt.timedelta(seconds=grace_s)), "pid": 0, "session_id": None, "worktree": None} if (shift or {}).get("issue"): - # Where a worker blocked past the grace is filed in the inbox (#645). + # Where a worker blocked past the grace is filed in the inbox. lease["shift_issue"] = shift["issue"] lease_path = slot / "leases" / f"{task}.json" if not _create_exclusive(lease_path, lease): continue # a lease appeared since we read them: never a second worker try: # Only a re-dispatch passes the flag, so a spawner without it - # (a test's) is called exactly as before. + # (a test's) is called without the keyword. again = {"redispatch": True} if task in counters["pending_redispatch"] else {} if member.get("resume"): - again["resume"] = member["resume"] # answered: RESUME_NOTE (#645) + again["resume"] = member["resume"] # answered: RESUME_NOTE siblings = sibling_prs(counters, member.get("repos") or []) if siblings: - again["siblings"] = siblings # open on its library (M3.6j) + again["siblings"] = siblings # open on its library lease.update(spawner.spawn(task, member["path"], slot / "leases", **again)) except Exception as e: # One task's failed launch is that task's refusal, not the tick's: @@ -2435,7 +2412,7 @@ def settled(task: str, member: dict) -> bool: refused.append({"task": task, "why": f"spawn failed: {str(e)[:300]}"}) startable.append(task) # One record per task however often the launch is retried: a - # failed launch is a crashed worker in the digest (#610). + # failed launch is a crashed worker in the digest. rec = worker_record(counters, f"launch-{task}", task, _iso(now)) rec["exits"] = ["launch-failed"] rec["attempts"] = int(rec.get("attempts") or 0) + 1 @@ -2476,7 +2453,7 @@ def settled(task: str, member: dict) -> bool: def _login_hold(counters: dict, spawner, members: list[dict], live: dict, now: _dt.datetime, probe=None) -> dict | None: - """The CLI login as this tick sees it (M3.6a, PyAutoBrain#659), or None. + """The CLI login as this tick sees it, or None. Probed (`claude auth status --json`, local, no model call) only for a real spawner, and only when a member is waiting to start while the last @@ -2515,20 +2492,20 @@ def _steered(out: dict, commands: list, paused: bool) -> dict: return out -# --- posting: marker before post, a failed post retried (#610, #611) ----------------- +# --- posting: marker before post, a failed post retried ------------------------------ #: Attempts per comment, the first included. Only a post `gh` says failed is #: retried; a timeout may have landed, so it never is. POST_TRIES = 3 -#: The one correction comment a late arrival may add after the digest (#610). +#: The one correction comment a late arrival may add after the digest. CORRECTION_MARKER = "correction.posted" CORRECTION_FILE = "correction.md" #: The watcher's own GitHub identity, for its own `gh` calls and nothing else -#: (then the human's account is the one an @mention notifies, #611 review): -#: its minimal GitHub App (`PYAUTO_SHIFT_APP_*`, PyAutoBrain#630), else this -#: static token as the fallback, else `gh`'s own auth. See `_app_token`. +#: (so the human's account is the one an @mention notifies): its minimal +#: GitHub App (`PYAUTO_SHIFT_APP_*`), else this static token as the fallback, +#: else `gh`'s own auth. See `_app_token`. GH_TOKEN_ENV = _app_token.GH_TOKEN_ENV #: The identity bound for the current tick (`tick`); outside one, a fresh one. _AUTH = None @@ -2648,7 +2625,7 @@ def post_once(marker: Path, issue: str, body_file: Path, poster, now: _dt.dateti def post_due(marker: Path) -> bool: """Whether a marker's post failed outright and has tries left. A marker - written before retries existed (no `state`) is never retried.""" + with no `state` is never retried.""" try: rec = json.loads(Path(marker).read_text()) except (OSError, ValueError): @@ -2710,11 +2687,11 @@ def _retry_mentions(slot: Path, counters: dict, poster, now: _dt.datetime) -> li return out -# --- the live shift view you can steer (PyAutoBrain#622) ---------------------------- +# --- the live shift view you can steer ---------------------------------------------- #: The one live status comment of a shift: claimed by this marker before its -#: create, then only edited — never a second (AUTONOMY.md watcher network -#: surface, amendment 2026-11-13). +#: create, then only edited — never a second (AUTONOMY.md "The watcher's +#: network surface"). STATUS_MARKER = "status.json" STATUS_FILE = "status.md" #: An unchanged status is re-edited this often (time left, tokens); any change @@ -2727,19 +2704,17 @@ def _retry_mentions(slot: Path, counters: dict, poster, now: _dt.datetime) -> li #: The dashboard's copy of the status: one `- live:` line in the brief record, #: rewritten through the one Mind writer when the shift's state changes. LIVE_KEY_FILE = "live.key" -#: The steering commands, read from the human's comments on the shift issue -#: (#622; `/add`, `/cap` and `/kill` from #644; `/clear-sweep` from M3.7e, #692). +#: The steering commands, read from the human's comments on the shift issue. COMMANDS = ("pause", "resume", "drop", "stop", "add", "cap", "kill", "clear-sweep") _COMMAND_RE = re.compile( r"^/(pause|resume|drop|stop|add|cap|kill|clear-sweep)\b[ \t]*(\S+)?(?:[ \t]+(\S+))?[ \t]*$") #: The one verb that takes two arguments (`/cap `). _TWO_ARGS = ("cap",) _TASK_ARG_RE = re.compile(r"^[A-Za-z0-9_./-]+$") -#: `/add` is refused this close to `review-at:` — a worker needs longer -#: (human ruling H8, 2026-11-16). +#: `/add` is refused this close to `review-at:` — a worker needs longer. ADD_CUTOFF_S = 1800 -#: `/cap ` → the brief key it lowers (human ruling H6: never above the -#: brief's own value). +#: `/cap ` → the brief key it lowers (never above the brief's own +#: value). CAP_KEYS = {"merges": "merge-cap", "workers": "max-workers", "sessions": "max-sessions", "tokens": "token-budget"} #: `/kill`'s one local act, `claude stop ` — not a network call. @@ -2835,7 +2810,7 @@ def _parse_command(body: str) -> tuple[str, str] | None: """(command, argument) when a comment's first non-empty line is a steering command and nothing else; None otherwise. `/cap`'s two arguments come back as one, space-separated; every other verb takes one - at most, as before #644.""" + at most.""" first = next((ln.strip() for ln in (body or "").splitlines() if ln.strip()), "") m = _COMMAND_RE.match(first) if not m: @@ -2977,7 +2952,7 @@ def _steer(slot: Path, counters: dict, shift: dict, now: _dt.datetime, github=No return out -# --- `/cap`, `/add`, `/kill` (#644; human rulings H5, H6, H8 of 2026-11-16) ------------- +# --- `/cap`, `/add`, `/kill` ---------------------------------------------------------- def _cap_ceiling(brief: dict, key: str) -> int | None: """A cap as `brief` states it: the spawn caps with their defaults, the @@ -3021,8 +2996,8 @@ def _cmd_cap(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict) of = f"{ceiling}" if ceiling is not None else "none" if key == "merge-cap": # Every slot taken this shift — in-turn merges, close-outs merged and - # close-outs still running alike (R3, #661). - # An in-turn merge made with no slot is counted too (#661 review). + # close-outs still running alike. An in-turn merge made with no slot + # is counted too. try: taken = _merge_slots.used(slot) unslotted = len(_digest.no_slot_merges( @@ -3100,7 +3075,7 @@ def _cmd_add(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict) """`/add `: make a draft a brief-named task for the rest of this shift. The planner's own gates judge it as they judge a named task; it overrides the brief's `exclude:` and an earlier shift's parked hold (the - human's newer word), never the organ rule (human ruling H8).""" + human's newer word), never the organ rule.""" if not arg or not _TASK_ARG_RE.match(arg): return "ignored: /add needs a prompt (draft/…/x.md, x.md or x)" now, review_at = ctx.get("now") or _now(), ctx.get("review_at") @@ -3112,8 +3087,8 @@ def _cmd_add(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict) return "refused: shadow shift: nothing is dispatched." mind = Path(ctx["mind"]) try: - # One fetch per `/add` (AUTONOMY.md amendment 2026-11-16, #644): a - # prompt filed mid-shift is newer than the once-per-shift fetch. + # One fetch per `/add` (AUTONOMY.md "The watcher's network surface"): + # a prompt filed mid-shift is newer than the once-per-shift fetch. _mind_writer.fetch(mind) except _mind_writer.MindWriteError as e: counters.setdefault("add_fetch_errors", []).append(str(e)[:200]) @@ -3147,7 +3122,7 @@ def _cmd_add(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict) kept, claimed = on_origin([rec], mind, set()) if not kept: return f"refused: {task}: {claimed.get(rel) or 'claimed on Mind origin/main'}" - # The inbox's word on earlier parks (#645): an answered park is not "was parked". + # The inbox's word on earlier parks: an answered park is not "was parked". was_parked = task in parked_elsewhere(slot, _questions.read_origin(mind)) counters.setdefault("added", {})[task] = {"prompt": rel, "by": who, "at": at, "record": rec} notes = "".join([" (was excluded in the brief)" if excluded else "", @@ -3176,10 +3151,10 @@ def claude_stop(agent_id: str, run=None) -> tuple[bool, str]: def _cmd_kill(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict) -> str: - """`/kill ` (human ruling H5): stop that task's running worker with - `claude stop`. The next reap sees it ended: it is `killed` (not a crash) - and re-dispatched once by the usual rule, unless the task was dropped. - A close-out is not killable here.""" + """`/kill `: stop that task's running worker with `claude stop`. The + next reap sees it ended: it is `killed` (not a crash) and re-dispatched + once by the usual rule, unless the task was dropped. A close-out is not + killable here.""" if not arg or not _TASK_ARG_RE.match(arg): return "ignored: /kill needs a task name" task = Path(arg).stem @@ -3212,7 +3187,7 @@ def _cmd_kill(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict return f"stopping {task}'s worker {key} (claude stop). {tail}" -# --- the shift-end cloud sweep (M3.7e, PyAutoBrain#692; ruling S4) ------------------- +# --- the shift-end cloud sweep -------------------------------------------------------- def _sweep_cfg() -> dict: """The sweep's repo and workflow (`config/policy.yaml` `shift_watcher:` @@ -3278,13 +3253,12 @@ def _shift_merges(counters: dict, start: _dt.datetime | None) -> list[str]: def _sweep_dispatch(slot: Path, counters: dict, now: _dt.datetime, start: _dt.datetime | None = None) -> bool: - """The one `gh workflow run` of the sweep per shift (S4), under the - human's own `gh` login (decision b): at the close, or from the late sweep - when a close-out merged after it — only when GitHub confirmed at least - one merge on a repo the sweep covers. `sweep.dispatched` is claimed - exclusively first, so a shift never dispatches twice; a failed dispatch - is recorded for the digest and never retried. True when this call - dispatched (or tried to).""" + """The one `gh workflow run` of the sweep per shift, under the human's own + `gh` login: at the close, or from the late sweep when a close-out merged + after it — only when GitHub confirmed at least one merge on a repo the + sweep covers. `sweep.dispatched` is claimed exclusively first, so a shift + never dispatches twice; a failed dispatch is recorded for the digest and + never retried. True when this call dispatched (or tried to).""" cfg = _sweep_cfg() if not cfg or (slot / _sweep.DISPATCH_MARKER).exists(): return False @@ -3353,7 +3327,7 @@ def _sweep_red_markers(slot: Path, counters: dict) -> None: if co.get("task"): tasks.setdefault(co["task"], []).append(pr) # A marker the current block does not cover goes: no block at all, or a - # newer block on other repos (review round 1). + # newer block on other repos. for marker in (slot / "leases").glob(f"*{_sweep.SWEEP_RED_SUFFIX}"): task = marker.name[:-len(_sweep.SWEEP_RED_SUFFIX)] if not blk or not any(_sweep_blocks(blk, pr) for pr in tasks.get(task, [])): @@ -3383,10 +3357,10 @@ def _cmd_clear_sweep(slot: Path, counters: dict, arg: str, who: str, at: str, return _sweep.clear(slot.parent, who, at) -# --- the event stream's watcher side (#644) -------------------------------------------- +# --- the event stream's watcher side --------------------------------------------------- -#: Needs-you event comments a shift may post (human ruling H4b), then one -#: last one saying the rest are in the status comment. +#: Needs-you event comments a shift may post, then one last one saying the +#: rest are in the status comment. EVENT_COMMENTS_MAX = 5 EVENT_OVERFLOW = "event.overflow" @@ -3448,11 +3422,11 @@ def event_comment_body(slot_name: str, event: dict) -> str: def _event_comments(slot: Path, events: list[dict], issue: str, poster, now: _dt.datetime) -> list[dict]: - """One comment per needs-you event on the shift issue (human ruling H4b), - at most `EVENT_COMMENTS_MAX` a shift and then one overflow comment, each - claimed by its marker before the post (`mentions/event.`); a post - `gh` said failed is retried with the mentions. Each counts in - `event_comments`, apart from the per-worker `pushes`.""" + """One comment per needs-you event on the shift issue, at most + `EVENT_COMMENTS_MAX` a shift and then one overflow comment, each claimed + by its marker before the post (`mentions/event.`); a post `gh` said + failed is retried with the mentions. Each counts in `event_comments`, + apart from the per-worker `pushes`.""" todo = [e for e in events if e.get("needs_you")] if not todo or not issue.startswith("http") or (slot / STOP_FILE).exists(): return [] @@ -3559,7 +3533,7 @@ def _live_status(slot: Path, mind: Path, shift: dict, now: _dt.datetime, agents, """The end of every open tick: the status comment (create once, then edit) and the dashboard's `- live:` line. Built from the same snapshot as `batch watch`, from what this tick already read — no network read of its - own (the work-issue links are a local git read of Mind, #634). + own (the work-issue links are a local git read of Mind). On the `/stop` tick only the status write runs, as the acknowledgement: nothing is queued or committed to Mind, exactly as under `STOP`.""" brief_path = shift.get("brief_path") @@ -3594,7 +3568,7 @@ def _live_status(slot: Path, mind: Path, shift: dict, now: _dt.datetime, agents, return out or None -# --- the digest (phase 3d) ---------------------------------------------------------- +# --- the digest --------------------------------------------------------------------- def _record_rel(brief_path: Path, mind: Path) -> str | None: """The record's path inside Mind, for the one-Mind-writer append; None when @@ -3624,20 +3598,19 @@ def late_sweep(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, grace_s: float = LEASE_GRACE_S, agents=None, tokens=transcript_usage, poster=None, pr_state=None) -> dict: """A closed shift whose digest is posted, with a worker still out, Mind - ops still queued (PyAutoBrain#594: a worker finished 12 minutes after - `review-at:` and its `.done` and ledger ops were stranded) or a failed - post due its retry. + ops still queued or a failed post due its retry: a `.done` or a ledger op + that arrives after `review-at:` must not be stranded. Reaps as a live tick does and commits the queued ops through the one Mind writer, then names each late arrival in the record under `### Late arrivals`, amends the shift's pilot row in place (`amended: true`) and - posts one correction comment for the shift (#610). Never a spawn, a - re-dispatch or a close-out: the grant ended at `review-at:`, so what - arrives late waits for `/prm`. + posts one correction comment for the shift. Never a spawn, a re-dispatch + or a close-out: the grant ended at `review-at:`, so what arrives late + waits for `/prm`. - A close-out still out at `review-at:` is reaped here too (#632, F1): its - merge is counted, its stage-2 row queued and the pilot row amended, and - the sweep runs while one is out.""" + A close-out still out at `review-at:` is reaped here too: its merge is + counted, its stage-2 row queued and the pilot row amended, and the sweep + runs while one is out.""" counters = read_counters(slot) counters["usage_unavailable"] = [] agents = agents or AgentsView() @@ -3684,7 +3657,7 @@ def late_sweep(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, lines.append(f"- late: {co['task']} — {what} (after review-at, {_iso(now)})") counters["late"].append(co["task"]) # A close-out that merged after the close, with no sweep dispatched yet: - # the shift's one dispatch is made here (M3.7e review round 1). + # the shift's one dispatch is made here. if not _brief.is_shadow(brief) and _sweep_dispatch( slot, counters, now, _brief._iso((top.get("dispatched") or {}).get("value", ""))): disp = counters.get("sweep_dispatch") or {} @@ -3741,31 +3714,30 @@ def late_sweep(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, return out -# --- early close (M3.7c, PyAutoBrain#690) ----------------------------------------- +# --- early close ------------------------------------------------------------------- def early_close_ready(slot: Path, counters: dict, result: dict) -> bool: """Whether a live tick leaves the shift with nothing to do before - `review-at:` (M3.7c, decisions 2 and 3). All must hold: the tick ran - (not shadow, not stopped) and the shift is not paused; nothing this - tick read failed (the steering comments, Mind origin/main); the shift has - started something (a worker or a carried PR), so a plan that could not be - read never closes it; no worker holds a lease (a parked one does not - count); no pick could still start (`startable`: a failed launch, an - unreadable spend, an expired login, a re-dispatch no cap refused); no - close-out or branch update is running or waiting on the updated head's - CI; and every open PR of the shift is judged — refused, merged, or - waiting in merge order behind an earlier PR (a wait behind a /prm-bound - PR does not hold the shift open).""" + `review-at:`. All must hold: the tick ran (not shadow, not stopped) and + the shift is not paused; nothing this tick read failed (the steering + comments, Mind origin/main); the shift has started something (a worker or + a carried PR), so a plan that could not be read never closes it; no + worker holds a lease (a parked one does not count); no pick could still + start (`startable`: a failed launch, an unreadable spend, an expired + login, a re-dispatch no cap refused); no close-out or branch update is + running or waiting on the updated head's CI; and every open PR of the + shift is judged — refused, merged, or waiting in merge order behind an + earlier PR (a wait behind a /prm-bound PR does not hold the shift open).""" if result.get("action") != "ticked" or result.get("paused") or counters.get("paused"): return False if result.get("spawned") or result.get("startable"): return False - # Review round 1, finding 1: an input this tick could not read is never - # "nothing to do" — an unread `/add` or `/resume` on the shift issue, or - # drafts the plan dropped because Mind origin/main failed closed. + # An input this tick could not read is never "nothing to do" — an unread + # `/add` or `/resume` on the shift issue, or drafts the plan dropped + # because Mind origin/main failed closed. if counters.get("commands_unread"): return False - # The sweep's run list unreadable (M3.7e review round 2): an unread input. + # The sweep's run list unreadable: an unread input. if (((counters.get("sweep") or {}).get("block") or {}).get("kind") == "unknown" or counters.get("sweep_waits")): return False @@ -3794,8 +3766,8 @@ def early_close_ready(slot: Path, counters: dict, result: dict) -> bool: def close_early(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, shift: dict, *, poster=None, health=None, agents=None, tokens=transcript_usage, grace_s: float = LEASE_GRACE_S, github=None, pr_state=None) -> dict: - """Close the shift on this tick (M3.7c): record when, then the digest as - at `review-at:`, with this tick's time as the shift's end — merges are + """Close the shift on this tick: record when, then the digest as at + `review-at:`, with this tick's time as the shift's end — merges are counted up to it. Called inside the tick lock.""" counters = read_counters(slot) counters["closed_early"] = _iso(now) @@ -3833,8 +3805,8 @@ def _after_early_close(brief_path: Path, mind: Path, slot: Path, now: _dt.dateti def _github_merges(counters: dict, review_at, pr_state) -> None: """GitHub's merge state for every PR the shift's workers named, read once - at `review-at:` — `in_window` when merged at or before it (#610). A PR - GitHub cannot say about is left to what the watcher recorded.""" + at `review-at:` — `in_window` when merged at or before it. A PR GitHub + cannot say about is left to what the watcher recorded.""" for o in counters["outcomes"].values(): for url in o.get("prs") or []: if "/pull/" not in url: @@ -3857,12 +3829,12 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, closed_at: _dt.datetime | None = None) -> dict: """Reap, then write the digest into the record and post it on the brief's issue. - `closed_at` is an early close's time (M3.7c): the shift's end in place of + `closed_at` is an early close's time: the shift's end in place of `review-at:`, so merges are counted up to it. - Reaping first (#610) puts a `.done` written after the last live tick into - the digest. The marker is created **before** the post, exclusively: a - crash between the two leaves a shift with no comment, never one with two + Reaping first puts a `.done` written after the last live tick into the + digest. The marker is created **before** the post, exclusively: a crash + between the two leaves a shift with no comment, never one with two (AUTONOMY.md "The watcher's network surface"); a post `gh` said failed is retried by the late sweep, up to `POST_TRIES`. Nothing is read back from GitHub to check. @@ -3878,15 +3850,15 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, counters["usage_unavailable"] = [] agents = agents or AgentsView() # one `claude agents` read serves the closing status _reap(slot, counters, now, grace_s, agents, tokens) - # A close-out that ended since the last tick lands in this digest (#632, - # F1); one still out is reaped by the late sweep. + # A close-out that ended since the last tick lands in this digest; one + # still out is reaped by the late sweep. reap_closeouts(slot, counters, now, agents, pr_state, tokens) counters["pending_redispatch"] = [] # the grant has ended: never re-dispatched if not _brief.is_shadow(brief): _github_merges(counters, closed_at or _brief._iso( (top.get("review-at") or {}).get("value", "")), pr_state) - # S4 (M3.7e): the one sweep dispatch, after the last merge and before - # the digest; then this tick's one read of the sweep, if not made yet. + # The one sweep dispatch, after the last merge and before the digest; + # then this tick's one read of the sweep, if not made yet. _sweep_dispatch(slot, counters, now, _brief._iso((top.get("dispatched") or {}).get("value", ""))) _sweep_tick(slot, counters, now) @@ -3896,11 +3868,11 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, # is named in the digest itself, which still reaches the record. _auth().failed() _note_auth(counters, now) - # The readiness pass (M3.3, PyAutoBrain#671): every gate on the next - # shift's queue becomes a ruling, queued for this shift's one Mind writer. + # The readiness pass: every gate on the next shift's queue becomes a + # ruling, queued for this shift's one Mind writer. readiness_pass(slot, counters, mind, now) # Everything the Mind writer reported so far is in this digest; what it - # reports from here on reaches the human through the late sweep (#632). + # reports from here on reaches the human through the late sweep. counters["ledger_reported"] = len(_mind_writer.report(slot)) _write_counters(slot, counters) digest = _digest.build(_brief.effective(brief, counters), slot, counters, health=health, @@ -3912,11 +3884,11 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, if rel is not None: _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, {"op": "append", "path": rel, "text": "\n" + digest}) - # The pilot ledger (phase 4a; jsonl #610): one row per shift, in the - # same commit, upserted by slot so a rerun never writes a second. + # The pilot ledger: one row per shift, in the same commit, upserted by + # slot so a rerun never writes a second. _queue_pilot(slot, brief, counters, amended=False) if (slot / LIVE_KEY_FILE).exists(): - # The dashboard's live line ends with the shift (#622). + # The dashboard's live line ends with the shift. _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, { "op": "record-key", "path": rel, "key": "live", "value": (f"closed early at {_iso(closed_at)}" if closed_at @@ -3944,12 +3916,12 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, def readiness_pass(slot: Path, counters: dict, mind: Path, now: _dt.datetime) -> None: - """Run `batch ready` at shift end (M3.3, PyAutoBrain#671): offline (the - premise check never fetches, no gh), against the watcher's Mind, each new - ruling queued as a `question-add` op in this shift's own ledger and noted - in `counters["rulings"]`. A shadow shift runs it too: its digest is - written through the same writer. A failure never breaks the close: its - reason is recorded and the digest says so.""" + """Run `batch ready` at shift end: offline (the premise check never + fetches, no gh), against the watcher's Mind, each new ruling queued as a + `question-add` op in this shift's own ledger and noted in + `counters["rulings"]`. A shadow shift runs it too: its digest is written + through the same writer. A failure never breaks the close: its reason is + recorded and the digest says so.""" try: import _ready # noqa: E402 — inside the try: an import failure is a failed pass res = _ready.run(mind, fetch=False, shift=Path(slot).name, now=now) @@ -3963,7 +3935,7 @@ def readiness_pass(slot: Path, counters: dict, mind: Path, now: _dt.datetime) -> def _close_status(brief_path: Path, slot: Path, issue: str, now: _dt.datetime, agents, github=None, *, mind=None) -> dict | None: """One last edit of the status comment at `review-at:`, saying the shift - is closed (#622); never retried — the digest is the record from here.""" + is closed; never retried — the digest is the record from here.""" rec = _read_json(slot / STATUS_MARKER) if not rec or rec.get("state") != "posted": return None @@ -3990,20 +3962,20 @@ def _write_packet(slot: Path, digest: str) -> Path: return out -# --- unattended `glance` close-out (phase 4b) ------------------------------------ +# --- unattended `glance` close-out ------------------------------------------------ -#: No close-out starts this close to `review-at:` (PyAutoBrain#632, F1): one -#: that ran past it merged outside the digest. The PR waits for `/prm`. +#: No close-out starts this close to `review-at:`: one that ran past it +#: would merge outside the digest. The PR waits for `/prm`. CLOSEOUT_CUTOFF_S = 1200 #: No close-out starts once the shift's spend reaches this multiple of its -#: `token-budget:` (AUTONOMY.md, ruling 2026-11-14, #632 F5). Below it a -#: close-out may pass the budget: it counts against it and the digest shows it. +#: `token-budget:` (AUTONOMY.md). Below it a close-out may pass the budget: +#: it counts against it and the digest shows it. CLOSEOUT_BUDGET_FACTOR = 1.5 def ledger_unreported(slot: Path) -> list[dict]: """What the Mind writer reported (set aside, conflict, held) after the - digest was built — the late sweep's to tell the human (#632 review).""" + digest was built — the late sweep's to tell the human.""" if not (slot / COUNTERS_FILE).exists(): return [] done = int(read_counters(slot).get("ledger_reported") or 0) @@ -4025,16 +3997,16 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti The watcher's guards are the ones it can judge from its own reads (AUTONOMY "Unattended `glance` merges"): the recorded tier, CI by `gh pr checks` not - red — running or green starts the close-out at PR-open (ruling S5, - M3.7b), which waits in-turn for a green `ci-verdict`; none at all is - refused after a grace (PyAutoHeart#343) — a free slot under the brief's - `merge-cap:`, and never in a shadow shift. The label, Heart, the witness, - the CI wait and the merge slot's take are the close-out session's — it is - the independent session, and it refuses rather than merges when one fails. - - GitHub is the merge truth (#603): before a finished close-out is counted - merged or refused — which frees its `merge-cap:` slot — the PR's state is - read (`pr_state`, else the spawner's, `gh pr view`). Only a GitHub MERGED + red — running or green starts the close-out at PR-open, which waits + in-turn for a green `ci-verdict`; none at all is refused after a grace — + a free slot under the brief's `merge-cap:`, and never in a shadow shift. + The label, Heart, the witness, the CI wait and the merge slot's take are + the close-out session's — it is the independent session, and it refuses + rather than merges when one fails. + + GitHub is the merge truth: before a finished close-out is counted merged + or refused — which frees its `merge-cap:` slot — the PR's state is read + (`pr_state`, else the spawner's, `gh pr view`). Only a GitHub MERGED counts: with a `merged` verdict or no file at all. A `merged` verdict on a PR still OPEN holds its slot and is asked again each tick; one GitHub shows CLOSED is refused. A non-merged verdict on a PR GitHub shows MERGED was @@ -4043,17 +4015,17 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti Every transition is written as it happens; a `.closeout` file is deleted only after that write. - Two more refusals (#632): no close-out starts within `CLOSEOUT_CUTOFF_S` - of `review-at:`, nor once the spend reaches `CLOSEOUT_BUDGET_FACTOR` × the + Two more refusals: no close-out starts within `CLOSEOUT_CUTOFF_S` of + `review-at:`, nor once the spend reaches `CLOSEOUT_BUDGET_FACTOR` × the `token-budget:`. """ pr_state = pr_state or getattr(spawner, "pr_state", None) pr_files = pr_files or getattr(spawner, "pr_files", None) events = reap_closeouts(slot, counters, now, agents, pr_state, tokens) events.setdefault("started", []) - # The cap every in-shift merge takes a slot against, worker or close-out - # (ruling R3, #661). A shadow or paused shift publishes a pause: a - # worker's take is refused and the PR waits for /prm. + # The cap every in-shift merge takes a slot against, worker or + # close-out. A shadow or paused shift publishes a pause: a worker's take + # is refused and the PR waits for /prm. try: _merge_slots.publish(slot, _brief._nonneg_int(brief.get("merge-cap", {}).get("value", "")) or 0, _brief.is_shadow(brief) or bool(counters.get("paused"))) @@ -4064,7 +4036,7 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti events["slots_error"] = str(e)[:300] # a take reads what is there, or cannot tell _sweep_red_markers(slot, counters) if _brief.is_shadow(brief) or counters.get("paused"): - return events # paused (#622): an open PR waits; it is not refused + return events # paused: an open PR waits; it is not refused return _start_closeouts(slot, brief, counters, spawner, now, health, events, review_at, pr_state=pr_state, pr_files=pr_files) @@ -4072,9 +4044,8 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti 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), as did an in-turn merge (#637). None when the pick - recorded no prompt.""" + what `lifecycle.py close` does, and neither an unattended close-out nor + an in-turn merge runs. None when the pick recorded no prompt.""" prompt = (counters.get("picks", {}).get(task) or {}).get("prompt") or "" if not prompt: return None @@ -4097,7 +4068,7 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta """Reap every finished close-out session (the first half of `_closeouts`): a live tick, `finish_shift` at `review-at:` and the late sweep all call it, so a close-out that ends after `review-at:` still lands its merge count and - stage-2 row (#632, F1). `late` marks the events as after `review-at:`.""" + stage-2 row. `late` marks the events as after `review-at:`.""" events = {"merged": [], "refused": []} lease_dir = slot / "leases" agents = agents or AgentsView() @@ -4107,7 +4078,7 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta if co["state"] != "running": continue if co.get("agent_id"): - # A close-out session spends tokens too: read every tick (#610). + # A close-out session spends tokens too: read every tick. if known is None: known = _liveness_known(agents) sid = (agents.session_of(co["agent_id"]) if known else None) or co.get("session_id") @@ -4145,10 +4116,10 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta merged = gh_state == "MERGED" if gh else said_merged result = (verdict or {}).get("result") if result in ORDER_STATES and not merged: - # A branch-update session's word (M3.6j, #683): the branch now has - # main in it (`updated`) or already had (`current`). Neither is a - # merge nor a refusal: the slot stays held, and a later tick - # starts the merge close-out once CI on the new head is not red (S5). + # A branch-update session's word: the branch now has main in it + # (`updated`) or already had (`current`). Neither is a merge nor + # a refusal: the slot stays held, and a later tick starts the + # merge close-out once CI on the new head is not red. co.update(state=result, updated=_iso(now)) if result == "updated": co.update(head=str(verdict.get("head") or "")[:64], @@ -4165,8 +4136,8 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta _write_counters(slot, counters) continue # e.g. `--auto` pending: not counted, the cap slot stays held if merged and co["task"] in counters["dropped"]: - # Dropped by the human (#622): a merge that landed anyway is never - # an unattended merge — no count, no stage-2 row. + # Dropped by the human: a merge that landed anyway is never an + # unattended merge — no count, no stage-2 row. co.update(state="refused", why="merged outside the close-out after /drop " f"(mergedBy={(gh or {}).get('mergedBy') or '?'})") @@ -4190,8 +4161,8 @@ 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. + # What became of the task's worktree and local branch: 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 out = counters["outcomes"].setdefault(co["task"], {"prs": [pr], "merged": []}) @@ -4200,24 +4171,24 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta tier = co.get("tier") or counters["picks"].get(co["task"], {}).get("tier", "?") if tier == "glance": # Only a `glance` close-out is a stage-2 row and an unattended - # `glance` merge; a `notify` one (ruling R3, #661) is neither. + # `glance` merge; a `notify` one is neither. counters["glance_auto_merges"] += 1 _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, { "op": "table-append", "path": STAGE2_LOG, "heading": STAGE2_HEADING, # One row per PR and shift, even if a crash between this queue - # and the counters write below reaps the close-out twice (#632). + # and the counters write below reaps the close-out twice. "unique": f"| {co['task']} ({pr}) | {slot.name} |", "row": stage2_row(now, co["task"], pr, slot.name, co["gate"], co["model"], merged_by=(gh or {}).get("mergedBy") or "")}) retire = queue_retire_op(counters, co["task"], pr, now) if retire: # The close-out queues this with its complete record; this is - # the safety net when it did not (#634). A second retire of - # the same entry finds none live and is silent. + # the safety net when it did not. A second retire of the same + # entry finds none live and is silent. _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, retire) # An unattended close-out never runs `lifecycle.py close`, so # the task's Open questions (a `blocked` one whose late `.done` - # merged) are answered here, or `check` would drift (#645). + # merged) are answered here, or `check` would drift. _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, question_retire_op(counters, co["task"], now)) events["merged"].append(pr) @@ -4233,11 +4204,11 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta co.update(state="refused", why=why) events["refused"].append(pr) if co["state"] == "refused": - # A refused close-out frees its PR's merge slot (R3, #661) whoever - # holds it for this task: the watcher (taken before a branch - # update) or the close-out session itself (its own `merge-slot - # take` just before the merge, M3.7b decision A). A merge made - # outside the close-out is not the shift's. A merged one keeps it. + # A refused close-out frees its PR's merge slot whoever holds it + # for this task: the watcher (taken before a branch update) or + # the close-out session itself (its own `merge-slot take` just + # before the merge). A merge made outside the close-out is not + # the shift's. A merged one keeps it. for by, of_task in ((_merge_slots.WATCHER, None), (_merge_slots.SESSION, co["task"])): try: @@ -4256,14 +4227,14 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta #: How long an `updated` PR (its branch just merged `main` in) may read #: NO-CHECKS before that is its CI verdict: room for CI to register on the new -#: head (M3.6j, PyAutoBrain#683). +#: head. UPDATE_CHECKS_GRACE_S = 600 #: Branch updates one PR may have in a shift; the next one it would need -#: refuses it, `main kept moving → your /prm` (M3.6j). +#: refuses it, `main kept moving → your /prm`. UPDATE_LIMIT = 2 -#: Close-out states the watcher looks at again on later ticks (M3.6j): the -#: branch was brought up to date with `main` (or already was), its slot is -#: held, and its merge close-out has not started yet. +#: Close-out states the watcher looks at again on later ticks: the branch +#: was brought up to date with `main` (or already was), its slot is held, +#: and its merge close-out has not started yet. ORDER_STATES = ("updated", "current") @@ -4275,8 +4246,8 @@ def _iso_or_none(text: str) -> _dt.datetime | None: def _known_prs(counters: dict) -> dict[str, str]: - """{canonical PR key: URL} for every PR this shift knows (ruling f): its - outcomes' PRs, carried ones included, and a carried outcome's `behind`.""" + """{canonical PR key: URL} for every PR this shift knows: its outcomes' + PRs, carried ones included, and a carried outcome's `behind`.""" out: dict[str, str] = {} for o in (counters.get("outcomes") or {}).values(): if not isinstance(o, dict): @@ -4290,7 +4261,7 @@ def _known_prs(counters: dict) -> dict[str, str]: def _earlier_prs(counters: dict, pr: str) -> list[str]: """This shift's known PRs that merge before `pr`, in PR order: the same - GitHub repo, a lower number, and only on a library repo (ruling f).""" + GitHub repo, a lower number, and only on a library repo.""" key = _merge_slots.pr_key(pr) if not key or not _library_key(pr): return [] @@ -4310,11 +4281,10 @@ def _recorded_merged(counters: dict) -> set[str]: def _merge_blockers(counters: dict, pr: str, pr_state, cache: dict) -> list[str]: - """The earlier PRs (`_earlier_prs`) `pr` must wait behind (M3.6j, - PyAutoBrain#683): every one not recorded merged and not MERGED or CLOSED - on GitHub, whatever this shift made of it — refused, dropped, red - (ruling c). One GitHub read per PR per tick (`cache`, ruling b); a PR - GitHub cannot say about blocks.""" + """The earlier PRs (`_earlier_prs`) `pr` must wait behind: every one not + recorded merged and not MERGED or CLOSED on GitHub, whatever this shift + made of it — refused, dropped, red. One GitHub read per PR per tick + (`cache`); a PR GitHub cannot say about blocks.""" merged = _recorded_merged(counters) out = [] for u in _earlier_prs(counters, pr): @@ -4323,8 +4293,7 @@ def _merge_blockers(counters: dict, pr: str, pr_state, cache: dict) -> list[str] gh = _gh_once(pr_state, cache, u) if (gh or {}).get("state") in ("MERGED", "CLOSED"): # Remembered for the digest's merge order: an earlier PR the - # human merged or closed is no longer one to merge first - # (2026-11-19-pm2 listed one as "open" twenty minutes after its merge). + # human merged or closed is no longer one to merge first. counters.setdefault("pr_gone", {})[u] = gh["state"] continue out.append(u) @@ -4333,11 +4302,11 @@ def _merge_blockers(counters: dict, pr: str, pr_state, cache: dict) -> list[str] def in_turn_merge_blockers(slot: Path, pr: str, pr_state=None) -> list[str]: """The earlier PRs of this shift a worker's in-turn merge of `pr` would - jump (M3.6j review F1): the same rule as the close-out's wait - (`_merge_blockers`), read from the slot's `counters.json`. `merge-slot - take` refuses while any is open, so the PR ends at PR-open and the - watcher's close-out merges it in order. A missing counters file (no shift - state yet) blocks nothing; an unreadable one raises `OSError`/`ValueError`.""" + jump: the same rule as the close-out's wait (`_merge_blockers`), read from + the slot's `counters.json`. `merge-slot take` refuses while any is open, + so the PR ends at PR-open and the watcher's close-out merges it in order. + A missing counters file (no shift state yet) blocks nothing; an + unreadable one raises `OSError`/`ValueError`.""" path = Path(slot) / COUNTERS_FILE if not path.exists(): return [] @@ -4361,8 +4330,8 @@ def _gh_once(pr_state, cache: dict, url: str) -> dict | None: def _merged_after_start(counters: dict, task: str, pr: str, pr_state, cache: dict, carried: bool) -> list[str]: - """The earlier PRs that merged after `task`'s first worker started (M3.6j): - its branch was cut from a `main` without them, so it is updated before it + """The earlier PRs that merged after `task`'s first worker started: its + branch was cut from a `main` without them, so it is updated before it merges. A carried PR's every merged earlier PR counts; so does one whose merge time cannot be read.""" first = None if carried else min( @@ -4386,11 +4355,10 @@ def _merged_after_start(counters: dict, task: str, pr: str, pr_state, cache: dic def _pr_files_once(counters: dict, pr_files, url: str) -> list[str] | None: """A PR's changed files, read at most once per PR per shift and kept in - `counters["pr_files"]` (S6, M3.7b; AUTONOMY.md "The watcher's network - surface", amendment 2026-11-19). A read that fails, raises or may be - truncated is kept as None — unreadable, an overlap — and never read - again. None, uncached, when there is no reader (a test spawner): that - fails toward the branch update, as before S6.""" + `counters["pr_files"]` (AUTONOMY.md "The watcher's network surface"). A + read that fails, raises or may be truncated is kept as None — unreadable, + an overlap — and never read again. None, uncached, when there is no + reader (a test spawner): that fails toward the branch update.""" cache = counters.setdefault("pr_files", {}) if url in cache: return cache[url] @@ -4404,15 +4372,15 @@ def _pr_files_once(counters: dict, pr_files, url: str) -> list[str] | None: return cache[url] -#: The label a worker puts on a PR whose decision the human must take (S7). +#: The label a worker puts on a PR whose decision the human must take. DECISION_TAKEN = "decision-taken" -#: Why a `decision-taken` PR is refused at PR-open (S7, M3.7c, #690). +#: Why a `decision-taken` PR is refused at PR-open. DECISION_TAKEN_WHY = "decision-taken — the human's /prm" -#: Label reads one PR may fail in a shift before it goes to the human's /prm -#: (review round 1, M3.7c): never assumed clean. At most one read a tick, and -#: never refused sooner than LABEL_READ_GRACE_S after the watcher first saw -#: the PR (round 2): with 60 s ticks and kicks, 3 misses take 2 minutes, so a -#: short `gh` outage must not refuse every new PR of the shift. +#: Label reads one PR may fail in a shift before it goes to the human's /prm: +#: never assumed clean. At most one read a tick, and never refused sooner +#: than LABEL_READ_GRACE_S after the watcher first saw the PR: with 60 s +#: ticks and kicks, 3 misses take 2 minutes, so a short `gh` outage must +#: not refuse every new PR of the shift. LABEL_READS = 3 LABEL_READ_GRACE_S = 900 LABELS_UNREADABLE_WHY = (f"labels unreadable ({LABEL_READS} misses over " @@ -4424,13 +4392,12 @@ def _pr_files_once(counters: dict, pr_files, url: str) -> list[str] | None: def _pr_labels_once(counters: dict, pr_state, cache: dict, url: str) -> list[str] | None: """A PR's label names, read once per PR per shift and kept in - `counters["pr_labels"]` (S7, M3.7c; AUTONOMY.md "The watcher's network - surface", amendment 2026-11-19): the `labels` field of the `gh pr view` - the tick already makes (`_gh_once`). None when GitHub cannot say: not - kept, asked again next tick (each miss counted in - `counters["pr_label_misses"]`), never assumed clean. No reader at all (a - test spawner) reads as no labels, uncached: the close-out's own label - check stays the second layer.""" + `counters["pr_labels"]` (AUTONOMY.md "The watcher's network surface"): + the `labels` field of the `gh pr view` the tick already makes + (`_gh_once`). None when GitHub cannot say: not kept, asked again next + tick (each miss counted in `counters["pr_label_misses"]`), never assumed + clean. No reader at all (a test spawner) reads as no labels, uncached: + the close-out's own label check stays the second layer.""" kept = counters.setdefault("pr_labels", {}) if url in kept: return kept[url] @@ -4449,9 +4416,9 @@ def _pr_labels_once(counters: dict, pr_state, cache: dict, url: str) -> list[str def _overlap(counters: dict, pr: str, merged_ahead: list[str], pr_state, pr_files, cache: dict) -> tuple[list[str], list[str]]: """(need, disjoint): which PRs merged ahead of `pr` its branch must be - updated for (ruling S6, M3.7b). Every one when GitHub reports `pr` - CONFLICTING or `pr`'s own files cannot be read; otherwise each one whose - changed files intersect `pr`'s, or cannot be read. The rest are disjoint.""" + updated for. Every one when GitHub reports `pr` CONFLICTING or `pr`'s own + files cannot be read; otherwise each one whose changed files intersect + `pr`'s, or cannot be read. The rest are disjoint.""" if not merged_ahead: return [], [] if (_gh_once(pr_state, cache, pr) or {}).get("mergeable") == "CONFLICTING": @@ -4471,35 +4438,34 @@ def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt. pr_state=None, pr_files=None) -> dict: """Start one close-out per newly open PR, under the watcher's guards. - Ruling S5 (M3.7b, PyAutoBrain#688): a PR whose CI reads RUNNING or - HEALTHY starts its close-out at once; the session runs the witness and - reads the diff while CI runs, then waits in-turn (`ci-verdict --until`, - at most CLOSEOUT_CI_WAIT_S and never past `review-at:`) and merges only on - GREEN. FAILED or UNKNOWN refuses with no session; NO-CHECKS waits - UPDATE_CHECKS_GRACE_S from when the watcher first saw the PR, then refuses. - Decision A: the watcher takes no merge slot for a merge close-out; it - refuses one when the cap has no room (`_merge_slots.room`, counting the - close-outs already running without a slot). The session takes its slot - itself, immediately before the merge. - - Merge order (M3.6j, PyAutoBrain#683): a library PR whose earlier PR of - this shift on the same library is still open waits — no close-out, no - merge slot, no refusal — in `counters["merge_waits"]`, rebuilt each tick; - a workspace PR waits while its own task's library PR waits or is being - closed out. Once nothing is ahead of it, a PR whose branch was cut before - an earlier PR merged gets a branch-update session first (`gh pr - update-branch`, ruling a) under a merge slot the watcher takes — only when - their changed files overlap, a file list cannot be read, or GitHub reports - this PR CONFLICTING (ruling S6). Its merge close-out starts on a later - tick, once GitHub shows the update's head and CI there is not red.""" + A PR whose CI reads RUNNING or HEALTHY starts its close-out at once; the + session runs the witness and reads the diff while CI runs, then waits + in-turn (`ci-verdict --until`, at most CLOSEOUT_CI_WAIT_S and never past + `review-at:`) and merges only on GREEN. FAILED or UNKNOWN refuses with no + session; NO-CHECKS waits UPDATE_CHECKS_GRACE_S from when the watcher + first saw the PR, then refuses. The watcher takes no merge slot for a + merge close-out; it refuses one when the cap has no room + (`_merge_slots.room`, counting the close-outs already running without a + slot). The session takes its slot itself, immediately before the merge. + + Merge order: a library PR whose earlier PR of this shift on the same + library is still open waits — no close-out, no merge slot, no refusal — + in `counters["merge_waits"]`, rebuilt each tick; a workspace PR waits + while its own task's library PR waits or is being closed out. Once + nothing is ahead of it, a PR whose branch was cut before an earlier PR + merged gets a branch-update session first (`gh pr update-branch`) under a + merge slot the watcher takes — only when their changed files overlap, a + file list cannot be read, or GitHub reports this PR CONFLICTING. Its + merge close-out starts on a later tick, once GitHub shows the update's + head and CI there is not red.""" lease_dir = slot / "leases" health = health or _digest.pr_health budget = _brief._nonneg_int(brief.get("token-budget", {}).get("value", "")) - cache: dict = {} # GitHub's word on a PR, read once this tick (ruling b) + cache: dict = {} # GitHub's word on a PR, read once this tick before_waits = counters.get("merge_waits") or {} waits: dict = {} counters["merge_waits"] = waits - # PRs held while the sweep is unknown (M3.7e), rebuilt each tick. + # PRs held while the sweep is unknown, rebuilt each tick. before_sweep = counters.get("sweep_waits") or {} sweep_waits: dict = {} counters["sweep_waits"] = sweep_waits @@ -4533,13 +4499,13 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: refuse(pr, task, "dropped by /drop — the human's /prm", held=again) continue if tier not in ("glance", "notify"): - # Ruling R3 (2026-11-17, #661): a `notify` PR a worker left - # open is closed out on the same terms as a `glance` one. + # A `notify` PR a worker left open is closed out on the same + # terms as a `glance` one. refuse(pr, task, f"tier {tier} — never merged unattended → your /prm", held=again) 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 + # A carried PR 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 = _gh_once(pr_state, cache, pr) if not gh: @@ -4549,7 +4515,7 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: # Merged by the human since its shift: settled, nothing left # for anyone. Final like a refusal (no close-out, no count as # an unattended merge), but the digest never lists it as - # needing the human (2026-11-19-pm2 and 2026-11-20-am did). + # needing the human. refuse(pr, task, f"{_digest.SETTLED} since {out['carried_from']}" + (f" (by {gh['mergedBy']})" if gh.get("mergedBy") else ""), held=again) @@ -4560,13 +4526,13 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: refuse(pr, task, f"carried over from {out['carried_from']}, but GitHub reads " f"it {state or '?'} — not closed out", held=again) continue - # S7 (M3.7c, #690): a `decision-taken` PR is the human's /prm, from - # its label alone: no close-out session, no merge slot, no CI read. - # It stays among the shift's known PRs, so a later PR on its library - # still waits behind it (ruling c). After the carried check (review - # round 1): a carried PR the human merged or closed is reported by - # its GitHub state. Unreadable: asked again next tick, then the - # human's /prm after LABEL_READS misses over LABEL_READ_GRACE_S. + # A `decision-taken` PR is the human's /prm, from its label alone: no + # close-out session, no merge slot, no CI read. It stays among the + # shift's known PRs, so a later PR on its library still waits behind + # it. After the carried check: a carried PR the human merged or closed + # is reported by its GitHub state. Unreadable: asked again next tick, + # then the human's /prm after LABEL_READS misses over + # LABEL_READ_GRACE_S. labels = _pr_labels_once(counters, pr_state, cache, pr) if labels is None: first = _iso_or_none(seen.get(pr) or "") @@ -4578,24 +4544,23 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: if DECISION_TAKEN in labels: refuse(pr, task, DECISION_TAKEN_WHY, held=again) continue - # The red sweep (M3.7e): a PR on a failing workspace's install chain - # is the human's /prm until a later sweep is green or /clear-sweep. + # The red sweep: a PR on a failing workspace's install chain is the + # human's /prm until a later sweep is green or /clear-sweep. blk = (counters.get("sweep") or {}).get("block") if _sweep_blocks(blk, pr): if blk.get("kind") == "unknown": - # The run list is unreadable (M3.7e review round 2): a wait, - # like the merge order's — no session, no slot, no refusal; - # judged again next tick. + # The run list is unreadable: a wait, like the merge order's — + # no session, no slot, no refusal; judged again next tick. prev = before_sweep.get(pr) or {} sweep_waits[pr] = {"task": task, "why": blk["why"], "since": prev.get("since") or _iso(now)} continue refuse(pr, task, blk["why"], held=again) continue - # Merge order (M3.6j): an earlier library PR of this shift still open - # holds this one back. Waiting is not a refusal and takes no slot. An - # earlier PR whose close-out is running (waiting in-turn on its CI, - # S5) is still open, so this one gets no session until it merges. + # Merge order: an earlier library PR of this shift still open holds + # this one back. Waiting is not a refusal and takes no slot. An + # earlier PR whose close-out is running (waiting in-turn on its CI) + # is still open, so this one gets no session until it merges. behind = _merge_blockers(counters, pr, pr_state, cache) if not behind and not _library_key(pr): behind = [u for u in out["prs"] if u != pr and _library_key(u) @@ -4610,8 +4575,8 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: events.setdefault("waiting", []).append(pr) continue if again and co.get("state") == "updated" and co.get("head"): - # CI is judged on the head the update made (review F5): until - # GitHub shows that head, a check read may be an older head's. + # CI is judged on the head the update made: until GitHub shows + # that head, a check read may be an older head's. head = (_gh_once(pr_state, cache, pr) or {}).get("head") or "" if not head: continue # GitHub cannot say yet: asked again next tick @@ -4637,8 +4602,8 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: # An updated PR at review-at is not refused: it keeps its # state, the digest reports it, and the next shift carries it. continue - # A close-out runs ~10-30 min; one still out at review-at - # merged outside the digest (#632, F1). Final, like the others. + # A close-out runs ~10-30 min; one still out at review-at would + # merge outside the digest. Final, like the others. refuse(pr, task, f"open within {CLOSEOUT_CUTOFF_S // 60} min of review-at — " "no close-out starts this late") continue @@ -4650,17 +4615,17 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: + ", ".join(counters["usage_unavailable"]) + ")"}) continue spent = _committed_tokens(counters) - # `is not None`: a `/cap tokens 0` (#644) means zero, not "no budget". + # `is not None`: a `/cap tokens 0` means zero, not "no budget". if budget is not None and spent >= CLOSEOUT_BUDGET_FACTOR * budget: - # The human's ruling 2026-11-14 (#632, F5): a close-out may pass - # the budget, but none starts once spend reaches 1.5x it — - # spend as the spawn gate counts it, reservations included. + # A close-out may pass the budget, but none starts once spend + # reaches CLOSEOUT_BUDGET_FACTOR × it — spend as the spawn gate + # counts it, reservations included. refuse(pr, task, f"token spend {spent} (committed) reached " f"{CLOSEOUT_BUDGET_FACTOR}× token-budget {budget}", held=again) continue - # Branch update (M3.6j): an earlier PR merged after this branch was - # cut, and this PR's branch does not have it yet — needed only when - # their changed files overlap or GitHub reports a conflict (S6). + # Branch update: an earlier PR merged after this branch was cut, and + # this PR's branch does not have it yet — needed only when their + # changed files overlap or GitHub reports a conflict. after = list((co or {}).get("after") or []) ahead = [u for u in _merged_after_start(counters, task, pr, pr_state, cache, bool(out.get("carried_from"))) @@ -4672,17 +4637,17 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: "→ your /prm", held=again) continue if need: - # One merge-slot count for the shift (R3, #661). The watcher - # takes it before a branch-update session, last, so no other - # refusal holds a slot. Idempotent: an updated PR holds its slot. + # One merge-slot count for the shift. The watcher takes it + # before a branch-update session, last, so no other refusal + # holds a slot. Idempotent: an updated PR holds its slot. try: taken, why = _merge_slots.take(slot, pr, _merge_slots.WATCHER, task) except (_merge_slots.MergeSlotError, OSError) as e: taken, why = False, f"merge slot cannot tell ({str(e)[:200]}) — left for your /prm" else: - # Decision A (M3.7b): the merge close-out takes its own slot just - # before the merge. The watcher only reads that one would be free, - # counting the close-outs already running without one. + # The merge close-out takes its own slot just before the merge. + # The watcher only reads that one would be free, counting the + # close-outs already running without one. pending = sum(1 for u, c in counters["closeouts"].items() if c.get("state") == "running" and c.get("kind") != "update" and _merge_slots.pr_key(u) not in counters.get("slot_holders", {})) @@ -4702,7 +4667,7 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: new.update(kind="update", after=after + need, updates=updates) else: # Only a PR with earlier PRs of the shift on its library is - # told about them, so every other close-out starts as before. + # told about them; every other close-out gets no merge-order step. before = _earlier_prs(counters, pr) until = now + _dt.timedelta(seconds=CLOSEOUT_CI_WAIT_S) if review_at is not None: @@ -4730,8 +4695,8 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: #: The merge-actor class the watcher writes on every stage-2 row (AUTONOMY.md -#: "Merge actor and random audit — 2026-11-12"); the Mind's lifecycle.py holds -#: the full set. +#: "Merge actor and random audit"); the Mind's lifecycle.py holds the full +#: set. STAGE2_ACTOR = "unattended-watcher" @@ -4754,8 +4719,8 @@ def pick_record(member: dict, brief: dict, *, proposed: bool = False) -> dict: `batch watch` to show it by title, size and repo, not by file name.""" why = _brief.pick_reason(member, brief) if member.get("resume"): - # An answer is not a new priority (Decision H11 a): the pick names - # the answer, then the standing it re-entered at. + # An answer is not a new priority: the pick names the answer, then + # the standing it re-entered at. why = (f"resumed after {', '.join(member['resume'].get('ids') or ['?'])} was " f"answered · {why}") rec = {"prompt": member["path"], "why": why, @@ -4768,8 +4733,8 @@ def pick_record(member: dict, brief: dict, *, proposed: bool = False) -> dict: def _propose(members: list[dict], brief: dict, counters: dict, max_sessions: int) -> list[str]: - """A shadow shift's tick (phase 4a): record what a live shift would have - dispatched — no lease, no worker — up to the brief's `max-sessions:`.""" + """A shadow shift's tick: record what a live shift would have dispatched — + no lease, no worker — up to the brief's `max-sessions:`.""" out = [] for member in members: task = task_id(member["path"]) @@ -4782,9 +4747,9 @@ def _propose(members: list[dict], brief: dict, counters: dict, max_sessions: int return out -# --- which brief: the one open on Mind origin/main (M3.6a, PyAutoBrain#659) ------- +# --- which brief: the one open on Mind origin/main -------------------------------- -#: The env file's brief: now only an override, honoured inside its own window. +#: The env file's brief: only an override, honoured inside its own window. SHIFT_BRIEF_ENV = "PYAUTO_SHIFT_BRIEF" ORIGIN_REF = "origin/main" @@ -4884,8 +4849,8 @@ def find_briefs(mind: Path, now: _dt.datetime, *, override: Path | None = None, working tree; one pushed but missing there is named, not ticked. An override takes the open brief's place only while it is open itself; - in its late window it is one more late brief, ticked beside the open one - (M3.6a review: a stale env file must never displace the next shift).""" + in its late window it is one more late brief, ticked beside the open one: + a stale env file must never displace the next shift.""" state = _override_state(override, now) if override is not None else "" briefs = shift_briefs(mind, ref) if briefs is None: @@ -4902,7 +4867,7 @@ def find_briefs(mind: Path, now: _dt.datetime, *, override: Path | None = None, and (Path(home) / b["name"] / "leases").is_dir() and late_owed(Path(home) / b["name"])] # Past the catch-up with something still owed: never ticked again, so the - # human is told once which slot was left and what it owes (M3.6a review). + # human is told once which slot was left and what it owes. abandoned = [] for b in briefs: slot = Path(home) / b["name"] @@ -4945,10 +4910,10 @@ def find_briefs(mind: Path, now: _dt.datetime, *, override: Path | None = None, def watch(mind: Path, *, home: Path | None = None, now: _dt.datetime | None = None, override: Path | None = None, **kw) -> dict: - """One timer firing (M3.6a, PyAutoBrain#659): find the brief(s) on Mind - `origin/main` and tick each. {"action": "idle", "reason"} when there is - none; else {"action": "watch", "ticked": {slot: tick result}} plus a - `reason` for what was left out.""" + """One timer firing: find the brief(s) on Mind `origin/main` and tick + each. {"action": "idle", "reason"} when there is none; else + {"action": "watch", "ticked": {slot: tick result}} plus a `reason` for + what was left out.""" now = now or _now() paths, why = find_briefs(mind, now, override=override, home=home) out: dict = {"action": "watch", "ticked": {}} diff --git a/agents/conductors/batch/_premise.py b/agents/conductors/batch/_premise.py index a96308e4..4d798914 100644 --- a/agents/conductors/batch/_premise.py +++ b/agents/conductors/batch/_premise.py @@ -1,11 +1,9 @@ """The premise check — does a draft's premise still hold on a fresh `main`? -Programme task M1.3, slice 1 (PyAutoBrain#608). In the one live shift that -worked (2026-11-06-pm), 2 of 3 dispatched tasks were obsolete on `main`: one -named a harness deleted five weeks earlier, the other a smoke-cap overrun the -timing record had not shown for days. Both workers noticed and stopped, but -each had been paid for as a full run. The planner's close-out guard looks for -work that ARRIVED; it cannot see a premise that has GONE AWAY. This can. +A draft can go obsolete while it waits: the harness it names is deleted, the +overrun it reports stops happening. A worker dispatched on it is paid for as +a full run before it notices. The planner's close-out guard looks for work +that ARRIVED; it cannot see a premise that has GONE AWAY. This can. It is mechanical and cheap — git reads plus, optionally, one `gh api` per named issue; never an LLM call. For each repo the draft names it views `main` diff --git a/agents/conductors/batch/_questions.py b/agents/conductors/batch/_questions.py index 134ee49a..b632bd42 100644 --- a/agents/conductors/batch/_questions.py +++ b/agents/conductors/batch/_questions.py @@ -1,4 +1,4 @@ -"""The questions inbox, Brain side (M3.5, PyAutoBrain#645) — readers only. +"""The questions inbox, Brain side — readers only. PyAutoMind `questions.md` holds the questions shift workers parked on, one `### Q. — ` entry each under `## Open`, `## Deferred`, @@ -133,9 +133,9 @@ def git(*args): # --- the parked hold ------------------------------------------------------------- -#: The inbox kind the readiness pass files (M3.3, PyAutoBrain#671): a gate on a -#: queued task for the human to rule on. It is answered like a question but -#: never holds or releases a parked task, and the inbox line leaves it out. +#: The inbox kind the readiness pass files: a gate on a queued task for the +#: human to rule on. It is answered like a question but never holds or +#: releases a parked task, and the inbox line leaves it out. RULING = "ruling" @@ -150,9 +150,9 @@ def questions_only(entries) -> list[dict]: def hold_for(task: str, shift: str, inbox: dict | None) -> tuple[str, dict | None]: """How the inbox rules on one task an earlier shift `shift` left parked: - ("held", None) — no entry (a park from before M3.5) or no readable inbox; + ("held", None) — no entry or no readable inbox; ("waiting", {ids}) — an entry is Open or Deferred; - ("dropped", {ids}) — an entry was dropped: the task is shelved (H9 a); + ("dropped", {ids}) — an entry was dropped: the task is shelved; ("answered", {ids, comments, answers}) — every entry is answered.""" if inbox is None: return "held", None @@ -256,18 +256,18 @@ def dashboard_link(mind) -> str: def unfiled_lines(counters: dict) -> list[str]: """One digest line per question the watcher could not file (no prompt, no - shift issue, an issue that is not a URL): never a silent drop (#645).""" + shift issue, an issue that is not a URL): never a silent drop.""" return [f"Inbox: not filed — `{u.get('task')}` ({u.get('kind')}): {u.get('why')}; " "see the task's issue or session yourself." for u in counters.get("inbox_unfiled") or []] def inbox_line(counters: dict, slot_name: str, mind=None, origin=None) -> str: - """The digest's one inbox line (Decision H7 a), "" when the shift added - none: `Inbox: 2 questions added to your inbox this shift (Q17, Q18), 5 - open in all — `. Ids and the open count come from Mind origin/main - (`origin`, else read here); a question still queued for the writer is - counted without its id.""" + """The digest's one inbox line, "" when the shift added none: `Inbox: 2 + questions added to your inbox this shift (Q17, Q18), 5 open in all — + `. Ids and the open count come from Mind origin/main (`origin`, + else read here); a question still queued for the writer is counted + without its id.""" added = counters.get("inbox") or [] if not added: return "" diff --git a/agents/conductors/batch/_ral.py b/agents/conductors/batch/_ral.py index 01451e9c..e21bde21 100644 --- a/agents/conductors/batch/_ral.py +++ b/agents/conductors/batch/_ral.py @@ -1,14 +1,11 @@ """The unattended-ssh probe for a brief that grants the `ral` lane. -Shift 2026-11-20-am ran with `lanes: any local-dev ral` and a -`ral-allowance:`, and its one worker that needed RAL could not reach it: -`Permission denied … Too many authentication failures`, key auth through the -jump host with nobody to answer. It spent a session and parked on a question. -Nothing at launch had said the lane was unusable. - -`batch brief --check` therefore asks once, for a brief whose `lanes:` include -`ral`: `ssh -o BatchMode=yes -o ConnectTimeout=10 true`. BatchMode -never prompts, so the answer is what a worker will get. The result is one of: +A worker reaches RAL by key auth through the jump host with nobody to answer +a prompt, so a lane that is unusable must be said at launch, not found by a +worker that spends its session on it. For a brief whose `lanes:` include +`ral`, `batch brief --check` asks once: +`ssh -o BatchMode=yes -o ConnectTimeout=10 true`. BatchMode never +prompts, so the answer is what a worker will get. The result is one of: - `ok` — the host answered; - `failed` — ssh ran and exited non-zero (its last line is the detail); @@ -18,7 +15,7 @@ Anything but `ok` and `skipped` is a **warning, never a refusal**: the human may be about to fix it, and a brief with no RAL task loses nothing. It runs in the launch chat only, never in the watcher (AUTONOMY.md "The watcher's network -surface", RAL probe — 2026-11-22). +surface", RAL probe). The host is the tenant's, so it is never written here. `PYAUTO_RAL_SSH_HOST` names it; otherwise it is read from the Mind's own access note, diff --git a/agents/conductors/batch/_ready.py b/agents/conductors/batch/_ready.py index 15cc589e..7a7f0896 100644 --- a/agents/conductors/batch/_ready.py +++ b/agents/conductors/batch/_ready.py @@ -1,12 +1,10 @@ -"""The readiness pass, `batch ready` (M3.3 slice 1, PyAutoBrain#671). +"""The readiness pass, `batch ready`. It walks Mind `queue.md`, resolves each entry to its next startable unit(s), checks each unit's gates, and turns every gate into an inbox entry of kind -`ruling` for the human. The next launch is then `brief --new`, read, go, -instead of a kick-off chat that finds each epic's next unit and asks the -rulings one at a time. +`ruling` for the human, so the next launch is `brief --new`, read, go. -Resolution (human decisions D3, 2026-11-18): +Resolution: - an epic ledger (a prompt with `Epic:` and no `Phase:`) resolves to every open member of that epic at the lowest leading phase number (`5c` is 5), @@ -15,19 +13,18 @@ gate `no-next-phase`. The ledgers' free-form phase tables are not read; - any other prompt resolves to itself, in flight when it is in `active/`. -Gates on each draft unit (Q5): `looks-shipped`, then `obsolete` (the premise +Gates on each draft unit: `looks-shipped`, then `obsolete` (the premise check, offline unless `--fetch`), and either one stops the rest. Then each of `claimed`, `unattended`, `human-required`, `blocked-by` and `no-lane` that -applies is its own ruling. A `judge` unit gets a note (D4: a tier is not a -gate). +applies is its own ruling. A `judge` unit gets a note (a tier is not a gate). What it writes: nothing on a dry run. `queue` puts one `question-add` op per new ruling in a slot's ledger, for the shift's one Mind writer, and records `counters["rulings"]`; `apply` writes them into a session-branch Mind checkout through Mind's own `questions_edit.add_text` (never on `main`, never a commit -or a push). A ruling still Open or Deferred on Mind `origin/main` for the same -task and gate is not filed again. Everything on the Mind side is read from the -local `origin/main` ref: no fetch. +or a push). A ruling in any state on Mind `origin/main` for the same task and +gate is not filed again. Everything on the Mind side is read from the local +`origin/main` ref: no fetch. """ from __future__ import annotations @@ -300,7 +297,7 @@ def check_premise(path: Path): unit_paths = [path] if epic and _batch._phase_declared(text) and not _batch._is_done(text): # A Phase member queued directly that is not its epic's next - # phase: a note, not a gate (PyAutoBrain#671 review, M3). + # phase: a note, not a gate. low = min((m["phase"] for m in epic_members(mind, epic)), default=float("inf")) mine = _batch._phase_of(text) @@ -354,10 +351,9 @@ def check_premise(path: Path): for t, xs in (origin or {}).items() for x in xs if _questions.is_ruling(x) and x["state"] in ("open", "deferred")), key=lambda x: int(x["id"][1:]) if x["id"][1:].isdigit() else 0) - # Once ruled, quiet (the human's L1 ruling, 2026-11-18): a ruling in any - # state — Open, Deferred, Answered or Dropped — keeps its task and gate - # from being filed again; `/questions` reopen asks again. An open one is - # named first. + # Once ruled, quiet: a ruling in any state — Open, Deferred, Answered + # or Dropped — keeps its task and gate from being filed again; + # `/questions` reopen asks again. An open one is named first. ruled: dict = {} for t, xs in (origin or {}).items(): for x in xs: @@ -502,8 +498,8 @@ def needed(counters: dict) -> int: def digest_lines(counters: dict) -> list[str]: """The digest's closing lines: why the pass failed or filed nothing, then - "The next shift needs N rulings from you." — nothing for a shift whose - watcher predates the pass (no `counters["rulings"]`).""" + "The next shift needs N rulings from you." — nothing when the pass did + not run (no `counters["rulings"]`).""" if "rulings" not in counters: return [] c = counters["rulings"] or {} diff --git a/agents/conductors/batch/_status.py b/agents/conductors/batch/_status.py index 981ab4f8..27308b0d 100644 --- a/agents/conductors/batch/_status.py +++ b/agents/conductors/batch/_status.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 """agents/conductors/batch/_status.py — one reading of "is a batch in flight?". -The Mind's dashboard shows this as the Shift part of its Autopilot block -(PyAutoBrain#650): the slot that is in flight, every member on one line, and — -once there is something to review — the button to its packet. The *reading* lives here and the dashboard only supplies its facts. +The Mind's dashboard shows this as the Shift part of its Autopilot block: the +slot that is in flight, every member on one line, and — once there is +something to review — the button to its packet. The *reading* lives here and +the dashboard only supplies its facts. Two constraints shape this module, and they are why it is a module at all: @@ -17,10 +18,6 @@ The vocabulary (`RECORD_KEY`, `PENDING_RE`) lives here and `_batch.py` imports it back, so the words the record is written in have one definition. - -It rendered a second box for the Cortex until 2026-09-03, when the science -review slot was retired (PyAutoCortex#9); checking in on the science is -`pyauto-brain cortex checkin` now, and that surface has no board of its own. """ from __future__ import annotations @@ -107,7 +104,7 @@ def _head(text: str, limit: int = 72) -> str: def dev_status(slot: str, keys: dict, members: list, review_exists: bool, pages: str) -> dict | None: - """The Mind's (development) reading — today's behaviour, unchanged. + """The Mind's (development) reading. A dev batch is dispatched at once and reviewed at once: it is open until it has been reviewed, and the review button appears when `collect` has @@ -145,7 +142,7 @@ def _status(slot: str, kind: str, keys: dict, rows: list, reviewable: bool, "url": review_url(pages, slot) if reviewable else "", "packet": f"batches/packets/{slot}.html", # A running shift's status, as its watcher last wrote it into the - # record (`- live:`, PyAutoBrain#622) — a record line, not a clock. + # record (`- live:`) — a record line, not a clock. "live": _one(keys, "live"), "issue": issue_url(keys), } diff --git a/agents/conductors/batch/_steer.py b/agents/conductors/batch/_steer.py index 11b9543c..48414df2 100644 --- a/agents/conductors/batch/_steer.py +++ b/agents/conductors/batch/_steer.py @@ -2,14 +2,14 @@ Readers only. `queue.md` is the ordered list of prompts the human wants done (the planner's statement of importance); `goals.md` is the ordered list of -goals a shift brief copies into `goals:` (PyAutoMind#565). Both are written by -the human alone, by hand or in a `/queue` chat (Brain `skills/queue`, through -the Mind's `scripts/queue_edit.py`), and validated by the Mind's -`lifecycle.py check`. The dashboard only reads them. - -The grammar is the one `lifecycle.py` and `_batch.read_queue` read: a fenced -block is the schema's own example, any heading ends the entry above it, and -only a numbered `## . ` heading starts one. +goals a shift brief copies into `goals:`. Both are written by the human alone, +by hand or in a `/queue` chat (Brain `skills/queue`, through the Mind's +`scripts/queue_edit.py`), and validated by the Mind's `lifecycle.py check`. +The dashboard only reads them. + +The grammar is the one `lifecycle.py` reads: a fenced block is the schema's +own example, any heading ends the entry above it, and only a numbered +`## . ` heading starts one. """ from __future__ import annotations @@ -22,9 +22,9 @@ GOAL_FIELD_RE = re.compile(r"^-\s+(epics|tags|note):\s*(.*?)\s*$") -# --- the planner's queue reader (was `_batch.read_queue`; `_batch` re-exports -# it). The Mind dashboard ranks its read-only ★ with it too (PyAutoBrain#640), -# so the page's `#n` is the planner's order by construction. +# --- the planner's queue reader (`_batch` re-exports it). The Mind dashboard +# ranks its read-only ★ with it too, so the page's `#n` is the planner's order +# by construction. #: A `queue.md` section heading — `## .