diff --git a/AGENTS.md b/AGENTS.md index 9b7109d7..8fdc5f6e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -133,7 +133,7 @@ the `/` slash commands. | Verb | Purpose | Entrypoint | |------|---------|------------| | `intake` | Conceive a task: turn raw input into a formal, headed PyAutoMind prompt (files it; never starts dev) | `bin/pyauto-brain intake` | -| `batch` | Compose one unattended shift: the BatchDecision, planned against the slot's REVIEW-MINUTE budget rather than a task count — proposes, never dispatches | `bin/pyauto-brain batch` | +| `batch` | Compose one unattended shift: the BatchDecision, planned against the slot's REVIEW-MINUTE budget rather than a task count — proposes, never dispatches; 'batch collect' scores what came back into the review packet and stamps the batch record | `bin/pyauto-brain batch` | | `community` | The ears — the organism's receptive function: scan/triage user-filed GitHub issues + PRs and review requests across the repos; drafts stay human-gated, dev work routes via start_dev_for_user (never posts) | `bin/pyauto-brain community` | | `feature` | Reason over PyAutoMind feature tasks: select, size, phase, plan for start_dev | `bin/pyauto-brain feature` | | `bug` | The immune system: classify a bug/regression/Heart finding, locate the fix, plan the repair | `bin/pyauto-brain bug` | diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 04faa912..1a9f169b 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -103,9 +103,28 @@ pyauto-brain batch plan # the BatchDecision for this lane 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 --evidence ev.json --apply # the one form that writes +pyauto-brain batch collect --out report.md --json ``` -Stdlib-only, offline, writes nothing. +`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) @@ -150,13 +169,16 @@ what a dispatcher actually needs before writing one. **At `review-at:` (or whenever they actually sit down):** -8. **Collect** (2026-08-31): science members — `hpc/sync pull` per project, - so every pointer in the packet is a local path (remote-only pointers exist - only where the pull cannot fetch by design, and say so; a mobile session - cannot pull and says "run collect from the laptop"). Dev members — the PR - number and whether every check ran green; no green-CI PR, not - `delivered:`. Fill the PENDING entries, stamp the page `refreshed:` — this - normally happens while the human is already reading the finished members. +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 members stay by hand until the Cortex kind lands (phase 5): + `hpc/sync pull` per project, so every pointer in the packet is a local path + (remote-only pointers exist only where the pull cannot fetch by design, and + say so; a mobile session cannot pull and says "run collect from the + laptop"). 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`, @@ -174,15 +196,17 @@ what a dispatcher actually needs before writing one. 11. Plan the next batch, and declare the next `review-at:`. **The one leg you must not skip.** A batch launch requires the independent -adversary (`AUTONOMY.md` leg 5). Until `batch collect` exists, run it by hand -before reading a PR: +adversary (`AUTONOMY.md` leg 5). Run it before reading a PR: ``` pyauto-brain review --task --witness "" --adversary ``` in a session **using a different model from the one that wrote the branch**. A -self-run adversary leg is an absent leg, not a weak one. +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. **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 @@ -191,10 +215,124 @@ 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 ran +under a model that is not the branch's author. **A self-run adversary leg is an +absent leg, not a weak one** (`AUTONOMY.md` leg 5), so an equal or missing +`author_model` is FAIL, not PASS. + +### 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", + "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"}}} +``` + +`witness.holds` is tri-state: `true` PASS, `false` FAIL, absent UNOBSERVABLE. + +### 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`, and `packet:`. 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. + +### The close leg + +A review that has landed closes the batch. 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 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` is the kind that ships. The science kind (pulled runs, the six legs of +`cortex collect`, rulings written into the project's own ledger) is Cortex +phase 5's, and it plugs in there rather than growing a second collect. + ## Not built yet -`slice` (the decomposition pass doctrine has named since inception) and -`collect` (the review packet) are the conductor's other two verbs — see the -epic ledger, `PyAutoMind/draft/feature/pyautomind/two_slot_batching_epic.md`. -`plan` is useful on its own: run it in a slot and dispatch by tapping the -dashboard's existing chips. +`slice` — the decomposition pass doctrine has named since inception — is the +conductor's one remaining verb; see the epic ledger, +`PyAutoMind/draft/feature/pyautomind/two_slot_batching_epic.md`. `plan` and +`collect` stand on their own in the meantime: plan a slot, dispatch by tapping +the dashboard's existing chips, collect what comes back. diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 74d131aa..a1c37b27 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -29,9 +29,14 @@ from __future__ import annotations import argparse +import datetime as _dt +import html import json +import re import shutil +import subprocess import sys +import tempfile from pathlib import Path BRAIN = Path(__file__).resolve().parents[3] @@ -312,9 +317,1606 @@ 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 the Cortex conductor's, kept +# byte-identical so both organs read one record the same way; `MEMBER_RE` is +# NOT — see `parse_member`. +RECORD_KEY = re.compile(r"^- ([a-z][a-z0-9-]*):(?:\s+(.*?))?\s*$") +MEMBER_RE = re.compile(r"^ - (?P[^:]+): (?P.+)$") + +#: 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: +#: the am record's REJECTED/ACCEPTED members are the ledger of a review that +#: happened, and overwriting them with a fresh machine reading would erase it. +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 +#: carried`, `CARRIED to the next batch`), not a vocabulary invented here. +PENDING_RE = re.compile(r"\b(RUNNING|CARRIED|IN FLIGHT|REFRESHED|PENDING|" + r"DISPATCHED)\b", re.I) + +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+") + + +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") + + +def _dash(line: str) -> str: + """` -- ` typed for an em dash. Records are hand-written as often as not.""" + return line.replace(" -- ", " — ") + + +def parse_member(raw: str) -> dict | None: + """` - : — — — `, or None. + + Deliberately not the Cortex conductor's `MEMBER_RE`: its `(?P\\S+)$` + fails on every real dev line (all nine outcomes in the 2026-08-31-pm record + contain spaces) and its `(?P\\S+)` fails on the two science lines, + 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") + + +def newest_slot(mind: Path) -> str: + """The last record by NAME, which is lexical: `-night` sorts before `-pm` + on the same date, so a night slot collected after a pm one is not the + newest by this reckoning. `--slot` is the escape, and the reason it exists. + """ + records = batch_records(mind) + 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. + + A prompt is written under `draft/`, issued into `active/` and retired into + `complete///`; the record names where it was AT DISPATCH. All + three are tried, by basename, because a member collected after its own + close-out would otherwise lose its question and its witness. + """ + if not path: + return None + direct = mind / path + if direct.is_file(): + return direct + name = Path(path).name + issued = mind / "active" / name + if issued.is_file(): + return issued + 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*$") + + +def _active_entry(slug: str, body: str) -> dict: + keys: dict[str, list[str]] = {} + current = None + for line in body.split("\n"): + m = ACTIVE_KEY_RE.match(line) + if m: + current = m.group(1) + keys.setdefault(current, []) + value = (m.group(2) or "").strip() + if value and value != "|": + keys[current].append(value) + continue + if current and (line.startswith(" - ") or line.startswith(" ")): + keys[current].append(line.strip().lstrip("- ").strip()) + elif line.strip(): + current = None + prompt = keys.get("prompt") or [""] + issue = ISSUE_URL_RE.search(body) + return {"slug": slug, "keys": keys, "text": body, + "prompt": Path(prompt[0]).name if prompt[0] else "", + "prs": sorted({m.group(0) for m in PR_URL_RE.finditer(body)}), + "issue": issue.group(0) if issue else "", + "status": (keys.get("status") or [""])[0]} + + +def read_active(mind: Path) -> dict: + """`active.md` as `{slug: entry}`. PR urls are harvested from the whole + entry text — they are spelled `library-pr:`, `workspace-pr:` and `prs:` in + different entries, and a reader keyed to one of those spellings sees a + third of them.""" + try: + text = (mind / "active.md").read_text(encoding="utf-8", errors="replace") + except OSError: + return {} + out: dict[str, dict] = {} + slug, buf = None, [] + for line in text.split("\n"): + if line.startswith("## "): + if slug: + out[slug] = _active_entry(slug, "\n".join(buf)) + slug, buf = line[3:].strip(), [] + elif slug is not None: + buf.append(line) + if slug: + out[slug] = _active_entry(slug, "\n".join(buf)) + return out + + +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") + +GH_FIELDS = ("number,url,state,additions,deletions,changedFiles,mergeable," + "merged,statusCheckRollup") + + +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 _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 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("merged")), + "checks": _checks_from_rollup(data.get("statusCheckRollup")), + }) + 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 "") + if not model or not author or model == author: + # AUTONOMY.md leg 5, verbatim in intent: the leg is a reading by a + # DIFFERENT model from the one that wrote the diff. + 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")) + return PASS, f"{model} vs author {author}: {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. +HEALTHS = ("FAILED", "NOT-DELIVERED", "SUSPECT", "HEALTHY", "PENDING", "MERGED") +HEALTH_SEV = {"FAILED": "failed", "NOT-DELIVERED": "failed", + "SUSPECT": "suspect", "HEALTHY": "healthy", + "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 + + +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. The Cortex's phase-5 + `cortex` kind claims a member whose path is a `phases/…` file; nothing else + may claim one, so the default is never a guess.""" + 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 lets the Cortex register +#: a `cortex` kind without either organ learning the other's vocabulary. +KINDS = {"dev": (score_dev, dev_blocks, None)} + + +# --------------------------------------------------------- collect() ------- +def collect(mind: Path, slot: str, *, evidence: dict | None = None, + kinds: dict | None = None) -> 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. + """ + kinds = kinds or KINDS + record_path = mind / "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, "slot": slot, "active": read_active(mind), + "evidence": evidence or {}, "notes": notes, "kinds": kinds} + + 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) + 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)) + review_path = mind / "batches" / "reviews" / f"{slot}.md" + review = (read_review(review_path.read_text(encoding="utf-8", + errors="replace")) + if review_path.is_file() else None) + return { + "slot": slot, "mind": mind, "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"], + "rulings": [(s["slug"], _ruling_line(s)) for s in scored], + "unparsable": rec["unparsable"], + "stamp": "", + } + + +def _ruling_line(s: dict) -> str: + """The one-line "why this needs you" for the rulings list.""" + for k in LEGS: + if s["legs"][k][0] == FAIL: + return f"{s['health']} — {LEG_TITLES[k]}: {s['legs'][k][1]}" + if s["pending"]: + return "PENDING — not finished at collect; refreshed during your read" + for k in LEGS: + if s["legs"][k][0] == UNOBSERVABLE: + return f"{s['health']} — {LEG_TITLES[k]}: {s['legs'][k][1]}" + return f"{s['health']} — {s['legs']['green'][1]}; merge / tweak / reject" + + +# ------------------------------------------------------- report and JSON --- +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}", ""] + 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 _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") 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}") + 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. + """ + sev = HEALTH_SEV.get(s["health"], "suspect") + classes = "member pending" if s["pending"] else "member" + chip_cls = "chip-pending" if s["pending"] else 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"])}', + f' ', + '
', + '
', + '
'] + 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

