diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 0f977619..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 @@ -291,6 +293,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,8 +305,78 @@ 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. +### 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, @@ -320,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.py b/agents/conductors/batch/_batch.py index 0f09012f..6b1e329e 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -373,6 +373,22 @@ def _dash(line: str) -> str: return line.replace(" -- ", " — ") +#: The spellings a hand-written record's boolean key is allowed to use. +YES_WORDS = ("yes", "true", "on", "1") + + +def _yes(values) -> bool: + """Is this record key asking for something? `read_record` keeps every value + of every key in file order, so a key is a LIST; the FIRST value is the + answer and a later `- integration: no` does not un-ask it — the same rule + `collected:` follows (the first collect owns it).""" + if isinstance(values, str): + values = [values] + for v in values or []: + return str(v).strip().casefold() in YES_WORDS + return False + + def parse_member(raw: str) -> dict | None: """` - : — — — `, or None. @@ -616,8 +632,18 @@ 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. +#: `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") + "mergedAt,statusCheckRollup,headRefName,headRefOid," + "headRepository,headRepositoryOwner") def load_evidence(path) -> dict: @@ -633,6 +659,38 @@ def load_evidence(path) -> dict: return {k: v for k, v in members.items() if isinstance(v, dict)} +def load_evidence_doc(path) -> dict: + """The whole evidence document. `load_evidence` deliberately returns only + its members; this returns the wrapper too, because `integration` is + slot-level rather than per member — and a laptop's integration block pasted + into a cloud session is how a non-laptop surface renders one at all.""" + try: + data = json.loads(Path(path).read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + return data if isinstance(data, dict) else {} + + +#: The integration leg lives in its own module: it is a git engine, it imports +#: nothing from here, and a session that never types `--integration` never pays +#: for it. Loaded by file location and cached, exactly like the Cortex +#: conductor below — and for the same reason. +INTEGRATION_MOD = (BRAIN / "agents" / "conductors" / "batch" / + "_integration.py") +_INTEG = None + + +def load_integration(): + global _INTEG + if _INTEG is None: + spec = importlib.util.spec_from_file_location( + "_batch_integration_leg", INTEGRATION_MOD) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + _INTEG = mod + return _INTEG + + def _checks_from_rollup(rollup) -> list: """`statusCheckRollup` — two shapes in one list. A check run reports `status`/`conclusion`; a commit status context reports `state` only, and a @@ -653,6 +711,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. @@ -704,8 +780,9 @@ 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), }) if prs: out[m["slug"]] = {"prs": prs} @@ -1154,6 +1231,12 @@ def collect(mind: Path, slot: str, *, evidence: dict | None = None, if s["health"] == "NOT-DELIVERED"], "rulings": [(s["slug"], _ruling_line(s)) for s in scored], "unparsable": rec["unparsable"], + # `members` above is sorted by HEALTH, so it cannot drive a merge + # order. Dispatch order is a property of the record — the order the + # human listed the members in — and it is the order `--integration` + # merges heads in, so the preview matches the shift. + "dispatch_order": [m["slug"] for m in rec["members"]], + "integration_requested": _yes(rec["keys"].get("integration")), "stamp": "", } @@ -1183,6 +1266,39 @@ def _ruling_line(s: dict) -> str: # ------------------------------------------------------- report and JSON --- +def _integ_detail(r: dict) -> str: + """One repo's outcome, minus its name and its status word — what the packet + puts after the chip and the report puts after both. Written once so the + terminal and the page cannot report the same merge differently.""" + if r.get("status") == "skipped": + return r.get("note") or "nothing to cut from" + merged = ", ".join(r.get("merged") or []) + detail = (f"{r.get('branch')} — {len(r.get('merged') or [])} member(s) " + "merged" + (f": {merged}" if merged else "")) + for c in r.get("conflicts") or []: + paths = ", ".join(c.get("paths") or []) or "(no paths reported)" + detail += (f"; {c['member']} ({c['branch']}) collides on {paths} — " + "left out") + return detail + + +def _integ_line(r: dict) -> str: + return f"{r.get('repo', '')} — {r.get('status', '')} — {_integ_detail(r)}" + + +def _integration_report(d: dict) -> list: + """The copy-paste line first, at the top of the report: the whole point of + the leg is that the human can RUN the batch, and a `source …` line five + screens down is a line nobody sources.""" + block = d.get("integration") + if not block: + return [] + L = ["## Integration branches", "", + f"Run the whole batch: `source {block.get('activate', '')}`", ""] + L += [f"- {_integ_line(r)}" for r in block.get("repos") or []] + return L + [""] + + def collect_report(d: dict) -> str: L = [f"# Batch collect {d['slot']}", ""] if d["not_delivered"]: @@ -1194,6 +1310,7 @@ def collect_report(d: dict) -> str: 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}", ""] + L += _integration_report(d) for s in d["members"]: L += _member_report(s) if d["review"] is not None: @@ -1531,6 +1648,45 @@ def _rulings(d: dict) -> str: return "\n".join(L) +CHIP_FOR_STATUS = {"clean": "chip-healthy", "conflicted": "chip-failed", + "skipped": "chip-pending"} + + +def _integration_panel(d: dict) -> str: + """The integration block, rendered. Every value goes through `_e` and the + panel carries no `data-*` hook: `packet.js` queries `[data-ruled]`, + `[data-decision]`, `[data-note]` and `[data-meta]` only, and there is + nothing for the human to *rule* about a merge preview — it is a finding they + read, not a control they operate.""" + block = d.get("integration") + if not block: + return "" + root = block.get("root", "") + L = ['
', + '

Integration branches

', + '

One throwaway worktree root merges every member's head ' + 'branch per repo, off origin/main. Nothing is pushed and ' + 'nothing is resolved: a member whose merge conflicts is left out and ' + 'named.

', + f'

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

', + '

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

', + '
    '] + for r in block.get("repos") or []: + status = str(r.get("status") or "") + chip = CHIP_FOR_STATUS.get(status, "chip-pending") + L.append(f'
  • {_e(r.get("repo", ""))} ' + f'{_e(status)} — ' + f'{_e(_integ_detail(r))}
  • ') + if not (block.get("repos") or []): + L.append("
  • No repo had a mergeable member head.
  • ") + L += ['
', '
'] + return "\n".join(L) + + def _sidenav(d: dict) -> str: L = ['