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/_common.sh b/agents/_common.sh index c8f85140..d7eef06c 100755 --- a/agents/_common.sh +++ b/agents/_common.sh @@ -75,24 +75,11 @@ _resolve_dir() { # resolve_mind — locate the PyAutoMind checkout (the organism's intent store). resolve_mind() { _resolve_dir PYAUTO_MIND PyAutoMind; } -# resolve_cortex — locate the PyAutoCortex checkout (the organism's science -# state: one ledger per project — Now, Runs, Log). Resolved independently of -# the Mind so a session holding one organ and not the other still works. -resolve_cortex() { _resolve_dir PYAUTO_CORTEX PyAutoCortex; } - # resolve_memory — locate the PyAutoMemory checkout (the organism's long-term # scientific/architectural knowledge). Optional: the Feature Agent degrades # gracefully when memory is absent rather than inventing context. resolve_memory() { _resolve_dir PYAUTO_MEMORY PyAutoMemory; } -# readiness_verdict — run `pyauto-heart readiness --json` and echo the verdict -# string (green/yellow/red). Returns non-zero if Heart can't be resolved/run. -readiness_verdict() { - local heart - heart="$(resolve_heart)" || return $? - "$heart" readiness --json | python3 -c 'import json,sys; print(json.load(sys.stdin).get("verdict","unknown"))' -} - # _agents_dir — directory holding the sibling agents (this file lives in it). # Agents are organised into two tiers beneath it: conductors/ (front-door agents # a human drives) and faculties/ (read-only reasoning capabilities the conductors @@ -108,10 +95,6 @@ _agents_dir() { # keeps the conductors (build, release, feature, health) decoupled from Heart's # surface and lets them all read the verdict the same way. # -# (Back-compat: `consult_health_agent_verdict` remains as an alias below — the -# faculty was renamed health -> vitals, and the loop conductor took the name -# `health`.) -# # --refresh ask the vitals faculty to refresh Heart's state first (a fresh # gate); release-grade work uses this, ordinary build work does not. # --profile P evaluate under a readiness evidence profile (e.g. `release-ci` @@ -217,9 +200,6 @@ except Exception: [[ "$out" == "green" ]] && echo "green" || echo "unknown" } -# Back-compat alias for the pre-rename name (faculty: health -> vitals). -consult_health_agent_verdict() { consult_vitals_verdict "$@"; } - # Print the readiness verdict's RED reason strings, one per line (empty if none # / unavailable). Used by the Build Agent's --accept-red override so a human can # authorize proceeding despite specific, named RED reasons. Reads the SAME diff --git a/agents/_pyauto_root.py b/agents/_pyauto_root.py index 3966b703..eca8a4a2 100644 --- a/agents/_pyauto_root.py +++ b/agents/_pyauto_root.py @@ -24,19 +24,15 @@ as unverified so a caller can say "I looked here and it was not a workspace" instead of silently finding nothing. -Consumers used to default to a hardcoded developer-box path instead of step 2. -On that box it was right; in a remote session ``$HOME`` is ``/root`` while the -checkouts are under ``/home/user``, so every consumer resolved into a directory -that does not exist. Nothing raised — these consumers all degrade — so they -reported empty. That is the failure mode this module exists to remove, and -naming any absolute workspace path here would reintroduce it for the next -environment that does not match. - -Step 2 exists for the mirror-image failure. Step 3 asks only "does this -directory hold an organ?", which a family subdirectory such as ``organs/`` -would answer yes to the moment the organs move into one — resolving the root -one level too deep, where every ``root / `` join below misses and, -again, nothing raises. The marker is what a directory says about itself. +No absolute workspace path is named here: a hardcoded developer-box default +resolves, in a remote session, into a directory that does not exist, and +because every consumer degrades rather than raises, they all report empty. + +Step 2 guards the mirror-image failure. Step 3 asks only "does this directory +hold an organ?", which a family subdirectory such as ``organs/`` also answers +yes to — resolving the root one level too deep, where every ``root / `` +join misses and, again, nothing raises. The marker is what a directory says +about itself. Stdlib only. """ 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/_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 cc4870f7..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, and reports what came back. 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 @@ -30,7 +28,6 @@ import argparse import datetime as _dt -import html import importlib.util import json import os @@ -38,7 +35,6 @@ import shutil import subprocess import sys -import tempfile from pathlib import Path BRAIN = Path(__file__).resolve().parents[3] @@ -48,22 +44,16 @@ 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) +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) @@ -75,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",) @@ -84,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" @@ -104,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 "" @@ -124,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) @@ -160,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") @@ -218,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") @@ -234,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": @@ -256,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) @@ -280,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 @@ -289,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) @@ -336,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: @@ -359,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 @@ -389,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" @@ -428,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}) @@ -445,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: @@ -468,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) @@ -545,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, @@ -561,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 @@ -594,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: @@ -603,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) @@ -622,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: @@ -639,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"]) @@ -657,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) @@ -668,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)")) @@ -690,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] @@ -736,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}], @@ -763,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" @@ -795,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"): @@ -811,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}") @@ -824,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 "") @@ -835,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") @@ -875,33 +853,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 +862,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 +876,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 +896,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*$") @@ -1174,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(): @@ -1202,456 +976,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 +1017,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("" #: 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/_integration.py b/agents/conductors/batch/_integration.py deleted file mode 100644 index 6414e3a5..00000000 --- a/agents/conductors/batch/_integration.py +++ /dev/null @@ -1,473 +0,0 @@ -"""agents/conductors/batch/_integration.py — the batch's integration branches. - -One throwaway worktree root per slot. Every member's head branch is merged into -`integration/`, per repo, off `origin/main`, so the human can *run* the -whole batch together before ruling on any of it — and so the question "how -would these resolve at the end?" is answered by a merge rather than by reading -diffs. - -Three properties, deliberately: - -* **It writes no remote unless `--push` is typed.** By default: `git fetch - origin` and local merges; no push, no PR, no remote ref is created or moved. - `--push` adds exactly one act, `push_repo` below — it publishes each - `integration/` to `origin` as a throwaway review ref. It is never - forced (no force flag, no lease): a branch that is not a fast-forward of what - is already published is pushed under a new `-N` name and the earlier ref is - left exactly where it is. Never a pull request, never a base for one. -* **It resolves nothing.** A member whose merge conflicts is left OUT of that - repo's branch and named with the conflicting paths. That report is the - product; it is not a failure of the collect, and it moves no exit code and no - member's health word (a member's health is about its own delivery; a merge - collision is a property of the *slot*). -* **It is stdlib-only and imports nothing from `_batch`.** The conductor loads - it lazily, so a session that never asks for `--integration` never pays for it — and this module stays unit-testable - against throwaway repos with no Mind, no record and no packet in sight. - -The seam with `bin/worktree.sh`: **worktree.sh knows layout, this module knows -merges.** The value of `worktree_create` is not `git worktree add` — it is the -root (activate.sh's `PYTHONPATH`, the per-task numba/matplotlib caches, and the -symlink of every other top-level entry so relative workspace paths resolve). -Re-deriving that here would fork the definition of "a PyAuto worktree root" into -two places that would drift, so the ROOT is built by shelling to worktree.sh -with `PYAUTO_WT_BRANCH=integration/`; the MERGES are plain `git`, because -a shell helper would bury the exit code and the unmerged-path list the packet -needs. -""" - -from __future__ import annotations - -import datetime as _dt -import os -import subprocess -from pathlib import Path - -import sys -sys.path.insert(0, str(Path(__file__).resolve().parents[2])) -from _repo_paths import repo_path # noqa: E402 -from _pyauto_root import pyauto_root # noqa: E402 - -BRAIN = Path(__file__).resolve().parents[3] -WORKTREE_SH = BRAIN / "bin" / "worktree.sh" - -#: `git` never gets to ask for a password: an unattended collect that blocks on -#: a credential prompt looks exactly like a hung merge. -GIT_ENV = {"GIT_TERMINAL_PROMPT": "0"} - -#: A box with no committed git identity (CI, a fresh container) cannot merge at -#: all. Supplied per-invocation with `-c`, and ONLY when the worktree has no -#: identity of its own — a human's box keeps their own name on their own merges. -FALLBACK_NAME = "PyAuto Batch" -FALLBACK_EMAIL = "batch@pyautolabs.invalid" - -NOT_LOCAL = ("batch collect --integration: the integration worktree is a " - "laptop leg (real git worktrees under $PYAUTO_WT_ROOT) — run " - "collect from the laptop; everything else is scored anyway.") - -NOT_LOCAL_PUSH = ("batch collect --integration --push: pushing an integration " - "ref needs the laptop's own git credential — a remote " - "session's GH_TOKEN is a proxy placeholder that cannot write " - "a ref at all (skills/GITHUB_ACCESS.md). Run it from the " - "laptop; everything else is scored anyway.") - -#: How many publications of one slot this will name before it gives up. A slot -#: that has been re-published twenty times is not a review branch any more. -MAX_SUFFIX = 20 - - -# ------------------------------------------------------------- where things go -def workspace_root() -> Path: - """The directory holding the organ checkouts side by side. - - Same convention as `bin/_pyauto_root.sh`: an explicit `PYAUTO_ROOT` is the - operator's word and always wins; otherwise it is the parent of this Brain - checkout, which is true in every environment the organism runs in. - """ - return pyauto_root() - - -def task_name(slot: str) -> str: - return f"integration-{slot}" - - -def branch_name(slot: str) -> str: - return f"integration/{slot}" - - -def wt_root() -> Path: - """Where task roots live — beside the workspace root, never inside it.""" - return Path(os.environ.get("PYAUTO_WT_ROOT") or f"{workspace_root()}-wt") - - -def root_for(slot: str) -> Path: - return wt_root() / task_name(slot) - - -def _env() -> dict: - """The environment every child gets: the caller's, plus the four variables - that make worktree.sh and this module resolve the *same* paths. Deriving - both sides from `workspace_root()` is what stops the root being built beside - one checkout while the merges read another.""" - env = dict(os.environ) - env.update(GIT_ENV) - env["PYAUTO_ROOT"] = str(workspace_root()) - env["PYAUTO_MAIN"] = str(workspace_root()) - env["PYAUTO_WT_ROOT"] = str(wt_root()) - return env - - -def _git(*args: str, cwd=None, timeout: int = 60): - """One git call. Captured, never interactive, and it NEVER raises on a - non-zero return code: every git failure here is a line in the report, and a - traceback out of a collect would lose the members that did merge.""" - try: - return subprocess.run(["git", *args], cwd=str(cwd) if cwd else None, - env=_env(), capture_output=True, text=True, - timeout=timeout) - except (OSError, subprocess.SubprocessError) as e: # pragma: no cover - return subprocess.CompletedProcess( - args=["git", *args], returncode=127, stdout="", stderr=str(e)) - - -def _tail(proc) -> str: - lines = ((proc.stderr or "") + (proc.stdout or "")).strip().splitlines() - return lines[-1][:160] if lines else "" - - -# ----------------------------------------------------------------- the plan -- -def plan_jobs(members: list, order: list, notes: list) -> list: - """`[{"repo", "dir", "members": [{"member", "branch", "want_sha"}…]}…]`. - - Grouped by **repo**, not by member: the common case is one member with organ - PRs across five repos, so a member contributes one head branch to each repo - it touched and can be merged in one and conflicted in another. Ordered by - the record's dispatch order (`order`), because `d["members"]` is re-sorted by - health and merge order is a property of the record, not of the scores. - - Everything left out says so. Four reasons, and none of them is a guess: - already merged, closed, no `head_ref` in the evidence, or a head that lives - on a fork (whose branch is simply not on `origin` and cannot be merged from - a local checkout at all). - """ - by_slug = {m.get("slug"): m for m in members} - groups: dict[str, dict] = {} - for slug in order: - m = by_slug.get(slug) - if not m: - continue - for p in m.get("prs") or []: - repo = str(p.get("repo") or "") - label = f"{repo}#{p.get('number')}" - if p.get("merged"): - notes.append(f"{slug}: {label} is already merged — not " - f"re-merged") - continue - if str(p.get("state") or "").upper() == "CLOSED": - notes.append(f"{slug}: {label} is CLOSED — not merged") - continue - head_ref = str(p.get("head_ref") or "") - if not head_ref: - notes.append(f"{slug}: {label} has no head_ref in the evidence " - f"— re-run collect --fetch (Phase 1 field " - f"headRefName)") - continue - head_repo = str(p.get("head_repo") or "") - if head_repo and head_repo != repo: - notes.append(f"{slug}: {label} is from a fork ({head_repo}) — " - f"its head is not on origin, left out") - continue - g = groups.setdefault(repo, {"repo": repo, - "dir": repo.split("/")[-1], - "members": []}) - g["members"].append({"member": slug, "branch": head_ref, - "want_sha": str(p.get("head_sha") or "")}) - jobs = [] - for g in groups.values(): - checkout = repo_path(workspace_root(), g["dir"]) - if not (checkout / ".git").exists(): - notes.append(f"{g['repo']}: no checkout at " - f"{checkout} — left out of the " - f"integration root") - continue - jobs.append(g) - return jobs - - -# ----------------------------------------------------------------- the root -- -def _worktree_sh(func: str, slot: str, *args: str): - """One call into `bin/worktree.sh`, with the branch override that is the - only thing it could not otherwise say.""" - env = _env() - env["PYAUTO_WT_BRANCH"] = branch_name(slot) - return subprocess.run( - ["bash", "-c", f'set -e; . "$0"; {func} "$@"', str(WORKTREE_SH), - task_name(slot), *args], - env=env, capture_output=True, text=True, timeout=600) - - -def ensure_root(slot: str, repo_dirs: list, notes: list): - """The worktree root, created or adopted. Idempotent by construction. - - `worktree_create` refuses an existing root — which is exactly why the two - branches are here rather than a force: a second run of the same slot adopts - the root it built the first time, and attaches only the repos that are still - placeholder symlinks in it. Anything that fails returns `None`: half a root - reported as an integration is worse than none. - """ - root = root_for(slot) - if not root.exists(): - proc = _worktree_sh("worktree_create", slot, *repo_dirs) - if proc.returncode != 0: - notes.append(f"integration root not built at {root}: " - f"{_tail(proc)}") - return None - return root - for name in repo_dirs: - if (repo_path(root, name) / ".git").exists(): - continue - proc = _worktree_sh("worktree_add_repo", slot, name) - if proc.returncode != 0: - notes.append(f"{name}: could not attach to the integration root " - f"at {root}: {_tail(proc)}") - return None - return root - - -# --------------------------------------------------------------- the merges -- -def _identity(wt: Path) -> list: - """`-c user.name=… -c user.email=…`, or nothing at all. A box with no - committed identity cannot make a merge commit; a box with one keeps it.""" - got = _git("-C", str(wt), "config", "user.email") - if got.returncode == 0 and got.stdout.strip(): - return [] - return ["-c", f"user.name={FALLBACK_NAME}", - "-c", f"user.email={FALLBACK_EMAIL}"] - - -def integrate_repo(job: dict, wt: Path, slot: str, notes: list) -> dict: - """One repo's integration branch. Returns the report row; raises nothing. - - The branch is **re-cut from `origin/main` on every run** (`checkout -B`). - The merge result is a function of the current `origin/main` and the current - heads, so a second run that merged onto the previous run's tip would report - a preview of a base that no longer exists — the honest refresh is a re-cut. - That is safe because the ref is a throwaway: nothing is pushed, no PR is - based on it and no member branch descends from it, so `-B` rewrites nothing - anyone else holds. (`AGENTS.md`'s "never rewrite history" is about - *published* history — which is precisely what Phase 3's never-force-push - rule will protect once such a branch exists on GitHub.) - - The one thing a re-cut could destroy is a human's uncommitted experiment - inside the integration worktree, so step 2 refuses a dirty worktree outright - and says so. **That refusal, not the branch policy, is the safety property.** - """ - branch = branch_name(slot) - row = {"repo": job["repo"], "dir": job["dir"], "path": str(wt), - "branch": branch, "base": "origin/main", "base_sha": "", - "head_sha": "", "merged": [], "conflicts": [], "status": "skipped", - "note": ""} - - # A run killed mid-merge leaves MERGE_HEAD and conflicted files behind, and - # `checkout -B` would refuse on both. Clearing it first is what makes the - # dirty check below mean "a human left something here", not "we did". - _git("-C", str(wt), "merge", "--abort") - - dirty = _git("-C", str(wt), "status", "--porcelain") - if dirty.returncode != 0: - row["note"] = f"git status failed in {wt}: {_tail(dirty)}" - notes.append(f"{job['repo']}: {row['note']}") - return row - if dirty.stdout.strip(): - row["note"] = ("the integration worktree has uncommitted changes — " - "left alone") - notes.append(f"{job['repo']}: {row['note']}") - return row - - fetched = _git("-C", str(wt), "fetch", "origin", "--quiet", timeout=300) - if fetched.returncode != 0: - notes.append(f"{job['repo']}: git fetch origin failed " - f"({_tail(fetched)}) — merged against the refs already " - f"here, which may be stale") - - base = _git("-C", str(wt), "rev-parse", "--verify", "origin/main") - if base.returncode != 0: - row["note"] = "no origin/main in this checkout — nothing to cut from" - notes.append(f"{job['repo']}: {row['note']}") - return row - row["base_sha"] = base.stdout.strip() - - cut = _git("-C", str(wt), "checkout", "-B", branch, "origin/main") - if cut.returncode != 0: - row["note"] = f"could not cut {branch} from origin/main: {_tail(cut)}" - notes.append(f"{job['repo']}: {row['note']}") - return row - - ident = _identity(wt) - for entry in job["members"]: - ref = f"origin/{entry['branch']}" - if _git("-C", str(wt), "rev-parse", "--verify", ref).returncode != 0: - notes.append(f"{entry['member']}: {ref} is not in " - f"{job['repo']} — pushed? left out") - continue - got = _git("-C", str(wt), *ident, "merge", "--no-ff", "--no-edit", - "-m", f"integration {slot}: {entry['member']} " - f"({entry['branch']})", ref, timeout=300) - if got.returncode == 0: - row["merged"].append(entry["member"]) - continue - # The unmerged paths exist only while the index is unmerged, so they are - # read BEFORE the abort — afterwards there is nothing left to name. - paths = _git("-C", str(wt), "diff", "--name-only", "--diff-filter=U") - row["conflicts"].append({ - "member": entry["member"], "branch": entry["branch"], - "paths": [p for p in paths.stdout.split("\n") if p.strip()]}) - _git("-C", str(wt), "merge", "--abort") - - head = _git("-C", str(wt), "rev-parse", "HEAD") - row["head_sha"] = head.stdout.strip() if head.returncode == 0 else "" - row["status"] = "conflicted" if row["conflicts"] else "clean" - return row - - -# ---------------------------------------------------------------- the push -- -def push_repo(row: dict, wt: Path, slot: str, notes: list) -> None: - """Publish one repo's integration branch to `origin`. Mutates `row`. - - The only remote write in this module, and the only one the batch ever makes. - It is a *throwaway review ref*: never a pull request, never a base for one, - and it expires at the record's `sweep-after:` date. - - **Nothing already on origin is ever moved.** There is no force flag and no - lease anywhere here; the four arms below are the whole decision, in order: - - 1. the merge was skipped — there is nothing to publish; - 2. `origin/` carries the SAME TREE as HEAD — not re-pushed. This arm - is load-bearing: `integrate_repo` re-cuts the branch every run - (`checkout -B` plus `--no-ff` merges), so the commit SHAs differ on every - refresh even when nothing changed. Comparing commits would make every - refresh look non-fast-forwardable and pile up `-2 … -20`; comparing trees - asks the question the human means, "is what is published still this?"; - 3. `origin/` is an ancestor of HEAD — a genuine fast-forward, pushed - plainly; - 4. otherwise the published ref and this one have diverged, so this one is - published under the first free `-N` instead and the earlier ref is - left exactly where it is. `branch -f` there only ever writes a LOCAL ref - whose name has just been proven absent on origin, so no published history - moves. - - A push that fails is a note and nothing more: `row["status"]` is never - touched, because the merge verdict is a fact about the merge and a network - failure must not turn a clean integration into a conflicted one. - """ - row["remote_branch"] = "" - row["pushed"] = False - row["push_note"] = "" - - if row.get("status") == "skipped": - row["push_note"] = "nothing was merged — nothing pushed" - return - - # The decision below rests on what is published RIGHT NOW, so the namespace - # is refreshed first. A failure is a note, not a stop — same shape as the - # fetch in `integrate_repo`. - fetched = _git("-C", str(wt), "fetch", "origin", "--quiet", - "+refs/heads/integration/*:refs/remotes/origin/integration/*", - timeout=300) - if fetched.returncode != 0: - notes.append(f"{row['repo']}: could not fetch the integration namespace " - f"({_tail(fetched)}) — the publication decision rests on " - f"the refs already here, which may be stale") - - base = branch_name(slot) - remote = f"origin/{base}" - target = base - - if _git("-C", str(wt), "rev-parse", "--verify", remote).returncode == 0: - theirs = _git("-C", str(wt), "rev-parse", f"{remote}^{{tree}}") - ours = _git("-C", str(wt), "rev-parse", "HEAD^{tree}") - same = (theirs.returncode == 0 and ours.returncode == 0 - and theirs.stdout.strip() == ours.stdout.strip()) - if same: - row["remote_branch"] = base - row["push_note"] = (f"origin/{base} already carries this exact " - f"tree — not re-pushed") - return - ff = _git("-C", str(wt), "merge-base", "--is-ancestor", remote, "HEAD") - if ff.returncode != 0: - cand = "" - for n in range(2, MAX_SUFFIX): - probe = f"{base}-{n}" - if _git("-C", str(wt), "rev-parse", "--verify", - f"origin/{probe}").returncode != 0: - cand = probe - break - if not cand: - row["push_note"] = ( - f"origin/{base} is not an ancestor of this branch, and " - f"-2 … -{MAX_SUFFIX - 1} are all published already — not " - f"pushed; sweep the old refs or collect a new slot") - notes.append(f"{row['repo']}: {row['push_note']}") - return - made = _git("-C", str(wt), "branch", "-f", cand, "HEAD") - if made.returncode != 0: - row["push_note"] = (f"could not name the local ref {cand}: " - f"{_tail(made)}") - notes.append(f"{row['repo']}: {row['push_note']}") - return - target = cand - row["push_note"] = (f"origin/{base} is not an ancestor of this " - f"branch — never force-pushed; published as " - f"{cand} instead") - - proc = _git("-C", str(wt), "push", "origin", - f"{target}:refs/heads/{target}", timeout=300) - if proc.returncode == 0: - row["remote_branch"] = target - row["pushed"] = True - return - row["pushed"] = False - row["remote_branch"] = "" - row["push_note"] = f"push failed: {_tail(proc)}" - notes.append(f"{row['repo']}: {row['push_note']}") - - -# ------------------------------------------------------------------- the leg -- -def run(members: list, order: list, slot: str, *, lane: str, - push: bool = False) -> tuple: - """`(block | None, notes)` — the whole `--integration` leg. - - Refuses any lane but `local-dev` with a pointer rather than a caught error, - exactly as `fetch_evidence` refuses a session with no `gh`: real git - worktrees under `$PYAUTO_WT_ROOT` are a laptop thing, and a cloud session - that tried would fail halfway rather than up front. `push=True` refuses the - same lanes for a second reason, and says that one instead: a remote - session's credential cannot write a ref at all. - """ - notes: list[str] = [] - if lane != "local-dev": - return None, [NOT_LOCAL_PUSH if push else NOT_LOCAL] - jobs = plan_jobs(members, order, notes) - if not jobs: - notes.append("batch collect --integration: no member PR has a " - "mergeable head branch in a local checkout — nothing to " - "integrate") - return None, notes - root = ensure_root(slot, [j["dir"] for j in jobs], notes) - if root is None: - return None, notes - repos = [integrate_repo(j, root / j["dir"], slot, notes) for j in jobs] - if push: - for j, r in zip(jobs, repos): - push_repo(r, root / j["dir"], slot, notes) - block = { - "slot": slot, "root": str(root), - "activate": str(root / "activate.sh"), - "branch": branch_name(slot), - "at": _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%MZ"), - # `sweep_after` is filled by the conductor: it is a fact about the - # RECORD (`review-at:` plus a week, or the human's own date), and this - # module never reads a record. - "pushed": bool(push), "sweep_after": "", - "repos": repos, "notes": list(notes), - } - return block, notes 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 96f351b5..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)] @@ -1110,11 +1097,6 @@ def _exit(rec: dict, word: str) -> None: rec["exits"].append(word) -def last_worker(counters: dict, task: str) -> dict | None: - """The newest worker record for a task (a re-dispatch makes a second).""" - return next((w for w in reversed(counters["workers"]) if w["task"] == task), None) - - def _reap(slot: Path, counters: dict, now: _dt.datetime, grace_s: float, agents: AgentsView | None = None, tokens=transcript_usage, *, late: bool = False) -> list[dict]: @@ -1122,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" @@ -1187,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"]: @@ -1202,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")) @@ -1272,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") @@ -1295,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}) @@ -1337,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 @@ -1346,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))) @@ -1356,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): @@ -1376,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 @@ -1401,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) @@ -1420,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} " @@ -1464,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) @@ -1501,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: @@ -1513,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 @@ -1530,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) @@ -1557,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() @@ -1603,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: @@ -1630,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 @@ -1649,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: @@ -1667,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) @@ -1693,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: " @@ -1705,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):(.*)$") @@ -1717,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 "" @@ -1785,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(): @@ -1840,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 @@ -1862,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 []), @@ -1895,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, {} @@ -1970,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) @@ -1982,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]] = {} @@ -2063,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 @@ -2084,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` @@ -2126,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) @@ -2140,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 @@ -2152,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) @@ -2178,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) @@ -2208,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), @@ -2230,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 " @@ -2248,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(): @@ -2282,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, @@ -2294,7 +2266,7 @@ def known(task: str) -> bool: own_tasks=counters["redispatched"]) except _mind_writer.MindWriteError as e: ledger = {"committed": None, "error": str(e)} - mentions = _mentions(slot, counters, shift or {}, poster, now, whoami) + mentions = _retry_mentions(slot, counters, poster, now) _write_counters(slot, counters) live = active_leases(slot) max_workers = _brief.cap_of(brief, "max-workers") @@ -2307,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): @@ -2331,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): @@ -2339,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" @@ -2358,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. @@ -2372,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: @@ -2385,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: @@ -2418,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: @@ -2440,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 @@ -2481,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 @@ -2520,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 @@ -2653,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): @@ -2671,10 +2643,10 @@ def retry_post(marker: Path, body_file: Path, poster, now: _dt.datetime) -> dict return _post_and_record(marker, rec, body_file, poster) -# --- the human, reached by @mention (#611) ----------------------------------------- +# --- the human's login, and event-comment retries ----------------------------------------- MENTIONS_DIR = "mentions" -#: The GitHub login a blocked worker @-mentions: this variable, else +#: The human's GitHub login, whose comments on the shift issue steer it: this variable, else #: `config/policy.yaml` `shift_watcher: mention_login:` — never written here. MENTION_ENV = "PYAUTO_SHIFT_MENTION" _LOGIN_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})") @@ -2696,130 +2668,30 @@ def mention_login() -> str: return login if _LOGIN_RE.fullmatch(login) else "" -def _mention_triggers(counters: dict, held: dict) -> list[tuple[str, str, str]]: - """(task, state, reason) for each worker that needs the human's @mention - on the shift issue. Since M3.5 (#645) none: a worker blocked on a person - past the grace (parked) and one whose `.done` names an issue not marked - `verdict:` both land in the questions inbox instead (`land_question`), - and the digest's one inbox line is their notice. The mention machinery - (markers, retries, the late sweep) stays for other triggers; a trigger is - read from durable state (`counters.json`, the leases), never from one - tick's events, so a tick that died before posting still mentions once.""" - # M3.5 (#645, Decision H7 a; memory `parked-questions-bulk-inbox`: never - # ask mid-run): a parked worker and a question no longer @-mention the - # human. Each lands in `questions.md` (`land_question`), and the digest - # says how many at review-at. The machinery stays for other triggers. - return [] - - -def mention_body(login: str, slot_name: str, task: str, state: str, reason: str, - counters: dict, worker: dict | None, lease: dict | None, - review_at: str) -> str: - who = f"@{login} " if login else "" - prompt = counters["picks"].get(task, {}).get("prompt") or (lease or {}).get("prompt") or task - urls = _digest.urls_of(counters["outcomes"].get(task)) - where = [f"session `{(worker or {}).get('key') or '?'}` (`claude agents` on the laptop)"] - if (lease or {}).get("worktree"): - where.append(f"worktree `{lease['worktree']}`") - lines = [f"{who}shift `{slot_name}`: the worker on `{task}` needs you — {state}.", "", - f"- reason: {reason}", f"- task: `{prompt}`", - f"- worker: {'; '.join(where)}", - f"- PR / issue: {', '.join(urls) or 'none yet'}", "", - f"The shift carries on without it; the digest at review-at {review_at} " - "lists it too. One comment per worker per state."] - if not login: - lines.append(f"(No login to mention: set `{MENTION_ENV}` or `config/policy.yaml` " - "`shift_watcher: mention_login:`.)") - return "\n".join(lines) + "\n" - - -def _note_mention(counters: dict, worker: dict | None, name: str, rec: dict) -> None: - if rec.get("state") == "posted": - counters["pushes"] += 1 - if worker is None: - return - for m in worker.setdefault("mentions", []): - if m.get("marker") == name: - m["posted"] = rec.get("state") == "posted" - return - worker["mentions"].append({"marker": name, "state": rec.get("mention_state"), - "posted": rec.get("state") == "posted"}) - - def mentions_due(slot: Path) -> bool: d = slot / MENTIONS_DIR return d.is_dir() and any(post_due(m) for m in d.glob("*.json")) def _retry_mentions(slot: Path, counters: dict, poster, now: _dt.datetime) -> list[dict]: - """Re-post every mention `gh` said failed, up to `POST_TRIES` — on a live - tick and in the late sweep alike.""" - d = slot / MENTIONS_DIR + """Re-post every needs-you event comment `gh` said failed, up to + `POST_TRIES` — on a live tick and in the late sweep alike.""" out = [] - if d.is_dir(): - for marker in sorted(d.glob("*.json")): - rec = retry_post(marker, marker.with_suffix(".md"), poster, now) - if rec is not None: - if marker.stem.startswith("event."): - # A needs-you event comment (#644): counted apart from pushes. - if rec.get("state") == "posted": - counters["event_comments"] = int(counters.get("event_comments") or 0) + 1 - out.append({"event": rec.get("event"), "post": rec["state"], - "retry": rec["tries"]}) - continue - w = last_worker(counters, rec.get("task", "")) - _note_mention(counters, w if w and w.get("key") == rec.get("worker") else None, - marker.stem, rec) - out.append({"task": rec.get("task"), "state": rec.get("mention_state"), - "post": rec["state"], "retry": rec["tries"]}) - return out - - -def _mentions(slot: Path, counters: dict, shift: dict, poster, now: _dt.datetime, - whoami=None) -> list[dict]: - """One comment on the shift's digest issue per worker per state that - needs the human (#611), claimed by marker before the post; a post `gh` - said failed is retried on the next tick, up to `POST_TRIES`.""" - d = slot / MENTIONS_DIR - out = _retry_mentions(slot, counters, poster, now) - held = leases(slot) - todo = [] - for task, state, reason in _mention_triggers(counters, held): - w = last_worker(counters, task) - key = (w or {}).get("key") or task - name = re.sub(r"[^A-Za-z0-9_.-]", "_", f"{task}.{state}.{key}") - if not (d / f"{name}.json").exists(): - todo.append((task, state, reason, w, key, name)) - if not todo: - return out - login = mention_login() - if login: - # Once per shift: who the comments post as. The human's own login - # gets no notification for its own comment (#611 review). - _poster_login(counters, whoami) - if login: - counters["mention_login"] = login - for task, state, reason, w, key, name in todo: - marker = d / f"{name}.json" - d.mkdir(parents=True, exist_ok=True) - body = d / f"{name}.md" - body.write_text(mention_body(login, slot.name, task, state, reason, counters, w, - held.get(task), shift.get("review_at", "?")), - encoding="utf-8") - rec = post_once(marker, shift.get("issue", ""), body, poster, now, - task=task, mention_state=state, worker=key) - if rec is None: - continue - _note_mention(counters, w, name, rec) - out.append({"task": task, "state": state, "post": rec["state"], "retry": 1}) + for marker in sorted((slot / MENTIONS_DIR).glob("event.*.json")): + rec = retry_post(marker, marker.with_suffix(".md"), poster, now) + if rec is not None: + if rec.get("state") == "posted": + counters["event_comments"] = int(counters.get("event_comments") or 0) + 1 + out.append({"event": rec.get("event"), "post": rec["state"], + "retry": rec["tries"]}) 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 @@ -2832,19 +2704,17 @@ def _mentions(slot: Path, counters: dict, shift: dict, poster, now: _dt.datetime #: 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. @@ -2940,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: @@ -3082,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 @@ -3126,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( @@ -3205,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") @@ -3217,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]) @@ -3252,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 "", @@ -3281,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 @@ -3317,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:` @@ -3383,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 @@ -3458,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, [])): @@ -3488,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" @@ -3553,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 [] @@ -3664,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") @@ -3699,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 @@ -3729,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() @@ -3789,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 {} @@ -3846,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 @@ -3899,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) @@ -3938,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: @@ -3962,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. @@ -3983,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) @@ -4001,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, @@ -4017,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 @@ -4049,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) @@ -4068,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 @@ -4095,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) @@ -4130,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 @@ -4148,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"))) @@ -4169,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) @@ -4177,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 @@ -4202,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() @@ -4212,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") @@ -4250,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], @@ -4270,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 '?'})") @@ -4295,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": []}) @@ -4305,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) @@ -4338,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: @@ -4361,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") @@ -4380,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): @@ -4395,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 [] @@ -4415,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): @@ -4428,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) @@ -4438,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 [] @@ -4466,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( @@ -4491,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] @@ -4509,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 " @@ -4529,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] @@ -4554,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": @@ -4576,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 @@ -4638,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: @@ -4654,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) @@ -4665,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 "") @@ -4683,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) @@ -4715,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 @@ -4742,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 @@ -4755,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"))) @@ -4777,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", {})) @@ -4807,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: @@ -4835,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" @@ -4859,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, @@ -4873,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"]) @@ -4887,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" @@ -4989,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: @@ -5007,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"] @@ -5050,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 ab469fca..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` @@ -46,7 +44,6 @@ import subprocess from pathlib import Path -STATUSES = ("ok", "obsolete", "unknown") VERIFIED_KEY = "Verified" #: Extensions that make a backticked token a path even without a `/`. diff --git a/agents/conductors/batch/_questions.py b/agents/conductors/batch/_questions.py index fba6a87d..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 "" @@ -291,129 +291,3 @@ def inbox_line(counters: dict, slot_name: str, mind=None, origin=None) -> str: line += f", {open_n} open in all" link = dashboard_link(mind) if mind is not None else "" return line + (f" — {link}" if link else "") + "." - - -# --- the one-off backfill (Build B, step 1) -------------------------------------- - -def _origin_path(mind, prompt: str, ref: str = "origin/main", run=None) -> str: - """Where `prompt` is on Mind origin/main now: itself, else `active/`, - else "" (completed or retired).""" - run = run or subprocess.run - for cand in (prompt, f"active/{Path(prompt).name}"): - try: - res = run(["git", "-C", str(mind), "cat-file", "-e", f"{ref}:{cand}"], - capture_output=True, text=True, timeout=30) - except (OSError, subprocess.SubprocessError): - return "" - if res.returncode == 0: - return cand - return "" - - -def _done_at(slot: Path, task: str) -> str: - """When the watcher reaped `task` as done (its tick's `at`), from tick.log.""" - try: - lines = (slot / "tick.log").read_text(encoding="utf-8", errors="replace").splitlines() - except OSError: - return "" - for line in lines: - try: - t = json.loads(line) - except ValueError: - continue - if any(isinstance(e, dict) and e.get("task") == task - and e.get("event") in ("done", "parked") for e in t.get("reaped") or []): - return (t.get("at") or "")[:16] + "Z" if t.get("at") else "" - return "" - - -def _proof_ask(slot: Path, task: str, issue: str) -> str: - """The proof packet's sentence that best states the question, for the - lead's review of the backfill only (the watcher itself never guesses): one - with a `?`, else one that asks for a choice (choose, decide, which, - whether), else one that says it parked on the issue; the no-sidecar ask - when none does. Issue links read "the issue".""" - try: - text = (slot / "proofs" / f"{task}.md").read_text(encoding="utf-8", errors="replace") - except OSError: - return NO_SIDECAR_ASK - body = " ".join(re.sub(r"^-\s+[a-z][a-z /-]*:\s*", "", ln.strip()) - for ln in text.splitlines() if ln.strip() and not ln.startswith("#")) - body = re.sub(re.escape(issue) + r"(?:#\S*)?", "the issue", body) - sentences = re.split(r"(?<=[.!?])\s+", body) - for test in (lambda x: "?" in x, - lambda x: re.search(r"\b(choose|decide|which|whether)\b", x, re.I), - lambda x: "the issue" in x and re.search(r"question|park", x, re.I)): - hit = next((x for x in sentences if test(x)), None) - if hit: - return sanitise(hit, ASK_MAX) - return NO_SIDECAR_ASK - - -def _record_issue(mind, slot_name: str) -> str: - try: - text = (Path(mind) / "batches" / f"{slot_name}.md").read_text(encoding="utf-8") - except OSError: - return "" - m = re.search(r"^- issue:[ \t]*(https://\S+)", text, re.M) - return m.group(1) if m else "" - - -def backfill(home: Path, mind, origin: dict | None = None) -> list[str]: - """`questions_edit.py add` lines for every task an earlier shift left - parked and still held today (the watcher's own `parked_elsewhere`, as if a - new shift were planning), one per question it parked on, oldest shift - first. Prints only — the lead reviews, then runs them. A task whose prompt - is no longer in `draft/` or `active/` on Mind origin/main, or whose - question is already in the inbox, is a `#` comment line instead.""" - import shlex - import _orchestrator as orch # noqa: E402 — deferred: it imports this module - home = Path(home) - held = orch.parked_elsewhere(home / ".backfill-probe") - origin = read_origin(mind) if origin is None else origin - slots = sorted(d for d in home.iterdir() if d.is_dir() - and (d / orch.COUNTERS_FILE).is_file()) if home.is_dir() else [] - rows = [] - for task in held: - # The last slot that parked it is the one whose hold stands. - for d in reversed(slots): - c = orch._safe_counters(d) or {} - o = (c.get("outcomes") or {}).get(task) - if (isinstance(o, dict) and o.get("questions")) or task in (c.get("parked") or []): - break - else: - continue - o = (c.get("outcomes") or {}).get(task) or {} - prompt = ((c.get("picks") or {}).get(task) or {}).get("prompt") or "" - worker = next((w.get("key") for w in reversed(c.get("workers") or []) - if w.get("task") == task), "") or "unknown" - if o.get("questions"): - asks = [(url, "question", _proof_ask(d, task, url)) for url in o["questions"]] - else: - asks = [(_record_issue(mind, d.name), "blocked", - f"the worker stopped at a prompt nobody answered (session {worker})")] - rows.append((d.name, task, prompt, worker, _done_at(d, task) or d.name, asks)) - out = [f"# questions backfill: {len(rows)} held task(s) in {home} — review, then run " - "each line from a temporary Mind worktree on origin/main"] - for shift, task, prompt, worker, asked, asks in sorted(rows): - now = _origin_path(mind, prompt) if prompt else "" - if not now: - out.append(f"# skipped: {task} (shift {shift}) — its prompt {prompt or '?'} is " - "no longer in draft/ or active/ on Mind origin/main; nothing to resume") - continue - for issue, kind, ask in asks: - if not issue: - out.append(f"# skipped: {task} (shift {shift}) — no issue to file it on") - continue - have = [e["id"] for e in (origin or {}).get(task, []) if e.get("shift") == shift - and e.get("issue") == issue] - if have: - out.append(f"# skipped: {task} (shift {shift}) — already in the inbox as " - + ", ".join(have)) - continue - out.append(" ".join(["python3 scripts/questions_edit.py add", - "--task", shlex.quote(now), "--issue", shlex.quote(issue), - "--kind", kind, "--ask", shlex.quote(ask), - "--shift", shlex.quote(shift), "--asked", shlex.quote(asked), - "--worker", shlex.quote(worker)])) - return out 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 e5d1e5e3..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 @@ -44,8 +41,6 @@ from _steer import read_queue_entries WORKER = "readiness pass" -GATES = ("no-next-phase", "looks-shipped", "obsolete", "claimed", "unattended", - "human-required", "blocked-by", "no-lane") NOT_FILED_KIND = "Mind has no `ruling` inbox kind yet (PyAutoBrain#671)" _KINDS_RE = re.compile(r"^QUESTION_KINDS\s*=\s*\(([^)]*)\)", re.M) @@ -302,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) @@ -356,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: @@ -504,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 2ee2082c..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: @@ -14,13 +15,9 @@ box that said "3h ago" would be drift on every re-render of an unchanged tree, and `dashboard --check` would report it as such. -The vocabulary (`RECORD_KEY`, `RULING_WORDS`, `PENDING_RE`) lives here and +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 @@ -43,13 +40,6 @@ #: `_cortex.py`'s reader so all three organs read one record the same way. RECORD_KEY = re.compile(r"^- ([a-z][a-z0-9-]*):(?:\s+(.*?))?\s*$") -#: Outcome tokens a human (or an earlier collect) already ruled with. A record -#: line opening with one of these is a VERDICT, and `--apply` leaves it alone. -RULING_WORDS = {"DELIVERED", "NOT-DELIVERED", "FAILED", "MERGED", "PARKED", - "CARRIED", "SUSPECT", "REJECTED", "ACCEPTED", "UNREVIEWED", - "STRUCTURE-OK", "LEAVE-TO-FINISH", "TWEAK", "DEFER", "PENDING", - "HEALTHY", "MERGE", "REJECT", "DROP", "DROPPED", "RERUN", - "ACCEPT"} #: An outcome that says the member had not finished when the record was #: written. These are the words the ledger actually uses (`REFRESHED … still @@ -112,29 +102,9 @@ def _head(text: str, limit: int = 72) -> str: return head if len(head) <= limit else head[:limit - 1].rstrip() + "…" -def _first_word(text: str) -> str: - words = (text or "").split() - return words[0].strip("(,.").upper() if words else "" - - -def freeze_line(rec: dict | None) -> str: - """The Heart freeze flag as one line — `""` when nothing is frozen. - - `rec` is PyAutoHeart's own reading (`pyauto-heart freeze --show --json`, or - the `freeze.json` sidecar read straight off disk). Heart owns the flag and - is its only writer; this is the Brain-side copy of the *wording*, kept - byte-identical to `PyAutoHeart/heart/freeze.py::render_line` so the batch - box, `vitals` and `/prm` all say the same sentence. `expired` reads as - thawed, exactly as Heart reads it. - """ - if not rec or rec.get("state") != "active": - return "" - return f"FROZEN: {rec.get('reason', 'unspecified')} until {rec.get('until', '?')}" - - def dev_status(slot: str, keys: dict, members: list, review_exists: bool, - pages: str, freeze: str = "") -> dict | None: - """The Mind's (development) reading — today's behaviour, unchanged. + pages: str) -> dict | None: + """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 @@ -150,27 +120,17 @@ def dev_status(slot: str, keys: dict, members: list, review_exists: bool, elif PENDING_RE.search(outcome): state, detail = IN_PROGRESS, _head(outcome) else: - # A ruling word (`RULING_WORDS`) or a collect health reading — + # A ruling word or a health reading — # either way the member ended and a human can read it. state, detail = AWAITING, _head(outcome) rows.append({"slug": m.get("slug", ""), "state": state, "detail": detail}) return _status(slot, "dev", keys, rows, - reviewable=bool(_one(keys, "collected")), pages=pages, - freeze=freeze) + reviewable=bool(_one(keys, "collected")), pages=pages) def _status(slot: str, kind: str, keys: dict, rows: list, reviewable: bool, - pages: str, freeze: str = "") -> dict: - """`freeze` is a caller-supplied FACT, and defaults to nothing on purpose. - - The flag lives in the dev box's `~/.pyauto-heart/`, which is machine state - and not in any checkout — so a surface that renders a **committed** - artifact must not pass it. The Mind's dashboard is regenerated in CI, where - that state does not exist, and a freeze folded into the page would read as - dashboard drift on the next `--check`. `batch collect`, which runs on the - box that holds the state and prints to a terminal, passes it. - """ + pages: str) -> dict: return { "slot": slot, "kind": kind, @@ -181,9 +141,8 @@ def _status(slot: str, kind: str, keys: dict, rows: list, reviewable: bool, "reviewable": reviewable, "url": review_url(pages, slot) if reviewable else "", "packet": f"batches/packets/{slot}.html", - "freeze": freeze, # 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), } @@ -312,8 +271,6 @@ def render_html(st: dict | None, last: dict | None = None) -> str: f'

    ({esc(text)}{link})

    ') H = [f'

    Shift ({esc(st["slot"])} — ' f"{esc(_counts(st))})

    "] - if st.get("freeze"): - H.append(f'

    {esc(st["freeze"])}

    ') text, url = _live_parts(st.get("live") or "") url = url or st.get("issue", "") if text or url: @@ -350,8 +307,6 @@ def render_md(st: dict | None, last: dict | None = None) -> str: text, url = _quiet(st, last) return "**Shift**\n\n_(" + text + (f" · [{_issue_label(url)}]({url})" if url else "") + ")_" L = [f"**Shift** ({st['slot']} — {_counts(st)})", ""] - if st.get("freeze"): - L += [st["freeze"], ""] text, url = _live_parts(st.get("live") or "") url = url or st.get("issue", "") if text or url: 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 — `## .