From dcd33e244dee406738644d09b304dcac2dd4e71d Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 2 Sep 2026 12:59:42 -0400 Subject: [PATCH 1/6] batch: record each PR's head branch in the evidence JSON (#337) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A batch record names members, never branches, and `active.md`'s PR field has four spellings — so a PR's own head is the only reliable member -> (repo, branch) map. `gh pr view` is now asked for `headRefName`/`headRefOid`/ `headRepository`/`headRepositoryOwner`, and `_head_of` splices `head_ref`, `head_sha` and `head_repo` onto every PR row. A fork or a deleted head repo reports an empty `head_repo` rather than being guessed as `origin`. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01NR2L4MT5kTP8Lu9eR7dPUP --- agents/conductors/batch/AGENTS.md | 8 ++++++ agents/conductors/batch/_batch.py | 27 +++++++++++++++++- tests/test_batch_collect.py | 47 +++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+), 1 deletion(-) diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 0f977619..0c1c5086 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -291,6 +291,8 @@ actually looked up and nothing more. "state": "open", "merged": false, "additions": 86, "deletions": 12, "changed_files": 3, "mergeable": "MERGEABLE", + "head_ref": "feature/autofit-resampling-info", + "head_sha": "2629933c...", "head_repo": "PyAutoLabs/PyAutoFit", "checks": [{"name": "tests", "status": "completed", "conclusion": "success"}]}], "witness": {"holds": true, "evidence": "ordering test green on 2629933c"}, @@ -301,6 +303,12 @@ actually looked up and nothing more. "summary": "one line"}}} ``` +`head_ref`/`head_repo` are the member -> branch map: the record stores no repo +or branch per member and `active.md`'s `repos:` field has four dialects, so the +PR's own head is the only reliable source. A `head_repo` that differs from +`repo` is a fork — its head is not on `origin`, so it is reported rather than +merged. + `witness.holds` is tri-state: `true` PASS, `false` FAIL, absent UNOBSERVABLE. ### The packet is refreshed, never rewritten diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 0f09012f..e43509ae 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -616,8 +616,14 @@ def active_for(member: dict, active: dict) -> tuple: #: get a wrapper right. EVIDENCE_KEYS = ("prs", "witness", "adversary", "flagged", "pending", "summary") +#: The `gh pr view --json` field list. The four `head*` fields are the +#: authoritative member -> (repo, branch) map: the record stores no branch per +#: member, so a PR's own head is the only reliable source. The head *repo* is +#: recorded too because a fork's head is not on `origin` and cannot be merged +#: from a local checkout at all. GH_FIELDS = ("number,url,state,additions,deletions,changedFiles,mergeable," - "merged,statusCheckRollup") + "merged,statusCheckRollup,headRefName,headRefOid," + "headRepository,headRepositoryOwner") def load_evidence(path) -> dict: @@ -653,6 +659,24 @@ def _checks_from_rollup(rollup) -> list: return out +def _head_of(data: dict, repo: str) -> dict: + """The PR's head branch and where it lives. `headRepository` / + `headRepositoryOwner` are objects (`{"name": ...}` / `{"login": ...}`) and + either may be null on a deleted fork — a missing head is reported empty, + never guessed as `origin`, so a caller can tell "same repo" from "unknown". + """ + data = data if isinstance(data, dict) else {} + name = data.get("headRepository") + owner = data.get("headRepositoryOwner") + name = name.get("name") if isinstance(name, dict) else None + owner = owner.get("login") if isinstance(owner, dict) else None + return { + "head_ref": str(data.get("headRefName") or ""), + "head_sha": str(data.get("headRefOid") or ""), + "head_repo": f"{owner}/{name}" if owner and name else "", + } + + def fetch_evidence(members: list, active: dict) -> tuple: """PR evidence from `gh`, when there is a `gh`. Never writes. @@ -706,6 +730,7 @@ def fetch_evidence(members: list, active: dict) -> tuple: "mergeable": data.get("mergeable"), "merged": bool(data.get("merged")), "checks": _checks_from_rollup(data.get("statusCheckRollup")), + **_head_of(data, repo), }) if prs: out[m["slug"]] = {"prs": prs} diff --git a/tests/test_batch_collect.py b/tests/test_batch_collect.py index bf42ee9e..d889eda3 100644 --- a/tests/test_batch_collect.py +++ b/tests/test_batch_collect.py @@ -15,6 +15,7 @@ import re import sys from pathlib import Path +from types import SimpleNamespace BRAIN = Path(__file__).resolve().parents[1] sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) @@ -102,6 +103,8 @@ def pr(**over) -> dict: "url": "https://github.com/ExampleOrg/ExampleFit/pull/1554", "state": "OPEN", "additions": 86, "deletions": 12, "changed_files": 3, "mergeable": "MERGEABLE", "merged": False, + "head_ref": "feature/autofit-resampling-info", + "head_sha": "2629933c", "head_repo": "ExampleOrg/ExampleFit", "checks": [{"name": "tests", "status": "completed", "conclusion": "success"}]} row.update(over) @@ -556,6 +559,50 @@ def test_fetch_without_gh_points_at_the_mcp_tools_and_still_scores( assert "## resampling — SUSPECT" in out +def test_fetch_records_the_head_branch_of_every_pr(tmp_path, monkeypatch): + """A record names members, never branches, and `active.md`'s PR field has + four spellings — so the PR's own head is the only reliable member -> + (repo, branch) map. It is asked for in the `--json` field list and carried + through onto the row; a fork whose owner is gone reports an empty head + repo rather than guessing `origin`.""" + calls = [] + head = {"headRefName": "feature/x", "headRefOid": "abc", + "headRepository": {"name": "ExampleFit"}, + "headRepositoryOwner": {"login": "ExampleOrg"}} + + def fake(cmd, **_kw): + calls.append(cmd) + body = {"number": 1554, "url": "https://example.invalid/pull/1554", + "state": "OPEN", "additions": 5, "deletions": 1, + "changedFiles": 2, "mergeable": "MERGEABLE", "merged": False, + "statusCheckRollup": [], **head} + return SimpleNamespace(returncode=0, stdout=json.dumps(body), + stderr="") + + monkeypatch.setattr(_batch.shutil, "which", lambda _name: "/usr/bin/gh") + monkeypatch.setattr(_batch.subprocess, "run", fake) + mind = mini_mind(tmp_path) + members = [{"slug": "resampling", "path": "draft/bug/autofit/resampling.md"}] + active = _batch.read_active(mind) + + got, notes = _batch.fetch_evidence(members, active) + + assert notes == [] + assert "headRefName" in _batch.GH_FIELDS + # The flag is what is pinned: a field dropped from the argv is a field the + # evidence silently loses. + assert any("headRefName" in str(arg) for arg in calls[0]) + row = got["resampling"]["prs"][0] + assert row["head_ref"] == "feature/x" + assert row["head_sha"] == "abc" + assert row["head_repo"] == "ExampleOrg/ExampleFit" + + head["headRepositoryOwner"] = None + got, _notes = _batch.fetch_evidence(members, active) + assert got["resampling"]["prs"][0]["head_repo"] == "" + assert got["resampling"]["prs"][0]["head_ref"] == "feature/x" + + def test_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.""" From 99e98c915e09e44529f537180f3cecaed051cb7e Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 2 Sep 2026 13:03:00 -0400 Subject: [PATCH 2/6] worktree: PYAUTO_WT_BRANCH override for non-feature roots (#337) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `_worktree_add_one` hardcoded `feature/$task`, so every root worktree.sh builds claims to be feature work. The batch conductor's forthcoming `collect --integration` needs a throwaway review root named `integration/` instead — the one thing the helper could not say. The override is additive: unset, nothing changes, which the second test pins. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01NR2L4MT5kTP8Lu9eR7dPUP --- bin/worktree.sh | 7 ++- tests/test_batch_integration.py | 93 +++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 tests/test_batch_integration.py diff --git a/bin/worktree.sh b/bin/worktree.sh index 16f46719..66d1da66 100644 --- a/bin/worktree.sh +++ b/bin/worktree.sh @@ -18,6 +18,9 @@ # back to the canonical checkout so relative paths keep working. # * Numba and matplotlib cache dirs are per-task to prevent concurrent pytest # runs from thrashing each other's caches. +# * PYAUTO_WT_BRANCH overrides the per-task branch name. The batch conductor's +# `collect --integration` sets it to integration/ so a throwaway review +# root does not masquerade as feature work; unset, nothing changes. set -o pipefail @@ -81,7 +84,7 @@ _worktree_add_one() { local task="$1" repo="$2" local repo_src="$PYAUTO_MAIN/$repo" local repo_dest="$PYAUTO_WT_ROOT/$task/$repo" - local branch="feature/$task" + local branch="${PYAUTO_WT_BRANCH:-feature/$task}" if [[ ! -d "$repo_src/.git" ]]; then echo "_worktree_add_one: $repo_src is not a git repo" >&2 @@ -191,7 +194,7 @@ worktree_add_repo() { return 1 fi - echo "worktree_add_repo: added $repo to $root on branch feature/$task" + echo "worktree_add_repo: added $repo to $root on branch ${PYAUTO_WT_BRANCH:-feature/$task}" } # worktree_remove diff --git a/tests/test_batch_integration.py b/tests/test_batch_integration.py new file mode 100644 index 00000000..57e81411 --- /dev/null +++ b/tests/test_batch_integration.py @@ -0,0 +1,93 @@ +"""tests/test_batch_integration.py — the batch conductor's integration branches. + +The Witness the task registers: *a batch-conductor test builds a temp repo with +two member branches, runs `collect --integration`, and asserts +`integration/` tree == merge of both heads plus a packet line `clean` / +`conflicted: ` per repo; evidence JSON carries `headRefName` for every +member PR.* + +This module drives the real `bin/worktree.sh` against throwaway repos rather +than a re-implementation of it: the value of `worktree_create` is the root +layout (activate.sh's PYTHONPATH, the per-task caches, the symlink of every +other top-level entry), and a second definition of "a PyAuto worktree root" +would drift from the first. +""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +BRAIN = Path(__file__).resolve().parents[1] +WORKTREE_SH = BRAIN / "bin" / "worktree.sh" + + +def _git(repo: Path, *args: str) -> None: + subprocess.run(["git", "-C", str(repo), *args], check=True, + capture_output=True) + + +def _repo(origins: Path, main: Path, name: str) -> Path: + """A clone of a bare origin with one commit on `main`, as `worktree_create` + expects: it branches from `origin/`, so `origin/main` must exist.""" + origin = origins / f"{name}.git" + subprocess.run(["git", "init", "--bare", "-b", "main", str(origin)], + check=True, capture_output=True) + repo = main / name + subprocess.run(["git", "clone", str(origin), str(repo)], check=True, + capture_output=True) + _git(repo, "config", "user.email", "t@t") + _git(repo, "config", "user.name", "t") + (repo / "a.py").write_text("base\n") + _git(repo, "add", "a.py") + _git(repo, "commit", "-m", "base") + _git(repo, "push", "-u", "origin", "main") + return repo + + +def _create(tmp_path: Path, task: str, branch: str | None) -> tuple[Path, Path]: + """Run the real `worktree_create` for one repo; return (root, worktree).""" + origins = tmp_path / "origins" + main = tmp_path / "main" + origins.mkdir(parents=True, exist_ok=True) + main.mkdir(parents=True, exist_ok=True) + _repo(origins, main, "MyRepo") + (main / "some_workspace").mkdir(exist_ok=True) # symlinked, not a worktree + + env = {k: v for k, v in os.environ.items() if k != "PYAUTO_WT_BRANCH"} + env.update({"HOME": str(tmp_path), "PYAUTO_ROOT": str(main), + "PYAUTO_MAIN": str(main), "PYAUTO_WT_ROOT": str(tmp_path / "wt")}) + if branch is not None: + env["PYAUTO_WT_BRANCH"] = branch + proc = subprocess.run( + ["bash", "-c", f'set -e; . "{WORKTREE_SH}"; worktree_create "$@"', + "_", task, "MyRepo"], + env=env, capture_output=True, text=True, timeout=120) + assert proc.returncode == 0, proc.stdout + proc.stderr + root = tmp_path / "wt" / task + return root, root / "MyRepo" + + +def _head(worktree: Path) -> str: + got = subprocess.run(["git", "-C", str(worktree), "rev-parse", + "--abbrev-ref", "HEAD"], + check=True, capture_output=True, text=True) + return got.stdout.strip() + + +def test_the_branch_name_override_is_honoured(tmp_path): + """`collect --integration` builds a throwaway review root, and a root that + calls itself `feature/` masquerades as feature work — every branch + sweep and every contribution check then has to guess. `PYAUTO_WT_BRANCH` is + the one thing worktree.sh could not otherwise say.""" + _root, worktree = _create(tmp_path, "integration-2026-09-03-pm", + branch="integration/x") + assert _head(worktree) == "integration/x" + + +def test_without_the_override_the_branch_is_still_feature_of_the_task(tmp_path): + """The override is additive: unset, worktree.sh names branches exactly as + every existing task worktree on disk is named.""" + _root, worktree = _create(tmp_path, "task-y", branch=None) + assert _head(worktree) == "feature/task-y" From f39230f94c7e9d977d95f2c1e1a12bb85bf7325c Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 2 Sep 2026 13:16:50 -0400 Subject: [PATCH 3/6] =?UTF-8?q?batch:=20=5Fintegration=20=E2=80=94=20merge?= =?UTF-8?q?=20every=20member's=20head=20into=20one=20review=20worktree=20(?= =?UTF-8?q?#337)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One throwaway worktree root per slot: every member's head branch merged into `integration/`, per repo, off `origin/main`, so the human can RUN the whole batch before ruling on any of it — and so "how would these resolve at the end?" is answered by a merge rather than by reading diffs. Three properties, deliberately. It writes no remote: `git fetch origin` and local merges, no push and no PR. It resolves nothing: a member whose merge conflicts is left OUT and named with the conflicting paths, and that report is the product. And it is stdlib-only, importing nothing from `_batch`, so the conductor can load it lazily and this suite can drive it against throwaway repos with no Mind, no record and no packet in sight. The seam with `bin/worktree.sh` is that worktree.sh knows LAYOUT and this module knows MERGES. The root is built by shelling to `worktree_create` with `PYAUTO_WT_BRANCH=integration/`, because the value of that function is activate.sh's PYTHONPATH, the per-task caches and the symlink of every other top-level entry — re-deriving it here would fork the definition of "a PyAuto worktree root" into two places that would drift. The merges are plain git, because a shell helper would bury the exit code and the unmerged-path list the report needs. The branch is re-cut from `origin/main` every run: the merge result is a function of the current base and the current heads, so a second run that stacked onto the first would preview a base that no longer exists. That is only safe because a dirty integration worktree is refused outright — that refusal, not the branch policy, is the safety property, and it is what the re-run and dirty-worktree tests pin. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01NR2L4MT5kTP8Lu9eR7dPUP --- agents/conductors/batch/_integration.py | 342 ++++++++++++++++++++++++ tests/test_batch_integration.py | 208 ++++++++++++++ 2 files changed, 550 insertions(+) create mode 100644 agents/conductors/batch/_integration.py diff --git a/agents/conductors/batch/_integration.py b/agents/conductors/batch/_integration.py new file mode 100644 index 00000000..c6f68c9f --- /dev/null +++ b/agents/conductors/batch/_integration.py @@ -0,0 +1,342 @@ +"""agents/conductors/batch/_integration.py — the batch's integration branches. + +One throwaway worktree root per slot. Every member's head branch is merged into +`integration/`, per repo, off `origin/main`, so the human can *run* the +whole batch together before ruling on any of it — and so the question "how +would these resolve at the end?" is answered by a merge rather than by reading +diffs. + +Three properties, deliberately: + +* **It writes no remote.** `git fetch origin` and local merges; no push, no PR, + no remote ref is created or moved. Pushing `integration/` is a separate, + later decision (the prompt's Phase 3). +* **It resolves nothing.** A member whose merge conflicts is left OUT of that + repo's branch and named with the conflicting paths. That report is the + product; it is not a failure of the collect, and it moves no exit code and no + member's health word (a member's health is about its own delivery; a merge + collision is a property of the *slot*). +* **It is stdlib-only and imports nothing from `_batch`.** The conductor loads + it lazily, the way it loads the Cortex conductor, so a session that never asks + for `--integration` never pays for it — and this module stays unit-testable + against throwaway repos with no Mind, no record and no packet in sight. + +The seam with `bin/worktree.sh`: **worktree.sh knows layout, this module knows +merges.** The value of `worktree_create` is not `git worktree add` — it is the +root (activate.sh's `PYTHONPATH`, the per-task numba/matplotlib caches, and the +symlink of every other top-level entry so relative workspace paths resolve). +Re-deriving that here would fork the definition of "a PyAuto worktree root" into +two places that would drift, so the ROOT is built by shelling to worktree.sh +with `PYAUTO_WT_BRANCH=integration/`; the MERGES are plain `git`, because +a shell helper would bury the exit code and the unmerged-path list the packet +needs. +""" + +from __future__ import annotations + +import datetime as _dt +import os +import subprocess +from pathlib import Path + +BRAIN = Path(__file__).resolve().parents[3] +WORKTREE_SH = BRAIN / "bin" / "worktree.sh" + +#: `git` never gets to ask for a password: an unattended collect that blocks on +#: a credential prompt looks exactly like a hung merge. +GIT_ENV = {"GIT_TERMINAL_PROMPT": "0"} + +#: A box with no committed git identity (CI, a fresh container) cannot merge at +#: all. Supplied per-invocation with `-c`, and ONLY when the worktree has no +#: identity of its own — a human's box keeps their own name on their own merges. +FALLBACK_NAME = "PyAuto Batch" +FALLBACK_EMAIL = "batch@pyautolabs.invalid" + +NOT_LOCAL = ("batch collect --integration: the integration worktree is a " + "laptop leg (real git worktrees under $PYAUTO_WT_ROOT) — run " + "collect from the laptop; everything else is scored anyway.") + + +# ------------------------------------------------------------- where things go +def workspace_root() -> Path: + """The directory holding the organ checkouts side by side. + + Same convention as `bin/_pyauto_root.sh`: an explicit `PYAUTO_ROOT` is the + operator's word and always wins; otherwise it is the parent of this Brain + checkout, which is true in every environment the organism runs in. + """ + return Path(os.environ.get("PYAUTO_ROOT") or BRAIN.parent) + + +def task_name(slot: str) -> str: + return f"integration-{slot}" + + +def branch_name(slot: str) -> str: + return f"integration/{slot}" + + +def wt_root() -> Path: + """Where task roots live — beside the workspace root, never inside it.""" + return Path(os.environ.get("PYAUTO_WT_ROOT") or f"{workspace_root()}-wt") + + +def root_for(slot: str) -> Path: + return wt_root() / task_name(slot) + + +def _env() -> dict: + """The environment every child gets: the caller's, plus the four variables + that make worktree.sh and this module resolve the *same* paths. Deriving + both sides from `workspace_root()` is what stops the root being built beside + one checkout while the merges read another.""" + env = dict(os.environ) + env.update(GIT_ENV) + env["PYAUTO_ROOT"] = str(workspace_root()) + env["PYAUTO_MAIN"] = str(workspace_root()) + env["PYAUTO_WT_ROOT"] = str(wt_root()) + return env + + +def _git(*args: str, cwd=None, timeout: int = 60): + """One git call. Captured, never interactive, and it NEVER raises on a + non-zero return code: every git failure here is a line in the report, and a + traceback out of a collect would lose the members that did merge.""" + try: + return subprocess.run(["git", *args], cwd=str(cwd) if cwd else None, + env=_env(), capture_output=True, text=True, + timeout=timeout) + except (OSError, subprocess.SubprocessError) as e: # pragma: no cover + return subprocess.CompletedProcess( + args=["git", *args], returncode=127, stdout="", stderr=str(e)) + + +def _tail(proc) -> str: + lines = ((proc.stderr or "") + (proc.stdout or "")).strip().splitlines() + return lines[-1][:160] if lines else "" + + +# ----------------------------------------------------------------- the plan -- +def plan_jobs(members: list, order: list, notes: list) -> list: + """`[{"repo", "dir", "members": [{"member", "branch", "want_sha"}…]}…]`. + + Grouped by **repo**, not by member: the common case is one member with organ + PRs across five repos, so a member contributes one head branch to each repo + it touched and can be merged in one and conflicted in another. Ordered by + the record's dispatch order (`order`), because `d["members"]` is re-sorted by + health and merge order is a property of the record, not of the scores. + + Everything left out says so. Four reasons, and none of them is a guess: + already merged, closed, no `head_ref` in the evidence, or a head that lives + on a fork (whose branch is simply not on `origin` and cannot be merged from + a local checkout at all). + """ + by_slug = {m.get("slug"): m for m in members} + groups: dict[str, dict] = {} + for slug in order: + m = by_slug.get(slug) + if not m: + continue + for p in m.get("prs") or []: + repo = str(p.get("repo") or "") + label = f"{repo}#{p.get('number')}" + if p.get("merged"): + notes.append(f"{slug}: {label} is already merged — not " + f"re-merged") + continue + if str(p.get("state") or "").upper() == "CLOSED": + notes.append(f"{slug}: {label} is CLOSED — not merged") + continue + head_ref = str(p.get("head_ref") or "") + if not head_ref: + notes.append(f"{slug}: {label} has no head_ref in the evidence " + f"— re-run collect --fetch (Phase 1 field " + f"headRefName)") + continue + head_repo = str(p.get("head_repo") or "") + if head_repo and head_repo != repo: + notes.append(f"{slug}: {label} is from a fork ({head_repo}) — " + f"its head is not on origin, left out") + continue + g = groups.setdefault(repo, {"repo": repo, + "dir": repo.split("/")[-1], + "members": []}) + g["members"].append({"member": slug, "branch": head_ref, + "want_sha": str(p.get("head_sha") or "")}) + jobs = [] + for g in groups.values(): + if not (workspace_root() / g["dir"] / ".git").exists(): + notes.append(f"{g['repo']}: no checkout at " + f"{workspace_root() / g['dir']} — left out of the " + f"integration root") + continue + jobs.append(g) + return jobs + + +# ----------------------------------------------------------------- the root -- +def _worktree_sh(func: str, slot: str, *args: str): + """One call into `bin/worktree.sh`, with the branch override that is the + only thing it could not otherwise say.""" + env = _env() + env["PYAUTO_WT_BRANCH"] = branch_name(slot) + return subprocess.run( + ["bash", "-c", f'set -e; . "$0"; {func} "$@"', str(WORKTREE_SH), + task_name(slot), *args], + env=env, capture_output=True, text=True, timeout=600) + + +def ensure_root(slot: str, repo_dirs: list, notes: list): + """The worktree root, created or adopted. Idempotent by construction. + + `worktree_create` refuses an existing root — which is exactly why the two + branches are here rather than a force: a second run of the same slot adopts + the root it built the first time, and attaches only the repos that are still + placeholder symlinks in it. Anything that fails returns `None`: half a root + reported as an integration is worse than none. + """ + root = root_for(slot) + if not root.exists(): + proc = _worktree_sh("worktree_create", slot, *repo_dirs) + if proc.returncode != 0: + notes.append(f"integration root not built at {root}: " + f"{_tail(proc)}") + return None + return root + for name in repo_dirs: + if (root / name / ".git").exists(): + continue + proc = _worktree_sh("worktree_add_repo", slot, name) + if proc.returncode != 0: + notes.append(f"{name}: could not attach to the integration root " + f"at {root}: {_tail(proc)}") + return None + return root + + +# --------------------------------------------------------------- the merges -- +def _identity(wt: Path) -> list: + """`-c user.name=… -c user.email=…`, or nothing at all. A box with no + committed identity cannot make a merge commit; a box with one keeps it.""" + got = _git("-C", str(wt), "config", "user.email") + if got.returncode == 0 and got.stdout.strip(): + return [] + return ["-c", f"user.name={FALLBACK_NAME}", + "-c", f"user.email={FALLBACK_EMAIL}"] + + +def integrate_repo(job: dict, wt: Path, slot: str, notes: list) -> dict: + """One repo's integration branch. Returns the report row; raises nothing. + + The branch is **re-cut from `origin/main` on every run** (`checkout -B`). + The merge result is a function of the current `origin/main` and the current + heads, so a second run that merged onto the previous run's tip would report + a preview of a base that no longer exists — the honest refresh is a re-cut. + That is safe because the ref is a throwaway: nothing is pushed, no PR is + based on it and no member branch descends from it, so `-B` rewrites nothing + anyone else holds. (`AGENTS.md`'s "never rewrite history" is about + *published* history — which is precisely what Phase 3's never-force-push + rule will protect once such a branch exists on GitHub.) + + The one thing a re-cut could destroy is a human's uncommitted experiment + inside the integration worktree, so step 2 refuses a dirty worktree outright + and says so. **That refusal, not the branch policy, is the safety property.** + """ + branch = branch_name(slot) + row = {"repo": job["repo"], "dir": job["dir"], "path": str(wt), + "branch": branch, "base": "origin/main", "base_sha": "", + "head_sha": "", "merged": [], "conflicts": [], "status": "skipped", + "note": ""} + + # A run killed mid-merge leaves MERGE_HEAD and conflicted files behind, and + # `checkout -B` would refuse on both. Clearing it first is what makes the + # dirty check below mean "a human left something here", not "we did". + _git("-C", str(wt), "merge", "--abort") + + dirty = _git("-C", str(wt), "status", "--porcelain") + if dirty.returncode != 0: + row["note"] = f"git status failed in {wt}: {_tail(dirty)}" + notes.append(f"{job['repo']}: {row['note']}") + return row + if dirty.stdout.strip(): + row["note"] = ("the integration worktree has uncommitted changes — " + "left alone") + notes.append(f"{job['repo']}: {row['note']}") + return row + + fetched = _git("-C", str(wt), "fetch", "origin", "--quiet", timeout=300) + if fetched.returncode != 0: + notes.append(f"{job['repo']}: git fetch origin failed " + f"({_tail(fetched)}) — merged against the refs already " + f"here, which may be stale") + + base = _git("-C", str(wt), "rev-parse", "--verify", "origin/main") + if base.returncode != 0: + row["note"] = "no origin/main in this checkout — nothing to cut from" + notes.append(f"{job['repo']}: {row['note']}") + return row + row["base_sha"] = base.stdout.strip() + + cut = _git("-C", str(wt), "checkout", "-B", branch, "origin/main") + if cut.returncode != 0: + row["note"] = f"could not cut {branch} from origin/main: {_tail(cut)}" + notes.append(f"{job['repo']}: {row['note']}") + return row + + ident = _identity(wt) + for entry in job["members"]: + ref = f"origin/{entry['branch']}" + if _git("-C", str(wt), "rev-parse", "--verify", ref).returncode != 0: + notes.append(f"{entry['member']}: {ref} is not in " + f"{job['repo']} — pushed? left out") + continue + got = _git("-C", str(wt), *ident, "merge", "--no-ff", "--no-edit", + "-m", f"integration {slot}: {entry['member']} " + f"({entry['branch']})", ref, timeout=300) + if got.returncode == 0: + row["merged"].append(entry["member"]) + continue + # The unmerged paths exist only while the index is unmerged, so they are + # read BEFORE the abort — afterwards there is nothing left to name. + paths = _git("-C", str(wt), "diff", "--name-only", "--diff-filter=U") + row["conflicts"].append({ + "member": entry["member"], "branch": entry["branch"], + "paths": [p for p in paths.stdout.split("\n") if p.strip()]}) + _git("-C", str(wt), "merge", "--abort") + + head = _git("-C", str(wt), "rev-parse", "HEAD") + row["head_sha"] = head.stdout.strip() if head.returncode == 0 else "" + row["status"] = "conflicted" if row["conflicts"] else "clean" + return row + + +# ------------------------------------------------------------------- the leg -- +def run(members: list, order: list, slot: str, *, lane: str) -> tuple: + """`(block | None, notes)` — the whole `--integration` leg. + + Refuses any lane but `local-dev` with a pointer rather than a caught error, + exactly as `fetch_evidence` refuses a session with no `gh`: real git + worktrees under `$PYAUTO_WT_ROOT` are a laptop thing, and a cloud session + that tried would fail halfway rather than up front. + """ + notes: list[str] = [] + if lane != "local-dev": + return None, [NOT_LOCAL] + jobs = plan_jobs(members, order, notes) + if not jobs: + notes.append("batch collect --integration: no member PR has a " + "mergeable head branch in a local checkout — nothing to " + "integrate") + return None, notes + root = ensure_root(slot, [j["dir"] for j in jobs], notes) + if root is None: + return None, notes + repos = [integrate_repo(j, root / j["dir"], slot, notes) for j in jobs] + block = { + "slot": slot, "root": str(root), + "activate": str(root / "activate.sh"), + "branch": branch_name(slot), + "at": _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%MZ"), + "repos": repos, "notes": list(notes), + } + return block, notes diff --git a/tests/test_batch_integration.py b/tests/test_batch_integration.py index 57e81411..5ac285db 100644 --- a/tests/test_batch_integration.py +++ b/tests/test_batch_integration.py @@ -91,3 +91,211 @@ def test_without_the_override_the_branch_is_still_feature_of_the_task(tmp_path): every existing task worktree on disk is named.""" _root, worktree = _create(tmp_path, "task-y", branch=None) assert _head(worktree) == "feature/task-y" + + +# --------------------------------------------------------- the merge engine -- +import importlib.util # noqa: E402 +import sys # noqa: E402 +from types import SimpleNamespace # noqa: E402 + +import pytest # noqa: E402 + +#: Loaded standalone, by file location — no `_batch`, no sizing faculty, no +#: `sys.path` surgery. That it imports at all is the first assertion: the merge +#: engine is stdlib-only and knows nothing about the conductor that calls it. +_INTEG_SPEC = importlib.util.spec_from_file_location( + "_batch_integration_leg_under_test", + BRAIN / "agents" / "conductors" / "batch" / "_integration.py") +INTEG = importlib.util.module_from_spec(_INTEG_SPEC) +_INTEG_SPEC.loader.exec_module(INTEG) + +SLOT = "2026-09-03-pm" +STAMP = "2026-09-03T08:00Z" + + +def _out(repo: Path, *args: str) -> str: + got = subprocess.run(["git", "-C", str(repo), *args], capture_output=True, + text=True) + return got.stdout.strip() + + +def _seed(origins: Path, main: Path, name: str) -> Path: + """A repo with `main` and three pushed member heads. + + `feature/alpha` and `feature/beta` both rewrite `a.py`, so each merges + cleanly onto `origin/main` alone and the SECOND of them collides — the + merge-order case the whole leg exists to preview. `feature/gamma` touches + `b.py` only, so it is the clean-alongside case. + """ + origin = origins / f"{name}.git" + subprocess.run(["git", "init", "--bare", "-b", "main", str(origin)], + check=True, capture_output=True) + repo = main / name + subprocess.run(["git", "clone", str(origin), str(repo)], check=True, + capture_output=True) + _git(repo, "config", "user.email", "t@t") + _git(repo, "config", "user.name", "t") + (repo / "a.py").write_text("base\n") + (repo / "b.py").write_text("base\n") + _git(repo, "add", "a.py", "b.py") + _git(repo, "commit", "-m", "base") + _git(repo, "push", "-u", "origin", "main") + for branch, path, body in (("feature/alpha", "a.py", "alpha"), + ("feature/beta", "a.py", "beta"), + ("feature/gamma", "b.py", "gamma")): + _git(repo, "checkout", "-B", branch, "main") + (repo / path).write_text(body + "\n") + _git(repo, "add", path) + _git(repo, "commit", "-m", branch) + _git(repo, "push", "-u", "origin", branch) + _git(repo, "checkout", "main") + return repo + + +@pytest.fixture +def ws(tmp_path, monkeypatch): + """A throwaway workspace root: `main/` holds the checkouts, `wt/` is where + task roots go. Both are declared through the same environment variables the + laptop uses, so nothing here is a special path this module invented.""" + origins, main, wt = tmp_path / "origins", tmp_path / "main", tmp_path / "wt" + origins.mkdir() + main.mkdir() + (main / "some_workspace").mkdir() # symlinked into the root, not a worktree + monkeypatch.setenv("PYAUTO_ROOT", str(main)) + monkeypatch.setenv("PYAUTO_MAIN", str(main)) + monkeypatch.setenv("PYAUTO_WT_ROOT", str(wt)) + monkeypatch.delenv("PYAUTO_WT_BRANCH", raising=False) + return SimpleNamespace(main=main, wt=wt, root=wt / f"integration-{SLOT}", + seed=lambda name: _seed(origins, main, name)) + + +def member(slug: str, branch: str, repo: str = "MyRepo", **over) -> dict: + """A scored member, cut down to what `plan_jobs` reads.""" + row = {"repo": f"Example/{repo}", "number": 7, "state": "OPEN", + "merged": False, "head_ref": branch, "head_sha": "", + "head_repo": f"Example/{repo}"} + row.update(over) + return {"slug": slug, "prs": [row]} + + +def test_two_members_merge_in_dispatch_order_and_the_conflicting_one_is_left_out(ws): + """**The Witness.** Two members rewrote the same file. Each is green on its + own; the batch is not. The leg answers "how would these resolve at the + end?" by merging in DISPATCH order and naming the collision — it never + resolves it, and it never touches the canonical checkout.""" + ws.seed("MyRepo") + was = _out(ws.main / "MyRepo", "rev-parse", "HEAD") + block, _notes = INTEG.run( + [member("alpha", "feature/alpha"), member("beta", "feature/beta")], + ["alpha", "beta"], SLOT, lane="local-dev") + + r = block["repos"][0] + assert r["status"] == "conflicted" + assert r["merged"] == ["alpha"] + assert r["conflicts"] == [{"member": "beta", "branch": "feature/beta", + "paths": ["a.py"]}] + assert r["branch"] == f"integration/{SLOT}" + + wt = Path(r["path"]) + assert (wt / "a.py").read_text() == "alpha\n" # the merge of base+alpha + assert _head(wt) == f"integration/{SLOT}" + # The abort really aborted: no half-merge is left for the human to find. + assert _out(wt, "status", "--porcelain") == "" + assert subprocess.run(["git", "-C", str(wt), "rev-parse", "--verify", + "MERGE_HEAD"], capture_output=True).returncode != 0 + + # The canonical checkout is untouched — same branch, same commit. + assert _out(ws.main / "MyRepo", "rev-parse", "HEAD") == was + assert _out(ws.main / "MyRepo", "rev-parse", "--abbrev-ref", "HEAD") == "main" + + +def test_a_clean_repo_reports_clean_and_carries_every_member(ws): + """Two members that never touch the same file both land, and the branch + carries one merge commit each — the case the human can actually run.""" + ws.seed("MyRepo") + block, _notes = INTEG.run( + [member("alpha", "feature/alpha"), member("gamma", "feature/gamma")], + ["alpha", "gamma"], SLOT, lane="local-dev") + r = block["repos"][0] + assert r["status"] == "clean" and r["conflicts"] == [] + assert r["merged"] == ["alpha", "gamma"] + wt = Path(r["path"]) + assert (wt / "a.py").read_text() == "alpha\n" + assert (wt / "b.py").read_text() == "gamma\n" + assert _out(wt, "rev-list", "--count", "--merges", + "origin/main..HEAD") == "2" + + +def test_a_re_run_reproduces_the_branch_rather_than_stacking_on_it(ws): + """The branch is re-cut from `origin/main` every run. The merge result is a + function of the current base and the current heads, so a second run that + stacked onto the first would preview a base that no longer exists.""" + ws.seed("MyRepo") + args = ([member("alpha", "feature/alpha"), member("gamma", "feature/gamma")], + ["alpha", "gamma"], SLOT) + first, _n = INTEG.run(*args, lane="local-dev") + wt = Path(first["repos"][0]["path"]) + tree = _out(wt, "rev-parse", "HEAD^{tree}") + count = _out(wt, "rev-list", "--count", "origin/main..HEAD") + + second, _n = INTEG.run(*args, lane="local-dev") + assert second["repos"][0]["status"] == "clean" + assert _out(wt, "rev-parse", "HEAD^{tree}") == tree + assert _out(wt, "rev-list", "--count", "origin/main..HEAD") == count + + +def test_a_dirty_integration_worktree_is_left_alone(ws): + """The refusal that makes re-cutting the branch safe at all. The one thing + a re-cut could destroy is a human's uncommitted experiment inside the + review root — so it is not re-cut, and the report says why.""" + ws.seed("MyRepo") + first, _n = INTEG.run([member("alpha", "feature/alpha")], ["alpha"], SLOT, + lane="local-dev") + wt = Path(first["repos"][0]["path"]) + (wt / "scratch.py").write_text("the human was mid-experiment\n") + + block, notes = INTEG.run([member("gamma", "feature/gamma")], ["gamma"], + SLOT, lane="local-dev") + r = block["repos"][0] + assert r["status"] == "skipped" + assert "uncommitted" in r["note"] + assert any("uncommitted" in n for n in notes) + assert (wt / "scratch.py").read_text() == "the human was mid-experiment\n" + assert (wt / "b.py").read_text() == "base\n" # gamma was NOT merged in + + +def test_a_fork_head_a_merged_pr_and_a_missing_head_ref_are_reported_not_merged(ws): + """Three heads that cannot honestly be merged, three notes, zero merges. A + fork's head is not on `origin` at all; a merged PR is history; a PR with no + `head_ref` was scored from evidence gathered before Phase 1 widened the + field list, and guessing a branch name is how a preview becomes a lie.""" + ws.seed("MyRepo") + block, notes = INTEG.run( + [member("forked", "feature/alpha", head_repo="Someone/MyRepo"), + member("landed", "feature/beta", merged=True), + member("blind", "")], + ["forked", "landed", "blind"], SLOT, lane="local-dev") + assert block is None + joined = "\n".join(notes) + assert "is from a fork (Someone/MyRepo)" in joined + assert "is already merged — not re-merged" in joined + assert "has no head_ref in the evidence" in joined + assert not ws.root.exists() + + +def test_the_worktree_root_carries_activate_sh_and_the_symlinks(ws): + """The root is built by `bin/worktree.sh`, not re-derived here: its value is + the layout — the PYTHONPATH, the per-task caches, and the symlink of every + other top-level entry so relative workspace paths still resolve.""" + ws.seed("MyRepo") + block, _n = INTEG.run([member("alpha", "feature/alpha")], ["alpha"], SLOT, + lane="local-dev") + root = Path(block["root"]) + assert root == ws.root + activate = (root / "activate.sh").read_text() + assert "PYTHONPATH" in activate and "NUMBA_CACHE_DIR" in activate + assert f'PYAUTO_TASK="integration-{SLOT}"' in activate + assert block["activate"] == str(root / "activate.sh") + # A linked worktree's `.git` is a FILE; an untouched entry stays a symlink. + assert (root / "MyRepo" / ".git").is_file() + assert (root / "some_workspace").is_symlink() From 68054fa2cc8b5e0e46e7fad8e395779b64fe4328 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 2 Sep 2026 13:18:03 -0400 Subject: [PATCH 4/6] batch: collect --integration wiring, report, packet region, record stamp (#337) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `collect --integration` (or `- integration: yes` written into the record at dispatch) runs the merge leg and reports it in the three places collect already owns: the terminal report, the packet page, and the record's stamps. `collect()` now exposes `dispatch_order` — `d["members"]` is sorted by HEALTH, so it cannot drive a merge order, and the order the human listed the members in is the order the preview must merge them in. It also exposes `integration_requested`, read through a `_yes` helper from the record key. `load_evidence_doc` returns the whole evidence document alongside `load_evidence`'s members, because `integration` is slot-level rather than per member — a laptop's block pasted into a cloud session is how a non-laptop surface renders one at all. Collect deliberately does NOT rewrite the human's `--evidence` file: that file is an input, `--apply` writes exactly the packet and the record, and persisting the block is `--json > ev.json`'s job. The report puts the `source /activate.sh` line at the TOP, right after the NOT-DELIVERED lede: the whole point of the leg is that the human can run the batch, and a source line five screens down is a line nobody sources. The packet's `pyauto:integration` sentinels ship even when the body is empty, so a later `--integration` refresh has somewhere to splice into, while the region is only re-rendered when this collect HAS a block — a plain refresh must not blank a preview that is still true. The panel carries no `data-*` hook and no second `")) + page, _notes = _batch.packet_html(d) + assert "" in page + assert "" in page + body = region_of(page) + assert "clean" in body and "conflicted" in body and "a.py" in body + assert "source /tmp/wt/integration-x/activate.sh" in body + assert "<script>alert(1)" in body + assert page.count("") == 1 + + +def test_the_panel_says_where_a_workspace_member_has_to_be_run(tmp_path): + """`activate.sh`'s PYTHONPATH covers the libraries only. A workspace member + is a real worktree in the root but is not importable from outside it, and a + human who runs its script from the canonical checkout tests the wrong tree.""" + mind = mini_mind(tmp_path) + page, _n = _batch.packet_html(collected(mind, block_for())) + body = region_of(page) + assert "PYTHONPATH" in body + assert "/tmp/wt/integration-x/<workspace>" in body + + +def test_a_refresh_without_an_integration_leaves_the_region_alone(tmp_path): + """A plain collect must not blank the region the last `--integration` + filled: that merge preview is still true, and the human is reading it.""" + mind = mini_mind(tmp_path) + first, _n = _batch.packet_html(collected(mind, block_for())) + was = region_of(first) + assert "Example/MyRepo" in was + second, _n = _batch.packet_html(collected(mind), first) + assert region_of(second) == was + + +def test_a_cloud_session_says_run_it_from_the_laptop(tmp_path, capsys): + """Mirrors the `--fetch` refusal: real worktrees under `$PYAUTO_WT_ROOT` are + a laptop thing, so a cloud session is pointed at the laptop rather than + failing halfway through building a root it cannot finish.""" + mind = mini_mind(tmp_path) + rc = _batch.main(["collect", "--mind", str(mind), "--slot", SLOT, + "--integration", "--lane", "web-github"]) + out = capsys.readouterr().out + assert rc == 1 + assert out.count("run collect from the laptop") == 1 + assert "## alpha — " in out # the members are still scored + + +def _recorder(monkeypatch) -> list: + calls: list = [] + + def run(members, order, slot, *, lane): + calls.append({"order": list(order), "slot": slot, "lane": lane}) + return None, [] + + monkeypatch.setattr(_batch, "load_integration", + lambda: SimpleNamespace(run=run)) + return calls + + +def test_the_record_can_ask_for_it_at_dispatch(tmp_path, monkeypatch): + """`- integration: yes` written at dispatch is the human saying "I will want + to run this batch" — it must not need them to remember a flag at collect.""" + calls = _recorder(monkeypatch) + mind = mini_mind(tmp_path, keys="- integration: yes") + _batch.main(["collect", "--mind", str(mind), "--slot", SLOT]) + assert [c["order"] for c in calls] == [["alpha"]] + + calls.clear() + off = mini_mind(tmp_path / "off", keys="- integration: no") + _batch.main(["collect", "--mind", str(off), "--slot", SLOT]) + assert calls == [] + + +def test_apply_stamps_the_integration_root_on_the_record(tmp_path): + """A SEPARATE key. `- integration: yes` is the human's request and + `- integration-root:` is what happened; writing the second over the first + would erase what they asked for.""" + mind = mini_mind(tmp_path, keys="- integration: yes") + d = collected(mind, block_for()) + before = (mind / "batches" / f"{SLOT}.md").read_text(encoding="utf-8") + after = _batch.record_update(before, d, STAMP) + assert _batch._rehearse_record(mind, before, after) == [] + assert "- integration: yes" in after + assert ("- integration-root: /tmp/wt/integration-x — " + f"integration/{SLOT}; 1 clean, 1 conflicted") in after + + _batch.apply_collect(mind, d, STAMP) + written = (mind / "batches" / f"{SLOT}.md").read_text(encoding="utf-8") + assert "- integration: yes" in written and "- integration-root: " in written + + +def test_the_report_puts_the_source_line_at_the_top(tmp_path): + """The whole point of the leg is that the human can RUN the batch, and a + `source …` line five screens down is a line nobody sources.""" + mind = mini_mind(tmp_path) + body = _batch.collect_report(collected(mind, block_for())) + assert "## Integration branches" in body + assert "source /tmp/wt/integration-x/activate.sh" in body + assert body.index("## Integration branches") < body.index("## alpha") + assert ("- Example/Other — conflicted — " in body + and "collides on a.py — left out" in body) + + +def test_plan_refuses_the_collect_flag(tmp_path): + """`batch plan --integration` means something, and it is not "plan".""" + mind = mini_mind(tmp_path) + (mind / "draft").mkdir(exist_ok=True) + assert _batch.main(["plan", "--mind", str(mind), "--integration"]) == 2 From 7cdf59ce6f22a812e5c92814776291c48ff169e7 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 2 Sep 2026 13:20:46 -0400 Subject: [PATCH 5/6] docs: batch --integration in AGENTS.md, batch.sh, skills/batch (#337) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The conductor's AGENTS.md gains a constraints row, a `## Running` line and an "Integration branches (`--integration`)" subsection: the block's JSON shape, the four skip reasons (merged, closed, fork, no `head_ref`), the dirty-worktree refusal, the re-cut policy and why the refusal rather than the policy is the safety property, and that conflicts change no exit code and no member's health word. The network line is said out loud, because `AUTONOMY.md`'s "the Brain reads no network except one opt-in flag" predates this one: `--integration` fetches and reads; it never pushes, opens a PR, or touches a remote ref. Like `--fetch` it is opt-in, non-default and laptop-only, and pushing `integration/` is a separate, later decision. Also documented so the next session does not "fix" it: **collect does not rewrite your `--evidence` file.** That file is an input; persisting the block is `--json > ev.json`'s job, and a block pasted back into an evidence file is how a cloud session renders one at all. The skill says where a member has to be RUN — a library change is live anywhere once `activate.sh` is sourced, a workspace member's script must be run from inside `/` — and adds the dispatch-time line: if the human says they will want to run the batch, write `- integration: yes` into the record. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01NR2L4MT5kTP8Lu9eR7dPUP --- agents/conductors/batch/AGENTS.md | 73 ++++++++++++++++++++++++++++++- agents/conductors/batch/batch.sh | 8 ++++ skills/batch/batch.md | 15 +++++++ 3 files changed, 94 insertions(+), 2 deletions(-) diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 0c1c5086..e291869c 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -52,6 +52,7 @@ consulting a conductor. If a rule here starts needing to *judge* rather than | **`Unattended: ready` only** | `needs-slicing` goes to the decomposition pass; `never` never enters a batch | | **Lane match** | a session detects its own lane and plans only that one | | **Backpressure** | see below | +| **One integration root per slot, and it is local** | `integration/` is cut fresh from `origin/main` on every run and never pushed, so a re-run is a re-preview rather than a rewrite; a dirty integration worktree is skipped, never reset. The one-member-per-library-repo rule above is what keeps within-repo conflicts rare — the common case is one member with organ PRs across five repos. | Everything rejected says so, with its reason. A planner that silently drops work teaches the human to distrust the number it reports. @@ -108,6 +109,7 @@ pyauto-brain batch collect # score the newest record; offline pyauto-brain batch collect --slot 2026-09-03-pm pyauto-brain batch collect --evidence ev.json # PR state from this session pyauto-brain batch collect --fetch # laptop: `gh pr view` per PR +pyauto-brain batch collect --integration # laptop: merge every member's head into one worktree root pyauto-brain batch collect --evidence ev.json --apply # the one form that writes pyauto-brain batch collect --out report.md --json @@ -311,6 +313,70 @@ merged. `witness.holds` is tri-state: `true` PASS, `false` FAIL, absent UNOBSERVABLE. +### Integration branches (`--integration`) + +One throwaway worktree root per slot under `$PYAUTO_WT_ROOT`, built by +`bin/worktree.sh` with `PYAUTO_WT_BRANCH=integration/`. Every affected +repo becomes a real worktree on `integration/`, cut from `origin/main`, +with every member's head branch merged in **dispatch order** — so the human can +*run* the whole batch before ruling on any of it, and "how would these resolve +at the end?" is answered by a merge rather than by reading diffs. + +**It fetches and reads; it never pushes, opens a PR, or touches a remote ref.** +Like `--fetch` it is opt-in, non-default and laptop-only — a cloud session is +pointed at the laptop rather than failing halfway through a root it cannot +finish. Pushing `integration/` is a separate, later decision. + +```jsonc +{"slot": "2026-09-03-pm", + "root": "~/Code/PyAutoLabs-wt/integration-2026-09-03-pm", + "activate": "/activate.sh", "branch": "integration/2026-09-03-pm", + "at": "2026-09-03T08:00Z", + "repos": [{"repo": "PyAutoLabs/PyAutoFit", "dir": "PyAutoFit", + "path": "/PyAutoFit", "branch": "integration/2026-09-03-pm", + "base": "origin/main", "base_sha": "…", "head_sha": "…", + "merged": ["autofit-resampling-info"], + "conflicts": [{"member": "autoarray-x", "branch": "feature/x", + "paths": ["src/mask/mask_2d.py"]}], + "status": "clean | conflicted | skipped", "note": ""}], + "notes": ["…"]} +``` + +**Four reasons a member's PR is left out**, each said out loud: it is already +merged; it is CLOSED; it has no `head_ref` in the evidence (gathered before the +head fields were asked for — re-run `--fetch`); or its head lives on a **fork**, +whose branch is not on `origin` and cannot be merged from a local checkout at +all. A repo with no local checkout under the workspace root is dropped the same +way. + +**Nothing is resolved.** A member whose merge conflicts is left OUT of that +repo's branch and named with the conflicting paths; the merge is aborted and +the next member is tried. **That report is the product** — it does not change +the exit code, and it does not change any member's health word. A member's +health is about *its own* delivery; a merge collision is a property of the +*slot*, and mixing them would make a green, delivered member read as SUSPECT +because a sibling touched the same file. + +**A dirty integration worktree is skipped, never reset.** The branch is re-cut +from `origin/main` on every run (`checkout -B`), because the merge result is a +function of the current base and the current heads — a second run stacked onto +the first would preview a base that no longer exists. That is safe only because +the one thing a re-cut could destroy, a human's uncommitted experiment inside +the review root, is refused outright and reported. **That refusal, not the +branch policy, is the safety property.** + +`activate.sh`'s `PYTHONPATH` covers the libraries, so a **library** member's +change is live anywhere once the root is sourced. A **workspace** member is a +real worktree in the root but is not on the PYTHONPATH, so its script must be +run from inside `/`. + +**Collect does not rewrite your `--evidence` file.** That file is an *input*; +`--apply` writes exactly two things, the packet and the record's stamps. The +computed block is emitted on `--json`, rendered into the packet and stamped on +the record as `integration-root:` — persisting it is `--json > ev.json`'s job, +and a block pasted back into an evidence file is how a cloud session renders one +at all. + ### The packet is refreshed, never rewritten `--apply` writes `batches/packets/.html` in place and at the same path, @@ -328,8 +394,11 @@ header was left alone. Collect never rewrites such a page wholesale. `--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** +`delivered: n/m`, `packet:`, and — after an `--integration` run — +`integration-root:` (a key of its own: the dispatch-time +`- integration: yes` is the human's request, and is never overwritten +with a path). 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 diff --git a/agents/conductors/batch/batch.sh b/agents/conductors/batch/batch.sh index a3817b8e..95398d4a 100755 --- a/agents/conductors/batch/batch.sh +++ b/agents/conductors/batch/batch.sh @@ -20,12 +20,20 @@ # batch.sh collect --slot 2026-09-03-pm # batch.sh collect --evidence ev.json # PR state the session gathered (MCP surface) # batch.sh collect --fetch # laptop only: one `gh pr view` per PR +# batch.sh collect --integration # laptop only: merge every member's head per repo # batch.sh collect --evidence ev.json --apply [--stamp ISO] # the form that writes # batch.sh collect --out report.md --json # # collect reads and prints; only --apply writes (the packet page and the # record's stamps). Exit: 0 all delivered, 1 a member needs the human, # 2 usage, 4 no Mind. +# +# --integration builds a throwaway worktree root under $PYAUTO_WT_ROOT, one +# repo per affected library/workspace on integration/ off origin/main +# with every member's head merged in. It writes no remote: it fetches and +# merges locally, pushes nothing and opens no PR. A member whose merge +# conflicts is left out and named with the conflicting files -- that report +# is the product, and it does not move the exit code. set -uo pipefail diff --git a/skills/batch/batch.md b/skills/batch/batch.md index 295469d3..a37d8468 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -67,6 +67,9 @@ In order: is where the grant expires; **if they did not say, ask before dispatching.** It is the one thing only they know — never infer it from a schedule, a previous batch, or the time of day, and do not dispatch without it. + **If the human says they will want to *run* the batch, write + `- integration: yes` into the record** — collect then builds the review's + integration worktree without anyone remembering a flag. 3. Start one session per member, each carrying `/start_dev --auto` plus the member-session contract below — the batch record is what informs a member of the shift's grant (it reads it at leg 4), not the dispatch line. Spawn them if this harness can; otherwise hand @@ -119,6 +122,18 @@ bin/pyauto-brain batch collect --slot - --evidence ev.json --apply `--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. +- **"I want to run the whole batch."** — + `bin/pyauto-brain batch collect --slot - --integration --apply` + (laptop only). One worktree root per slot under + `~/Code/PyAutoLabs-wt/integration-/`, each affected repo on + `integration/` cut from `origin/main` with every member's head merged + in dispatch order. Hand the human the `source /activate.sh` line: once + it is sourced a **library** member's change is live anywhere (it is on the + `PYTHONPATH`), while a **workspace** member's script must be run from inside + `/`. A member that conflicts is **left out and named with + the conflicting files** — report that as the answer to "how would this + resolve at the end?", not as a failure. Nothing is pushed, no PR is opened, + no remote ref is touched. - **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. From bf3e57b588e0d7129d11b543c14ebef585952344 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 2 Sep 2026 13:24:49 -0400 Subject: [PATCH 6/6] =?UTF-8?q?batch:=20--fetch=20asks=20gh=20for=20merged?= =?UTF-8?q?At=20=E2=80=94=20there=20is=20no=20`merged`=20field=20(#337)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `gh pr view --json merged` does not drop an unknown name, it rejects the WHOLE request: "Unknown JSON field: merged" (gh 2.98). So one wrong word in `GH_FIELDS` made every PR of every `--fetch` exit 1 and be scored UNOBSERVABLE — and the report blamed the PRs, not the field list. Found driving the `--integration` smoke, which cannot run without a working `--fetch`. `mergedAt` is the same fact and is a real field; the evidence row's `merged` stays a bool, derived from it, so nothing downstream changes shape. Pinned by a test that asserts both halves — that `mergedAt` is asked for and that no bare `merged,` remains in the field list — because the failure mode is silent at the call site and only visible as a note about a PR. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01NR2L4MT5kTP8Lu9eR7dPUP --- agents/conductors/batch/_batch.py | 8 +++++-- tests/test_batch_collect.py | 38 +++++++++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 68a5b7bb..6b1e329e 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -637,8 +637,12 @@ def active_for(member: dict, active: dict) -> tuple: #: member, so a PR's own head is the only reliable source. The head *repo* is #: recorded too because a fork's head is not on `origin` and cannot be merged #: from a local checkout at all. +#: `mergedAt`, NOT `merged`: `gh pr view --json` has no `merged` field (gh +#: 2.98 rejects the whole request with "Unknown JSON field", so ONE bad name +#: made every `--fetch` PR UNOBSERVABLE rather than dropping one column). The +#: timestamp is the same fact, and `merged` is derived from it below. GH_FIELDS = ("number,url,state,additions,deletions,changedFiles,mergeable," - "merged,statusCheckRollup,headRefName,headRefOid," + "mergedAt,statusCheckRollup,headRefName,headRefOid," "headRepository,headRepositoryOwner") @@ -776,7 +780,7 @@ def fetch_evidence(members: list, active: dict) -> tuple: "deletions": data.get("deletions"), "changed_files": data.get("changedFiles"), "mergeable": data.get("mergeable"), - "merged": bool(data.get("merged")), + "merged": bool(data.get("mergedAt")), "checks": _checks_from_rollup(data.get("statusCheckRollup")), **_head_of(data, repo), }) diff --git a/tests/test_batch_collect.py b/tests/test_batch_collect.py index d889eda3..d39a9066 100644 --- a/tests/test_batch_collect.py +++ b/tests/test_batch_collect.py @@ -574,8 +574,8 @@ def fake(cmd, **_kw): calls.append(cmd) body = {"number": 1554, "url": "https://example.invalid/pull/1554", "state": "OPEN", "additions": 5, "deletions": 1, - "changedFiles": 2, "mergeable": "MERGEABLE", "merged": False, - "statusCheckRollup": [], **head} + "changedFiles": 2, "mergeable": "MERGEABLE", + "mergedAt": None, "statusCheckRollup": [], **head} return SimpleNamespace(returncode=0, stdout=json.dumps(body), stderr="") @@ -603,6 +603,40 @@ def fake(cmd, **_kw): assert got["resampling"]["prs"][0]["head_ref"] == "feature/x" +def test_fetch_asks_gh_for_mergedat_because_there_is_no_merged_field( + tmp_path, monkeypatch): + """`gh pr view --json` has no `merged` field. It does not drop an unknown + name — it rejects the WHOLE request ("Unknown JSON field: merged", gh + 2.98), so one wrong word made every PR of every `--fetch` UNOBSERVABLE and + the report blamed the PRs. `mergedAt` is the same fact, and the row's + `merged` is derived from it.""" + assert "mergedAt" in _batch.GH_FIELDS + assert "merged," not in _batch.GH_FIELDS + + rows = [{"number": 1554, "url": "u", "state": "MERGED", "additions": 5, + "deletions": 1, "changedFiles": 2, "mergeable": "UNKNOWN", + "mergedAt": "2026-09-01T19:34:55Z", "statusCheckRollup": [], + "headRefName": "feature/x", "headRefOid": "abc", + "headRepository": {"name": "ExampleFit"}, + "headRepositoryOwner": {"login": "ExampleOrg"}}] + + def fake(cmd, **_kw): + return SimpleNamespace(returncode=0, stdout=json.dumps(rows[0]), + stderr="") + + monkeypatch.setattr(_batch.shutil, "which", lambda _name: "/usr/bin/gh") + monkeypatch.setattr(_batch.subprocess, "run", fake) + mind = mini_mind(tmp_path) + members = [{"slug": "resampling", "path": "draft/bug/autofit/resampling.md"}] + got, notes = _batch.fetch_evidence(members, _batch.read_active(mind)) + assert notes == [] + assert got["resampling"]["prs"][0]["merged"] is True + + rows[0]["mergedAt"] = None + got, _n = _batch.fetch_evidence(members, _batch.read_active(mind)) + assert got["resampling"]["prs"][0]["merged"] is False + + def test_apply_writes_nothing_that_a_re_read_cannot_recover(tmp_path): """The rehearsal. A ledger half-written has no way back, so the rewrite is re-parsed on a throwaway copy before it is written for real."""