', + f'
'] + for value, label in s["review_chips"]: + L.append(f' ') + 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) + + +def _sidenav(d: dict) -> str: + L = [''] + return "\n".join(L) + + +def _members_js(d: dict) -> str: + members = [{"id": s["id"], "slug": s["slug"], "health": s["health"]} + 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") + home = _mind_home(d["mind"]) + for token, value in ( + ("%%MEMBERS_JSON%%", payload), + ("%%SLOT%%", d["slot"]), + ("%%PACKET_PATH%%", f"PyAutoMind/batches/packets/{d['slot']}.html"), + ("%%REVIEW_PATH%%", f"batches/reviews/{d['slot']}.md"), + ("%%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)) + n, total = d["delivered"] + L = [head, '
    ', '', '
    ', + f'

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

    ', + f'

    Slot Review — {_e(slot)}

    ', + f'

    {n} of {total} ended member(s) delivered on the ' + 'evidence — a PR with a non-empty diff and checks that ran. Choose a ' + 'decision and leave a note on each member, then Submit ' + 'review at the bottom; the review lands in ' + f'batches/reviews/{_e(slot)}.md 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), + '', '', + '
    ', '', + '', _sidenav(d), + '', '', + '
    ', '', + ''] + for s in d["members"]: + L += [render_member_section(s), ''] + L += ['', '', + '
    ', '
    ', '', + '
    ', + '
    ', '', + '
    ', + f'

    Ruled 0 of ' + f'{len(d["members"])} · decisions 0 of {len(d["members"])}

    ', + ' ', + '
    ', '', + '', '', + '', _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"), + ) + 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.""" + for k in LEGS: + if s["legs"][k][0] == FAIL: + return _short(f"{LEG_TITLES[k]}: {s['legs'][k][1]}", 160) + if s["pending"]: + return _short(s["outcome"] or "still in flight", 160) + for k in LEGS: + if s["legs"][k][0] == UNOBSERVABLE: + return _short(f"{LEG_TITLES[k]}: {s['legs'][k][1]}", 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 + + +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) + 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) + inserts.append(f"- refreshed: {stamp} — collect " + f"({len(d['members'])} member(s))") + at = _insert_anchor(rec) + lines[at:at] = inserts + return "\n".join(lines) + + +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") + + packet = mind / "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. + notes.append("review submitted — the packet is never rewritten after a " + f"review; batches/reviews/{d['slot']}.md is the record now") + return notes + existing = (packet.read_text(encoding="utf-8", errors="replace") + if packet.is_file() else None) + page, pnotes = packet_html(d, existing) + packet.parent.mkdir(parents=True, exist_ok=True) + packet.write_text(page, encoding="utf-8") + notes += pnotes + notes.append(("packet refreshed" if existing is not None + else "packet written") + f": batches/packets/{d['slot']}.html") + return notes + + +def _rehearse_record(mind: Path, before: str, after: str) -> list: + """Re-read the rewritten record from a throwaway copy of `batches/` before + it is written for real. The Cortex's collect does the same, for the same + reason: a partial write of a ledger has no way back.""" + tmp = Path(tempfile.mkdtemp(prefix="batch-collect-")) + try: + copy = tmp / "batches" + shutil.copytree(mind / "batches", copy, symlinks=True) + rehearsal = copy / "rehearsal.md" + rehearsal.write_text(after, encoding="utf-8") + again = read_record(rehearsal.read_text(encoding="utf-8")) + except OSError as e: + return [f"the rehearsal copy could not be made ({e})"] + finally: + shutil.rmtree(tmp, ignore_errors=True) + was = read_record(before) + problems = [] + got = {m["slug"] for m in again["members"]} + for m in was["members"]: + if m["slug"] not in got: + problems.append(f"member `{m['slug']}` no longer parses") + for key in was["keys"]: + if key not in again["keys"]: + problems.append(f"key `{key}` disappeared") + if len(again["unparsable"]) > len(was["unparsable"]): + problems.append("a member line stopped parsing") + return problems + + +# --------------------------------------------------------- the close leg --- +REVIEW_HEAD_RE = re.compile(r"^## (?P.+?)(?:\s+—\s+(?P[A-Z-]+))?$") +REVIEW_KEY_RE = re.compile(r"^- (decision|ruled|note): (.*)$") + + +def read_review(text: str) -> dict: + """`batches/reviews/.md` — what the human ruled, verbatim. + + Read, reported, and never enacted: `batches/reviews/AGENTS.md` gives the + close-out to the orchestrator, and a review never executes its own + follow-ups. + """ + keys: dict[str, str] = {} + members: dict[str, dict] = {} + slug = None + for raw in text.split("\n"): + line = _dash(raw) + head = REVIEW_HEAD_RE.match(line) + if head: + name = head.group("slug").strip() + if name.lower().startswith("follow-up"): + slug = None + continue + slug = name + members[slug] = {"health": head.group("health") or "", + "decision": "", "ruled": "", "note": []} + continue + if slug is None: + m = RECORD_KEY.match(line) + if m: + keys[m.group(1)] = (m.group(2) or "").strip() + continue + m = REVIEW_KEY_RE.match(line) + if m: + if m.group(1) == "note": + members[slug]["note"].append(m.group(2).strip()) + else: + members[slug][m.group(1)] = m.group(2).strip() + elif line.strip() and not line.startswith(""); + lines.push(""); + return lines.join("\n"); + } + + var modal = document.getElementById("submit-modal"); + var preview = document.getElementById("md-preview"); + var ghLink = document.getElementById("btn-github"); + var ghHint = document.getElementById("gh-hint"); + var copyBtn = document.getElementById("btn-copy"); + var dlBtn = document.getElementById("btn-download"); + var currentMd = ""; + + function openModal() { + currentMd = buildMarkdown(); + if (preview) { preview.textContent = currentMd; } + if (ghLink) { + var url = GITHUB_NEW + "?filename=" + encodeURIComponent(REVIEW_PATH) + + "&value=" + encodeURIComponent(currentMd); + /* GitHub's prefilled-new-file URL is the affordance that lands the review + * without a copy-paste; past ~7,500 chars it silently truncates, which + * would commit a review missing its last members. */ + if (!GITHUB_NEW) { + /* The renderer found no GitHub home for this Mind (no origin remote, + * no README link) and names none itself, so there is nothing to link. */ + ghLink.removeAttribute("href"); + ghLink.classList.add("is-disabled"); + ghLink.setAttribute("aria-disabled", "true"); + if (ghHint) { + ghHint.textContent = "No GitHub home resolved for this Mind — use Copy, then paste into a new file at " + REVIEW_PATH + "."; + } + } else if (url.length > 7500) { + ghLink.removeAttribute("href"); + ghLink.classList.add("is-disabled"); + ghLink.setAttribute("aria-disabled", "true"); + if (ghHint) { + ghHint.textContent = "The review is too long for a prefilled GitHub URL — use Copy, then paste into a new file at " + REVIEW_PATH + "."; + } + } else { + ghLink.setAttribute("href", url); + ghLink.classList.remove("is-disabled"); + ghLink.removeAttribute("aria-disabled"); + } + } + if (modal) { modal.hidden = false; } + } + function closeModal() { if (modal) { modal.hidden = true; } } + + var submitBtn = document.getElementById("btn-submit"); + if (submitBtn) { submitBtn.addEventListener("click", openModal); } + var closeBtn = document.getElementById("btn-close"); + if (closeBtn) { closeBtn.addEventListener("click", closeModal); } + if (modal) { + modal.addEventListener("click", function (ev) { + if (ev.target === modal) { closeModal(); } + }); + } + document.addEventListener("keydown", function (ev) { + if (ev.key === "Escape") { closeModal(); } + }); + + function flash(btn, text) { + var old = btn.textContent; + btn.textContent = text; + window.setTimeout(function () { btn.textContent = old; }, 2000); + } + + if (copyBtn) { + copyBtn.addEventListener("click", function () { + var done = function () { flash(copyBtn, "Copied ✓"); }; + var fallback = function () { + try { + var ta = document.createElement("textarea"); + ta.value = currentMd; + ta.setAttribute("readonly", "readonly"); + ta.style.position = "fixed"; + ta.style.left = "-9999px"; + document.body.appendChild(ta); + ta.select(); + document.execCommand("copy"); + document.body.removeChild(ta); + done(); + } catch (e) { flash(copyBtn, "Copy failed — select the preview"); } + }; + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(currentMd).then(done, fallback); + } else { fallback(); } + }); + } + + if (dlBtn) { + dlBtn.addEventListener("click", function () { + try { + var blob = new Blob([currentMd], { type: "text/markdown" }); + var a = document.createElement("a"); + a.href = URL.createObjectURL(blob); + a.download = SLOT + "-review.md"; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + window.setTimeout(function () { URL.revokeObjectURL(a.href); }, 5000); + } catch (e) { flash(dlBtn, "Download blocked — use Copy"); } + }); + } + + var links = document.querySelectorAll(".sidenav a[data-nav]"); + if (links.length && "IntersectionObserver" in window) { + var map = {}; + var targets = []; + for (i = 0; i < links.length; i++) { + var key = links[i].getAttribute("data-nav"); + var el = document.getElementById(key); + if (el) { map[key] = links[i]; targets.push(el); } + } + var visible = {}; + var observer = new IntersectionObserver(function (entries) { + for (var j = 0; j < entries.length; j++) { + visible[entries[j].target.id] = entries[j].isIntersecting; + } + var active = null; + for (var k = 0; k < targets.length; k++) { + if (visible[targets[k].id]) { active = targets[k].id; break; } + } + for (var key2 in map) { + if (Object.prototype.hasOwnProperty.call(map, key2)) { + map[key2].classList.toggle("active", key2 === active); + } + } + }, { rootMargin: "-10% 0px -70% 0px", threshold: 0 }); + for (i = 0; i < targets.length; i++) { observer.observe(targets[i]); } + } +}()); diff --git a/bin/pyauto-brain b/bin/pyauto-brain index 357cffed..ec9e9235 100755 --- a/bin/pyauto-brain +++ b/bin/pyauto-brain @@ -80,7 +80,7 @@ declare -A AGENT_SCRIPT=( ) declare -A AGENT_DESC=( [intake]="Conceive a task: turn raw input into a formal, headed PyAutoMind prompt (files it; never starts dev)" - [batch]="Compose one unattended shift: the BatchDecision, planned against the slot's REVIEW-MINUTE budget rather than a task count — proposes, never dispatches" + [batch]="Compose one unattended shift: the BatchDecision, planned against the slot's REVIEW-MINUTE budget rather than a task count — proposes, never dispatches; 'batch collect' scores what came back into the review packet and stamps the batch record" [community]="The ears — the organism's receptive function: scan/triage user-filed GitHub issues + PRs and review requests across the repos; drafts stay human-gated, dev work routes via start_dev_for_user (never posts)" [feature]="Reason over PyAutoMind feature tasks: select, size, phase, plan for start_dev" [bug]="The immune system: classify a bug/regression/Heart finding, locate the fix, plan the repair" diff --git a/skills/batch/batch.md b/skills/batch/batch.md index a317563d..2ac307ed 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -104,22 +104,38 @@ In order: ## When they come back — collect, review, close (2026-08-31) -**Collect first, before the human reads anything.** - -- **Science members end at pulled results.** Step 0 is each project's - `hpc/sync pull`, so every run output the packet cites is on the laptop — - these are evolving projects the human stays in the loop on, and the loop - runs through their own disk. Every "where to look" pointer in the packet is - a **local path**; a pointer may stay remote only when the pull cannot fetch - it by design, and must say so. A mobile session cannot pull: it says "run +**Collect first, before the human reads anything.** It is one command: + +``` +bin/pyauto-brain batch collect --slot - --evidence ev.json --apply +``` + +- **Gather the evidence, then hand it over.** Collect has no GitHub of its + own. In a web session, read each member's PRs with the GitHub MCP tools + (`pull_request_read` for state and diff counts, the check rollup or + `actions_list` for the checks — `PyAutoBrain/skills/GITHUB_ACCESS.md` maps + each operation) and write them into the evidence JSON that the conductor's + `AGENTS.md` documents under "The collect recipe". On the laptop lane + `--fetch` does the same by running one `gh pr view` per PR. Run it once + without `--apply` to read the report; run it again with `--apply` to write + the packet and stamp the record. +- **What comes back is scored, not summarised.** Six legs per member (pr · + diff · checks · green · witness · adversary), one health word (FAILED · + NOT-DELIVERED · SUSPECT · HEALTHY · PENDING · MERGED), failures at the top. + A leg with no evidence is UNOBSERVABLE and never delivered — a member you + did not look up reaches the human as SUSPECT, not as clean. +- **The PENDING entries fill themselves in.** `--apply` regenerates each + member's section in place — same path, same id — and stamps the page + `refreshed:`, normally while the human is already reading the finished + members. No other member's markup is touched, so their stored notes and + chips survive. +- **Science members are still by hand** until the Cortex kind lands: step 0 is + each project's `hpc/sync pull`, so every run output the packet cites is on + the laptop — these are evolving projects the human stays in the loop on, and + the loop runs through their own disk. Every "where to look" pointer is a + **local path**; one may stay remote only when the pull cannot fetch it by + design, and must say so. **A mobile session cannot pull**: it says "run collect from the laptop" rather than emitting a remote-only packet. -- **Dev members end at a PR with CI green.** The packet states, per dev - member, the PR number and whether **every check ran and ran green** — a - member without a green-CI PR is not `delivered:`, however clean its diff. -- **Fill the PENDING entries.** The packet was written at dispatch; the - morning collect replaces each PENDING member with its readout and adds a - `refreshed:` stamp. This normally happens while the human is already - reading the finished members. **Before reading any PR from a batch, the independent adversary leg must have run** (`AUTONOMY.md` leg 5): `bin/pyauto-brain review --task --witness @@ -133,7 +149,11 @@ failures first, then anything labelled `decision-taken`, then clean. They tick, choose and annotate each member on the page and submit; the submission lands as `PyAutoMind/batches/reviews/-.md` (or they dictate the same content in-chat — both are the same review). When they say the review is done, -read that file and act on it, member by member: +run `batch collect --slot - --apply` once more: with the review +file present it **refuses to rewrite the packet** — that page is what they +ruled against — and closes the record instead (`reviewed-at:`, +`review-minutes-actual:`, `review:`). It reports their decisions and enacts +none of them; that part is yours, member by member: - **merge** — `/prm `; for a science member, write the ruling into the project's own ledger (DECISIONS, harvest table, results summary) verbatim. diff --git a/tests/test_batch_collect.py b/tests/test_batch_collect.py new file mode 100644 index 00000000..bf42ee9e --- /dev/null +++ b/tests/test_batch_collect.py @@ -0,0 +1,626 @@ +"""tests/test_batch_collect.py — the Batch Agent's collection rules. + +`batches/AGENTS.md` states the rule every test here defends: **a green session +is not a delivered task**. A member counts as delivered only with a PR that has +a non-empty diff and checks that actually ran, and a member that ends green +with no PR is reported not delivered, loudly. So most of these are refusals +too — refusals to call something delivered on evidence that does not say so, +and refusals to invent evidence that is simply not here. +""" + +from __future__ import annotations + +import importlib.util +import json +import re +import sys +from pathlib import Path + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) +_spec = importlib.util.spec_from_file_location( + "_batch_collect_under_test", + BRAIN / "agents" / "conductors" / "batch" / "_batch.py") +_batch = importlib.util.module_from_spec(_spec) +sys.modules["_batch_collect_under_test"] = _batch +_spec.loader.exec_module(_batch) + +STAMP = "2026-09-03T08:00Z" + +PROMPT = """# Add a resampling info section + +Type: bug +Target: autofit +Witness: the new section appears in search.summary and a unit test pins it + +The bottom of `search.summary` says nothing about resampling, so a run that +resampled heavily looks identical to one that did not. +""" + +ACTIVE = """# Active Tasks + +## resampling-info-summary-section +- issue: https://github.com/ExampleOrg/ExampleFit/issues/1551 +- prompt: active/resampling.md +- status: library-shipped, awaiting-merge +- library-pr: https://github.com/ExampleOrg/ExampleFit/pull/1554 + +## something-else +- prompt: active/other.md +- status: pr-open +- prs: + - https://github.com/ExampleOrg/ExampleArray/pull/9 +""" + +MEMBER = (" - resampling: draft/bug/autofit/resampling.md — glance — 3 — " + "session ended green (exit 0, cloud session, --auto)") + + +def record(*members, keys="", notes=True) -> str: + body = ["# Batch 2026-09-03 pm", "", + "- dispatched: 2026-09-03T17:40Z", + "- review-at: 2026-09-04T08:00Z", + "- lane: any", + "- review-minutes-planned: 3", + "- members:"] + body += list(members) + if keys: + body.append(keys) + if notes: + body += ["- notes: |", + " What actually happened.", + " - delivered: this line is prose, not a key", + " Nothing stalled."] + return "\n".join(body) + "\n" + + +def mini_mind(tmp_path, *members, active=ACTIVE, notes=True, keys="", + review=None) -> Path: + mind = tmp_path / "mind" + (mind / "batches" / "packets").mkdir(parents=True) + (mind / "batches" / "reviews").mkdir(parents=True) + (mind / "draft" / "bug" / "autofit").mkdir(parents=True) + (mind / "active").mkdir(parents=True) + (mind / "batches" / "2026-09-03-pm.md").write_text( + record(*(members or (MEMBER,)), keys=keys, notes=notes), + encoding="utf-8") + (mind / "batches" / "2026-09-03-am.md").write_text( + record(" - other: draft/bug/autofit/resampling.md — glance — 1 — " + "REJECTED by the human at review"), encoding="utf-8") + (mind / "draft" / "bug" / "autofit" / "resampling.md").write_text( + PROMPT, encoding="utf-8") + (mind / "active" / "resampling.md").write_text(PROMPT, encoding="utf-8") + (mind / "active.md").write_text(active, encoding="utf-8") + if review is not None: + (mind / "batches" / "reviews" / "2026-09-03-pm.md").write_text( + review, encoding="utf-8") + return mind + + +def pr(**over) -> dict: + row = {"repo": "ExampleOrg/ExampleFit", "number": 1554, + "url": "https://github.com/ExampleOrg/ExampleFit/pull/1554", + "state": "OPEN", "additions": 86, "deletions": 12, + "changed_files": 3, "mergeable": "MERGEABLE", "merged": False, + "checks": [{"name": "tests", "status": "completed", + "conclusion": "success"}]} + row.update(over) + return row + + +def evidence(**over) -> dict: + row = {"prs": [pr()], + "witness": {"holds": True, "evidence": "the new test is green"}, + "adversary": {"ran": True, "model": "gpt-5.1", + "author_model": "claude-opus-4", "verdict": "CLEAN"}} + row.update(over) + return {"resampling": row} + + +def one(d, slug="resampling"): + return next(s for s in d["members"] if s["slug"] == slug) + + +# ------------------------------------------------------ reading the record -- +def test_a_member_outcome_may_contain_the_separator(tmp_path): + """Every one of the nine dev outcomes in the 2026-08-31-pm record contains + spaces and several contain the separator itself. Splitting with maxsplit=3 + keeps the outcome whole; the Cortex conductor's `(?P\\S+)$` does + not, which is why this module does not reuse it.""" + line = (" - resampling: draft/bug/autofit/resampling.md — glance — 3 — " + "DELIVERED (ExampleFit#1554 — 4/4 checks green, mergeable clean)") + row = _batch.parse_member(line) + assert row["slug"] == "resampling" + assert row["path"] == "draft/bug/autofit/resampling.md" + assert row["tier"] == "glance" and row["minutes"] == "3" + assert row["outcome"].endswith("mergeable clean)") + assert "—" in row["outcome"] + + +def test_an_unparsable_member_line_is_a_note_not_a_crash(tmp_path): + """The two science members of the 2026-08-31-pm record have a sentence + where the path goes. Reporting them is right; refusing to collect the slot + because of them is not.""" + science = (" - subhalo-wave: PyAutoCortex phases/subhalo_validation/ " + "(four phases, one per lens) — judge — 15 — REFRESHED, carried") + mind = mini_mind(tmp_path, MEMBER, science) + d = _batch.collect(mind, "2026-09-03-pm") + assert [s["slug"] for s in d["members"]] == ["resampling"] + assert any("does not read as a member line" in n for n in d["notes"]) + assert any("subhalo-wave" in n for n in d["notes"]) + + +def test_the_em_dash_may_be_typed_as_two_hyphens(tmp_path): + row = _batch.parse_member( + " - resampling: draft/bug/autofit/resampling.md -- glance -- 3 -- " + "DELIVERED (ExampleFit#1554)") + assert row and row["tier"] == "glance" and row["minutes"] == "3" + + +def test_a_notes_block_is_never_read_as_members(tmp_path): + """`- notes: |` carries prose that looks exactly like the ledger — the + fixture's block contains a `- delivered:` line on purpose.""" + mind = mini_mind(tmp_path) + rec = _batch.read_record( + (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8")) + assert [m["slug"] for m in rec["members"]] == ["resampling"] + assert "notes" in rec["keys"] + assert "delivered" not in rec["keys"] + + +# --------------------------------------------------------------- the legs -- +def test_no_pr_is_not_delivered_however_green_the_session(tmp_path): + """The record's own first rule. A session's green status means it exited + without an infrastructure error, nothing more.""" + mind = mini_mind(tmp_path) + d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence(prs=[])) + assert one(d)["health"] == "NOT-DELIVERED" + assert d["not_delivered"] == ["resampling"] + assert _batch.main(["collect", "--mind", str(mind), "--slot", + "2026-09-03-pm"]) == 1 + + +def test_an_empty_diff_is_not_delivered(tmp_path): + mind = mini_mind(tmp_path) + d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( + prs=[pr(additions=0, deletions=0, changed_files=0)])) + assert one(d)["health"] == "NOT-DELIVERED" + assert one(d)["legs"]["diff"][0] == _batch.FAIL + + +def test_checks_that_never_ran_are_not_delivered_but_a_red_check_failed(tmp_path): + """Two different findings that a single "checks bad" verdict would blur: + nothing ran (the work never reached CI) versus something ran and went + red (the work is wrong).""" + mind = mini_mind(tmp_path) + never = _batch.collect(mind, "2026-09-03-pm", + evidence=evidence(prs=[pr(checks=[])])) + assert one(never)["health"] == "NOT-DELIVERED" + assert "never ran" in one(never)["legs"]["checks"][1] + red = _batch.collect(mind, "2026-09-03-pm", evidence=evidence(prs=[pr( + checks=[{"name": "tests", "status": "completed", + "conclusion": "failure"}])])) + assert one(red)["health"] == "FAILED" + assert "tests" in one(red)["legs"]["green"][1] + + +def test_a_self_run_adversary_is_an_absent_leg(tmp_path): + """AUTONOMY.md leg 5, verbatim: a self-run adversary leg is an absent leg, + not a weak one, and recording it as run is a false ledger row.""" + mind = mini_mind(tmp_path) + d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( + adversary={"ran": True, "model": "claude-opus-4", + "author_model": "claude-opus-4", "verdict": "CLEAN"})) + verdict, why = one(d)["legs"]["adversary"] + assert verdict == _batch.FAIL + assert "absent leg, not a weak one" in why + + +def test_a_missing_witness_is_unobservable_and_makes_the_member_suspect(tmp_path): + (tmp_path / "mind").mkdir(parents=True, exist_ok=True) + mind = mini_mind(tmp_path) + (mind / "draft" / "bug" / "autofit" / "resampling.md").write_text( + PROMPT.replace("Witness: the new section appears in search.summary " + "and a unit test pins it\n", ""), encoding="utf-8") + (mind / "active" / "resampling.md").unlink() + d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence()) + assert one(d)["legs"]["witness"][0] == _batch.UNOBSERVABLE + assert one(d)["health"] == "SUSPECT" + + +def test_a_flagged_decision_keeps_a_green_member_out_of_healthy(tmp_path): + """decide-and-flag: the run made a call it was not licensed to make. Green + checks do not settle that — a human does.""" + mind = mini_mind(tmp_path) + clean = _batch.collect(mind, "2026-09-03-pm", evidence=evidence()) + assert one(clean)["health"] == "HEALTHY" + d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( + flagged=["decide-and-flag: PR opened rather than parked"])) + assert one(d)["health"] == "SUSPECT" + assert "decide-and-flag" in "\n".join( + b for _l, b in one(d)["blocks"]) + + +def test_members_sort_failures_first_and_pending_last(tmp_path): + mind = mini_mind( + tmp_path, + " - clean: draft/bug/autofit/resampling.md — glance — 3 — session ended green", + " - broken: draft/bug/autofit/resampling.md — judge — 20 — session ended green", + " - waiting: draft/bug/autofit/resampling.md — judge — 9 — CARRIED, " + "still running") + ev = {"clean": evidence()["resampling"], + "broken": dict(evidence()["resampling"], + prs=[pr(checks=[{"name": "tests", + "status": "completed", + "conclusion": "failure"}])]), + "waiting": evidence()["resampling"]} + d = _batch.collect(mind, "2026-09-03-pm", evidence=ev) + assert [s["slug"] for s in d["members"]] == ["broken", "clean", "waiting"] + assert one(d, "waiting")["health"] == "PENDING" + + +def test_no_evidence_at_all_is_unobservable_not_delivered(tmp_path): + """The third verdict. Calling these legs PASS would invent evidence; + calling them FAIL would condemn every member of every offline collect.""" + mind = mini_mind(tmp_path) + d = _batch.collect(mind, "2026-09-03-pm") + assert one(d)["health"] == "SUSPECT" + assert all(one(d)["legs"][k][0] == _batch.UNOBSERVABLE + for k in ("pr", "diff", "checks", "green")) + assert d["delivered"] == (0, 1) + + +def test_active_md_is_matched_by_prompt_basename_when_the_slug_differs(tmp_path): + """The record's slug is a dispatch label, the registry's is the task's + name: `autofit-resampling-info` is registered as + `resampling-info-summary-section`.""" + mind = mini_mind(tmp_path) + active = _batch.read_active(mind) + entry, how = _batch.active_for( + {"slug": "autofit-resampling-info", "path": "draft/x/resampling.md"}, + active) + assert entry["slug"] == "resampling-info-summary-section" + assert how == "prompt basename" + assert entry["prs"] == ["https://github.com/ExampleOrg/ExampleFit/pull/1554"] + assert entry["issue"].endswith("/issues/1551") + + +# ------------------------------------------------------------ the packet --- +def packet_of(mind) -> str: + return (mind / "batches" / "packets" / "2026-09-03-pm.html").read_text( + encoding="utf-8") + + +def apply_once(mind, ev=None, stamp=STAMP): + d = _batch.collect(mind, "2026-09-03-pm", evidence=ev or evidence()) + d["stamp"] = stamp + notes = _batch.apply_collect(mind, d, stamp) + return d, notes + + +def test_apply_writes_a_complete_document_and_the_record_keys(tmp_path): + mind = mini_mind(tmp_path) + apply_once(mind) + page = packet_of(mind) + assert page.startswith("") + assert page.rstrip().endswith("") + assert page.count("") == 1 + assert "[hidden] { display: none !important; }" in page + assert "" in page and "charset" in page + record = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") + assert f"- collected: {STAMP}" in record + assert f"- refreshed: {STAMP} — collect (1 member(s))" in record + assert "- delivered: 1/1" in record + assert "- packet: batches/packets/2026-09-03-pm.html" in record + + +def sections(page: str) -> dict: + out = {} + for start, end, mid in _batch._member_spans(page): + out[mid] = page[start:end] + return out + + +def test_a_refresh_regenerates_one_section_and_leaves_the_others_alone(tmp_path): + """TEMPLATE.md: the morning refresh regenerates that section in place, at + the same path, and never touches another member's markup — the human is + reading the page while it happens, and their notes live in it.""" + mind = mini_mind( + tmp_path, + " - clean: draft/bug/autofit/resampling.md — glance — 3 — session ended green", + " - second: draft/bug/autofit/resampling.md — glance — 3 — session ended green") + ev = {"clean": evidence()["resampling"], "second": evidence()["resampling"]} + apply_once(mind, ev) + before = packet_of(mind) + ev["second"] = dict(ev["second"], prs=[pr(checks=[ + {"name": "tests", "status": "completed", "conclusion": "failure"}])]) + apply_once(mind, ev) + after = packet_of(mind) + assert sections(before)["m-clean"] == sections(after)["m-clean"] + assert sections(before)["m-second"] != sections(after)["m-second"] + assert set(sections(before)) == set(sections(after)) + assert (mind / "batches" / "packets" / "2026-09-03-pm.html").is_file() + + +def test_a_pending_member_becomes_a_full_block_on_refresh_with_the_same_id(tmp_path): + mind = mini_mind( + tmp_path, + " - resampling: draft/bug/autofit/resampling.md — glance — 3 — " + "DELIVERED (ExampleFit#1554)") + ev = evidence() + ev["resampling"] = dict(ev["resampling"], pending=True) + apply_once(mind, ev) + before = sections(packet_of(mind))["m-resampling"] + assert "chip-pending" in before and "PENDING" in before + assert "Health evidence" not in before + apply_once(mind, evidence()) + after = sections(packet_of(mind))["m-resampling"] + assert "Health evidence" in after and "chip-pending" not in after + assert 'id="m-resampling"' in after + + +def test_the_submit_markdown_schema_is_parse_stable(tmp_path): + """The orchestrator parses the review on these exact forms; a cosmetic + edit here silently breaks close-out.""" + mind = mini_mind( + tmp_path, + " - clean: draft/bug/autofit/resampling.md — glance — 3 — session ended green", + " - second: draft/bug/autofit/resampling.md — judge — 9 — session ended green") + d, _ = apply_once(mind, {"clean": evidence()["resampling"], + "second": evidence()["resampling"]}) + page = packet_of(mind) + assert '"# Batch review " + SLOT' in page + assert '"- decision: "' in page and '"- ruled: "' in page + assert '"## Follow-ups accepted"' in page + members = json.loads(re.search(r"var MEMBERS = (\[.*?\]);", page, + re.S).group(1)) + assert [m["slug"] for m in members] == [s["slug"] for s in d["members"]] + assert [m["id"] for m in members] == [s["id"] for s in d["members"]] + assert all(m["health"] for m in members) + + +def test_stored_review_state_is_versioned_and_every_access_is_guarded(tmp_path): + """The page is opened from Pages, from a file:// path and from inside an + artifact viewer; two of those can throw on the accessor itself.""" + mind = mini_mind(tmp_path) + apply_once(mind) + page = packet_of(mind) + assert 'var KEY = "slot-review-2026-09-03-pm-v1";' in page + touches = [ln for ln in page.split("\n") + if "window.localStorage" in ln] + assert touches + assert all("try {" in ln for ln in touches) + + +# ------------------------------------------------------------ the record --- +def test_a_ruling_word_outcome_is_never_rewritten(tmp_path): + """The am record's REJECTED/ACCEPTED members are a review that happened. + A machine reading must not overwrite a human's sentence.""" + mind = mini_mind( + tmp_path, + " - ruled: draft/bug/autofit/resampling.md — glance — 3 — REJECTED " + "by the human at review", + " - fresh: draft/bug/autofit/resampling.md — glance — 3 — session ended green " + "into the wave") + apply_once(mind, {"ruled": evidence()["resampling"], + "fresh": evidence()["resampling"]}) + record = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") + assert "REJECTED by the human at review" in record + assert "session ended green" not in record + assert " - fresh: draft/bug/autofit/resampling.md — glance — 3 — HEALTHY" \ + in record + + +def test_the_notes_block_survives_a_record_rewrite_byte_for_byte(tmp_path): + mind = mini_mind(tmp_path) + path = mind / "batches" / "2026-09-03-pm.md" + before = path.read_text(encoding="utf-8") + block = before[before.index("- notes: |"):] + apply_once(mind) + after = path.read_text(encoding="utf-8") + assert after[after.index("- notes: |"):] == block + + +def test_a_second_apply_adds_one_refreshed_line_and_nothing_else(tmp_path): + mind = mini_mind(tmp_path) + path = mind / "batches" / "2026-09-03-pm.md" + apply_once(mind) + first = path.read_text(encoding="utf-8").split("\n") + apply_once(mind, stamp="2026-09-03T09:30Z") + second = path.read_text(encoding="utf-8").split("\n") + added = [ln for ln in second if ln not in first] + assert added == ["- refreshed: 2026-09-03T09:30Z — collect (1 member(s))"] + assert len(second) == len(first) + 1 + assert first.count(f"- collected: {STAMP}") == 1 + assert second.count(f"- collected: {STAMP}") == 1 + + +REVIEW = """# Batch review 2026-09-03-pm + +- packet: PyAutoMind/batches/packets/2026-09-03-pm.html +- reviewed-at: 2026-09-04T08:30Z +- review-minutes-actual: 55 + +## resampling — HEALTHY +- decision: merge +- ruled: yes + +Ship it, the summary block reads well. + +## Follow-ups accepted +""" + + +def test_a_submitted_review_closes_the_record_and_never_rewrites_the_packet(tmp_path): + """`batches/packets/AGENTS.md`: the archived page and the review file are + the audit pair — what was shown, what was ruled. A correction gets a new + dated page, not an edit.""" + mind = mini_mind(tmp_path, review=REVIEW) + d, notes = apply_once(mind) + assert not (mind / "batches" / "packets" / "2026-09-03-pm.html").exists() + assert any("never rewritten after a review" in n for n in notes) + record = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") + assert "- reviewed-at: 2026-09-04T08:30Z" in record + assert "- review-minutes-actual: 55" in record + assert "- review: batches/reviews/2026-09-03-pm.md" in record + assert d["review"]["members"]["resampling"]["decision"] == "merge" + assert d["review"]["members"]["resampling"]["ruled"] == "yes" + # Reported, never enacted. + assert "merge" in _batch.collect_report(d) + + +def test_a_closed_batch_keeps_every_member_line_and_every_value_it_has(tmp_path): + """Found on the live pm record: `PR OPENED AT REVIEW (…)` opens with no + ruling word, and the record's `reviewed-at:` carried a clause about where + the review sat. Once the review has landed the record is history — no + member line changes, and the close leg fills only what is blank.""" + mind = mini_mind( + tmp_path, + " - resampling: draft/bug/autofit/resampling.md — glance — 3 — PR " + "OPENED AT REVIEW (ExampleFit#1554 from the parked branch)", + keys="- reviewed-at: 2026-09-04T08:30 (transcribed; the review sat " + "outside the packet)\n- review-minutes-actual: (not given)\n" + "- delivered: 6/9 cloud members (5 PR sets green + 1 verdict)", + review=REVIEW) + apply_once(mind) + record = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") + assert "- delivered: 6/9 cloud members (5 PR sets green + 1 verdict)" in record + assert "- delivered: 0/1" not in record + assert "PR OPENED AT REVIEW (ExampleFit#1554 from the parked branch)" in record + assert "— HEALTHY" not in record + assert ("- reviewed-at: 2026-09-04T08:30 (transcribed; the review sat " + "outside the packet)") in record + assert "- reviewed-at: 2026-09-04T08:30Z" not in record + assert "- review-minutes-actual: 55" in record + assert "(not given)" not in record + + +def test_review_minutes_not_given_is_not_written_back(tmp_path): + mind = mini_mind(tmp_path, review=REVIEW.replace("55", "(not given)")) + apply_once(mind) + record = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") + assert "review-minutes-actual" not in record + + +# --------------------------------------------------------------- the cli --- +def test_exit_codes(tmp_path, capsys): + mind = mini_mind(tmp_path) + ev_file = tmp_path / "ev.json" + ev_file.write_text(json.dumps({"schema": 1, "members": evidence()}), + encoding="utf-8") + assert _batch.main(["collect", "--mind", str(mind), "--slot", + "2026-09-03-pm", "--evidence", str(ev_file)]) == 0 + bad = tmp_path / "bad.json" + bad.write_text(json.dumps({"members": evidence(prs=[])}), encoding="utf-8") + assert _batch.main(["collect", "--mind", str(mind), "--slot", + "2026-09-03-pm", "--evidence", str(bad)]) == 1 + assert _batch.main(["collect", "--mind", str(mind), + "--slot", "nope"]) == 2 + assert _batch.main(["collect", "--mind", str(tmp_path / "nowhere")]) == 4 + + +def test_malformed_evidence_is_a_usage_error(tmp_path): + mind = mini_mind(tmp_path) + broken = tmp_path / "broken.json" + broken.write_text("{not json", encoding="utf-8") + assert _batch.main(["collect", "--mind", str(mind), "--slot", + "2026-09-03-pm", "--evidence", str(broken)]) == 2 + + +def test_collect_only_flags_are_refused_on_plan(tmp_path): + mind = mini_mind(tmp_path) + assert _batch.main(["plan", "--mind", str(mind), "--apply"]) == 2 + + +def test_the_newest_slot_is_the_default_and_the_sort_is_lexical(tmp_path): + mind = mini_mind(tmp_path) + assert _batch.newest_slot(mind) == "2026-09-03-pm" + (mind / "batches" / "2026-09-03-night.md").write_text(record(MEMBER), + encoding="utf-8") + assert _batch.newest_slot(mind) == "2026-09-03-pm" + + +def test_fetch_without_gh_points_at_the_mcp_tools_and_still_scores( + tmp_path, monkeypatch, capsys): + """`gh` installs in a web session, authenticates, then 403s every + repo-scoped call — so its absence is answered with a pointer, never a + caught error.""" + monkeypatch.setattr(_batch.shutil, "which", lambda _name: None) + mind = mini_mind(tmp_path) + rc = _batch.main(["collect", "--mind", str(mind), "--slot", + "2026-09-03-pm", "--fetch"]) + out = capsys.readouterr().out + assert rc == 1 + assert "no gh here" in out and "--evidence " in out + assert out.count("no gh here") == 1 + assert "## resampling — SUSPECT" in out + + +def test_apply_writes_nothing_that_a_re_read_cannot_recover(tmp_path): + """The rehearsal. A ledger half-written has no way back, so the rewrite is + re-parsed on a throwaway copy before it is written for real.""" + mind = mini_mind(tmp_path) + before = (mind / "batches" / "2026-09-03-pm.md").read_text(encoding="utf-8") + d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence()) + after = _batch.record_update(before, d, STAMP) + assert _batch._rehearse_record(mind, before, after) == [] + broken = after.replace(" - resampling:", " - resampling") + assert _batch._rehearse_record(mind, before, broken) + + +# ------------------------------------------------------ the kinds registry -- +def _fake_score(member, ctx): + legs = {k: (_batch.PASS, "the fake kind says so") for k in _batch.LEGS} + return {"slug": member["slug"], "kind": "fake", "id": f"m-{member['slug']}", + "title": "A phase of a science project", "health": "HEALTHY", + "eyebrow": "cortex · phase 3", "jobs": "342091", + "chip": "witness landed", "est_minutes": 15, "tier": "judge", + "pending": False, "merged": False, "flagged": [], "legs": legs, + "links": [], "notes": [], "path": member["path"], "outcome": "", + "prs": [], "summary": "", "ruling_line": "_(yours to write)_", + "review_chips": [("accept", "Accept"), ("rerun", "Rerun")]} + + +def _fake_blocks(s): + return [("Question", "Does the subhalo show up?"), + ("Ruling", s["ruling_line"])] + + +def test_the_kinds_registry_is_the_extension_point(tmp_path): + """Phase 5 registers a `cortex` kind here. Nothing about the report or the + renderer may need to change for it, which is what this pins.""" + mind = mini_mind( + tmp_path, + " - resampling: draft/bug/autofit/resampling.md — glance — 3 — " + "session ended green", + " - subhalo: phases/subhalo_validation/pl_eff.md — judge — 15 — " + "session ended green") + kinds = dict(_batch.KINDS) + kinds["fake"] = (_fake_score, _fake_blocks, + lambda m, ctx: m["path"].startswith("phases/")) + d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence(), kinds=kinds) + d["stamp"] = STAMP + assert {s["kind"] for s in d["members"]} == {"dev", "fake"} + report = _batch.collect_report(d) + assert "## subhalo — HEALTHY" in report + assert "Does the subhalo show up?" in report + page, notes = _batch.packet_html(d) + assert notes == [] + assert 'id="m-subhalo"' in page + assert "A phase of a science project" in page + assert 'value="rerun"' in page + + +def test_every_interpolated_value_is_escaped(tmp_path): + """A record, a prompt and a check name are all human-written text on a page + served from Pages.""" + mind = mini_mind( + tmp_path, + " - x: draft/bug/autofit/resampling.md — " + "glance — 3 — session ended green") + d = _batch.collect(mind, "2026-09-03-pm") + d["stamp"] = STAMP + page, _notes = _batch.packet_html(d) + assert "" not in page + assert "<script>alert(1)</script>" in page + assert page.count("