diff --git a/.github/workflows/branch_sweep.yml b/.github/workflows/branch_sweep.yml index b8cc6bf6..4f5b8e1f 100644 --- a/.github/workflows/branch_sweep.yml +++ b/.github/workflows/branch_sweep.yml @@ -26,6 +26,11 @@ name: Branch Sweep # never an open PR's head, never a branch git cannot prove is contained) live # in the script, not here — see PyAutoBrain/bin/branch_sweep.sh and # PyAutoBrain/skills/repo_cleanup/SKILL.md. +# +# `integration/*` batch review refs are the one exception to containment: they +# are merge previews, so nothing can ever prove them contained. They expire on +# the `sweep-after:` date of the batch record that published them, which is why +# PyAutoMind's `batches/` is passed as `--records`. Without it they are kept. on: workflow_dispatch: @@ -71,6 +76,13 @@ jobs: path: .brain fetch-depth: 1 + - name: Check out PyAutoMind (the batch records integration/* expires from) + uses: actions/checkout@v4 + with: + repository: ${{ github.repository_owner }}/PyAutoMind + path: .mind + fetch-depth: 1 + - name: Sweep env: GH_TOKEN: ${{ github.token }} @@ -88,6 +100,7 @@ jobs: --owner '${{ github.repository_owner }}' \ --name '${{ github.event.repository.name }}' \ --mode "$mode" \ + --records "$GITHUB_WORKSPACE/.mind/batches" \ --limit '${{ inputs.limit || 0 }}' 2>&1 | tee sweep.log # The run summary is the readable surface on a phone. diff --git a/.github/workflows/branch_sweep_all.yml b/.github/workflows/branch_sweep_all.yml index c7f12b20..3c07df99 100644 --- a/.github/workflows/branch_sweep_all.yml +++ b/.github/workflows/branch_sweep_all.yml @@ -156,6 +156,7 @@ jobs: --owner "${slug%%/*}" \ --name "$name" \ --mode "$mode" \ + --records "$PWD/.mind/batches" \ --limit '${{ inputs.limit || 0 }}' 2>&1 | tee "work/$name.log" || failed=1 { diff --git a/AUTONOMY.md b/AUTONOMY.md index 4f4556e8..acc9a442 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -557,8 +557,21 @@ tier), never by weakening leg 4. already exist upstream. It is **read-only, opt-in and non-default**: without the flag no clone, socket or subprocess is used, and a test detonates on any attempt. It ranks prompts for human review in a `needs-review` band and never - emits a shipped verdict, so it retires nothing on its own. Any *further* - network surface in the Brain is a new decision, not covered by this line. + emits a shipped verdict, so it retires nothing on its own. + + A second exception, added 2026-09-02: `batch collect --integration` fetches + and merges locally, and `--integration --push` publishes each + `integration/` to `origin`. Both are **opt-in, non-default and + laptop-only** (a remote session's credential cannot write a ref — + `skills/GITHUB_ACCESS.md`). The push writes throwaway review refs under + `integration/*` and nothing else: never `main`, never a release ref, never a + pull request, never a base for one. It is **never forced** — a branch that is + not a fast-forward of what is already published is pushed under a new `-N` + name instead — and every pushed ref carries a `sweep-after:` date on the + batch record, after which `bin/branch_sweep.sh` may delete it. + + Any *further* network surface in the Brain is a new decision, not covered by + this line. - The `Autonomy:` header is a model's own estimate. The caps, the explicit `--auto` launch, and the calibration log are what make consuming it defensible — none of the three is optional. diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index e291869c..956c18f9 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -53,6 +53,7 @@ consulting a conductor. If a rule here starts needing to *judge* rather than | **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. | +| **Publishing that root is a separate act, typed by the human** | `--push` is the only remote write the batch makes, and no record can ask for it — `- integration: yes` requests the *local* preview. What it writes is a throwaway `integration/*` review ref and nothing else: never a pull request, never a base for one, never forced. A refresh that is not a fast-forward publishes `-2` rather than moving what is already there, and the ref expires at the record's `sweep-after:`. | Everything rejected says so, with its reason. A planner that silently drops work teaches the human to distrust the number it reports. @@ -325,7 +326,8 @@ 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. +finish. Pushing `integration/` is a separate, later decision, and a +separate flag — see `--push` below. ```jsonc {"slot": "2026-09-03-pm", @@ -338,10 +340,19 @@ finish. Pushing `integration/` is a separate, later decision. "merged": ["autofit-resampling-info"], "conflicts": [{"member": "autoarray-x", "branch": "feature/x", "paths": ["src/mask/mask_2d.py"]}], - "status": "clean | conflicted | skipped", "note": ""}], + "status": "clean | conflicted | skipped", "note": "", + // --push only; "" and false on every run without it + "remote_branch": "integration/2026-09-03-pm", "pushed": true, + "push_note": ""}], + "pushed": false, "sweep_after": "", "notes": ["…"]} ``` +`status` is the merge verdict and `pushed` is the network one; they are +deliberately separate. A push that fails leaves a clean integration reading +`clean`, because whether the merge collided is a fact about the merge and a +dead network does not change it. + **Four reasons a member's PR is left out**, each said out loud: it is already merged; it is CLOSED; it has no `head_ref` in the evidence (gathered before the head fields were asked for — re-run `--fetch`); or its head lives on a **fork**, @@ -377,6 +388,52 @@ the record as `integration-root:` — persisting it is `--json > ev.json`'s job, and a block pasted back into an evidence file is how a cloud session renders one at all. +### Pushing the integration branch (`--push`) + +`--push` publishes what `--integration` built. It **requires** `--integration` +(without it, a usage error and rc 2) and it is refused on `plan` — and no +record can ask for it. `- integration: yes` is a request for the *local* +preview; putting a ref on GitHub is a separate act, typed at collect by the +human, because it writes into shared repos under the laptop's own credential. +Laptop lane only, for the same reason `--integration` is: a cloud session's +credential cannot write a ref at all, so it is pointed at the laptop rather +than failing halfway. + +**What it publishes.** One real branch per repo — `integration/` — whose +tip is exactly the state `--integration` merged. A **conflicted** repo still +publishes: its branch carries the members that merged, and the ones left out +are named, with their conflicting paths, in the same report. A pushed branch is +therefore never a claim that the whole slot merges; it is the same partial +preview, on a machine the reviewer can reach. + +**Never a PR, never a base.** These refs are review scaffolding with a +death date, not proposals. Nothing opens a pull request from one, nothing +targets one as a base, and nothing merges one anywhere. + +**Never forced.** Three arms, decided per repo after re-fetching the +`integration/*` namespace: + +- the remote branch carries the **same tree** → not re-pushed at all, and said + so. This is the common case on a refresh: `--integration` re-cuts and + re-merges honestly, so the commit SHAs differ every run even when nothing + changed. Compare trees, not commits, or every refresh mints a new name. +- the remote branch is an **ancestor** → a plain fast-forward push. +- otherwise → published as `integration/-2` (then `-3`, …, first free + name, capped). The earlier ref is left exactly where it was. There is no + `--force` and no `--force-with-lease` anywhere in this path; `branch -f` + appears once, on a *local* name already proven absent on origin. + +A push that fails is a note and a `push_note` on the row, never a change to the +merge verdict. + +**How it ends.** Every push stamps `integration-remote:` on the record and +fills `sweep-after:` (see below); `bin/branch_sweep.sh --records ` deletes `integration/*` refs on or after that date and +protects them in every other case — no records dir, no record, no date, no +deletion. That expiry is the only thing keeping these refs from accumulating: +they can never be proven contained in `main`, so the sweep's ordinary +containment gate would keep them forever. + ### The packet is refreshed, never rewritten `--apply` writes `batches/packets/.html` in place and at the same path, @@ -397,7 +454,13 @@ header was left alone. Collect never rewrites such a page wholesale. `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 ` ()` — +with a path). After an `--integration --push` run it also writes +`integration-remote:` — `:`, comma-separated, under the repo name +`branch_sweep.sh --name` matches on — **rewritten on every push**, because the +current publication is the truth and a stale list would send the sweep after a +ref that no longer exists. Alongside it, `sweep-after:` is **filled once and +never overwritten**: `review-at:` plus a week by default, and a date the human +typed is a decision about their own review. Member outcomes become ` ()` — **unless the outcome already opens with a ruling word** (`ACCEPTED`, `REJECTED`, `MERGED`, `LEAVE-TO-FINISH`, …), which is a human's verdict and is never overwritten by a machine re-read. Once the slot's review diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 6b1e329e..bf14f0e9 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -368,6 +368,30 @@ def _utc_now() -> str: return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%MZ") +#: How long a pushed `integration/` ref lives after the review it exists +#: for. A week is generous for a branch whose whole reason to exist is one +#: reading; longer, and the namespace becomes a graveyard nobody dares sweep. +SWEEP_DAYS = 7 + + +def sweep_after_default(review_at: str, notes: list) -> str: + """`review-at` plus a week — the default expiry of a pushed review ref. + + The review is the branch's reason to exist, so the review date is what the + expiry hangs off. An unparsable `review-at:` falls back to today plus the + same week and SAYS SO: a silently guessed deletion date is the one kind of + guess a branch sweep must never act on unexplained. + """ + try: + day = _dt.date.fromisoformat((review_at or "").strip()[:10]) + except ValueError: + notes.append(f"sweep-after: review-at {review_at or '(none)'!r} does " + f"not read as a date — defaulted to today + {SWEEP_DAYS} " + f"days; edit the record to change it") + day = _dt.datetime.now(_dt.timezone.utc).date() + return (day + _dt.timedelta(days=SWEEP_DAYS)).isoformat() + + def _dash(line: str) -> str: """` -- ` typed for an em dash. Records are hand-written as often as not.""" return line.replace(" -- ", " — ") @@ -1237,6 +1261,11 @@ def collect(mind: Path, slot: str, *, evidence: dict | None = None, # 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")), + # Read for `--push` only: `review-at` is what the default expiry of a + # published ref hangs off, and a `sweep-after:` the human wrote is + # theirs and wins over that default. + "review_at": (rec["keys"].get("review-at") or [""])[0].strip(), + "sweep_after": (rec["keys"].get("sweep-after") or [""])[0].strip(), "stamp": "", } @@ -1279,6 +1308,12 @@ def _integ_detail(r: dict) -> str: paths = ", ".join(c.get("paths") or []) or "(no paths reported)" detail += (f"; {c['member']} ({c['branch']}) collides on {paths} — " "left out") + if r.get("pushed") and r.get("remote_branch"): + detail += f"; pushed to origin/{r['remote_branch']}" + if r.get("push_note"): + detail += f" ({r['push_note']})" + elif r.get("push_note"): + detail += f"; NOT pushed — {r['push_note']}" return detail @@ -1295,6 +1330,10 @@ def _integration_report(d: dict) -> list: return [] L = ["## Integration branches", "", f"Run the whole batch: `source {block.get('activate', '')}`", ""] + if block.get("pushed"): + L += [f"Pushed for review; the branch sweep may delete these after " + f"**{block.get('sweep_after') or '(no sweep-after)'}**. Never a " + f"PR, never a base.", ""] L += [f"- {_integ_line(r)}" for r in block.get("repos") or []] return L + [""] @@ -1662,14 +1701,28 @@ def _integration_panel(d: dict) -> str: if not block: return "" root = block.get("root", "") + # The lede tells the truth about THIS block: "nothing is pushed" is a + # promise the panel may no longer be able to make. + pushed = bool(block.get("pushed")) + lede = ('One throwaway worktree root merges every member's head ' + 'branch per repo, off origin/main. ' + + ('Nothing is resolved: a member whose merge conflicts is left ' + 'out and named.' if pushed else + 'Nothing is pushed and nothing is resolved: a member whose ' + 'merge conflicts is left out and named.')) L = ['
', '

Integration branches

', - '

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 ' + f'

{lede}

', + f'

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

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

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

') + L += ['

Once that is sourced, a library ' 'change is live anywhere — it is on the PYTHONPATH. A ' 'workspace member is a real worktree but is not on the ' 'PYTHONPATH, so run its script from inside ' @@ -2042,6 +2095,18 @@ def record_update(text: str, d: dict, stamp: str) -> str: _set_key(lines, rec, "integration-root", f"{block.get('root', '')} — {block.get('branch', '')}; " f"{clean} clean, {bad} conflicted", inserts) + # What was PUBLISHED, per repo, under the name `branch_sweep.sh --name` + # matches on. Rewritten on every push, because the current publication + # is the truth; `sweep-after:` is filled once and never overwritten, + # because the date a human typed is a decision about their own review. + remotes = [f"{r['dir']}:{r['remote_branch']}" + for r in block.get("repos") or [] if r.get("remote_branch")] + if remotes: + _set_key(lines, rec, "integration-remote", ", ".join(remotes), + inserts) + if block.get("sweep_after"): + _fill_key(lines, rec, "sweep-after", block["sweep_after"], + inserts) review = d.get("review") if review is not None: _fill_key(lines, rec, "review", @@ -2785,8 +2850,8 @@ def cortex_ready_note(cortex_arg: str = "") -> str: #: Flags that belong to `collect` only. Passing one to `plan` is a usage error #: rather than a silent no-op: a human who types `batch plan --apply` means #: something, and it is not "plan". -COLLECT_ONLY = ("slot", "evidence", "fetch", "integration", "apply", "out", - "stamp") +COLLECT_ONLY = ("slot", "evidence", "fetch", "integration", "push", "apply", + "out", "stamp") #: …except on `plan --kind cortex`, which OPENS a board: the slot is its name, #: `--apply` writes it, and the stamp is its `dispatched:`. Only with the kind @@ -2820,6 +2885,11 @@ def main(argv=None) -> int: help="laptop: build one throwaway worktree root merging " "every member's head branch per repo, and report the " "conflicts (writes no remote, pushes nothing)") + ap.add_argument("--push", action="store_true", + help="laptop: push each integration/ to origin as a " + "throwaway review ref (needs --integration; never a " + "PR, never forced, expires at the record's " + "sweep-after:)") ap.add_argument("--apply", action="store_true", help="write the packet and update the record") ap.add_argument("--out", default="", help="write the report here") @@ -2948,6 +3018,11 @@ def _main_collect(mind: Path, a) -> int: if not (mind / "batches").is_dir(): print(f"batch: no batch records at {mind}", file=sys.stderr) return RC_NO_MIND + if a.push and not a.integration: + raise BatchUsageError( + "batch: --push publishes what --integration built — pass both. A " + "record's `- integration: yes` asks for the LOCAL preview; putting " + "a ref on GitHub is a separate act, typed at collect.") slot = a.slot or newest_slot(mind) if not slot or not (mind / "batches" / f"{slot}.md").is_file(): print(f"batch: no batch record batches/{slot or ''}.md at {mind}", @@ -2978,7 +3053,15 @@ def _main_collect(mind: Path, a) -> int: if a.integration or d.get("integration_requested"): integ = load_integration() block, inotes = integ.run(d["members"], d["dispatch_order"], slot, - lane=(a.lane or detect_lane())) + lane=(a.lane or detect_lane()), + push=a.push) + if block and a.push: + # The expiry is a fact about the RECORD, so it is filled here and + # not in the merge engine: the human's own `sweep-after:` wins, and + # the default hangs off the review the branch exists for. + block["sweep_after"] = (d.get("sweep_after") + or sweep_after_default( + d.get("review_at", ""), inotes)) d["integration"] = block d["notes"] += inotes elif isinstance(doc.get("integration"), dict): diff --git a/agents/conductors/batch/_integration.py b/agents/conductors/batch/_integration.py index c6f68c9f..f7dfc201 100644 --- a/agents/conductors/batch/_integration.py +++ b/agents/conductors/batch/_integration.py @@ -8,9 +8,13 @@ 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 writes no remote unless `--push` is typed.** By default: `git fetch + origin` and local merges; no push, no PR, no remote ref is created or moved. + `--push` adds exactly one act, `push_repo` below — it publishes each + `integration/` to `origin` as a throwaway review ref. It is never + forced (no force flag, no lease): a branch that is not a fast-forward of what + is already published is pushed under a new `-N` name and the earlier ref is + left exactly where it is. Never a pull request, never a base for one. * **It resolves nothing.** A member whose merge conflicts is left OUT of that repo's branch and named with the conflicting paths. That report is the product; it is not a failure of the collect, and it moves no exit code and no @@ -56,6 +60,16 @@ "laptop leg (real git worktrees under $PYAUTO_WT_ROOT) — run " "collect from the laptop; everything else is scored anyway.") +NOT_LOCAL_PUSH = ("batch collect --integration --push: pushing an integration " + "ref needs the laptop's own git credential — a remote " + "session's GH_TOKEN is a proxy placeholder that cannot write " + "a ref at all (skills/GITHUB_ACCESS.md). Run it from the " + "laptop; everything else is scored anyway.") + +#: How many publications of one slot this will name before it gives up. A slot +#: that has been re-published twenty times is not a review branch any more. +MAX_SUFFIX = 20 + # ------------------------------------------------------------- where things go def workspace_root() -> Path: @@ -310,18 +324,123 @@ def integrate_repo(job: dict, wt: Path, slot: str, notes: list) -> dict: return row +# ---------------------------------------------------------------- the push -- +def push_repo(row: dict, wt: Path, slot: str, notes: list) -> None: + """Publish one repo's integration branch to `origin`. Mutates `row`. + + The only remote write in this module, and the only one the batch ever makes. + It is a *throwaway review ref*: never a pull request, never a base for one, + and it expires at the record's `sweep-after:` date. + + **Nothing already on origin is ever moved.** There is no force flag and no + lease anywhere here; the four arms below are the whole decision, in order: + + 1. the merge was skipped — there is nothing to publish; + 2. `origin/` carries the SAME TREE as HEAD — not re-pushed. This arm + is load-bearing: `integrate_repo` re-cuts the branch every run + (`checkout -B` plus `--no-ff` merges), so the commit SHAs differ on every + refresh even when nothing changed. Comparing commits would make every + refresh look non-fast-forwardable and pile up `-2 … -20`; comparing trees + asks the question the human means, "is what is published still this?"; + 3. `origin/` is an ancestor of HEAD — a genuine fast-forward, pushed + plainly; + 4. otherwise the published ref and this one have diverged, so this one is + published under the first free `-N` instead and the earlier ref is + left exactly where it is. `branch -f` there only ever writes a LOCAL ref + whose name has just been proven absent on origin, so no published history + moves. + + A push that fails is a note and nothing more: `row["status"]` is never + touched, because the merge verdict is a fact about the merge and a network + failure must not turn a clean integration into a conflicted one. + """ + row["remote_branch"] = "" + row["pushed"] = False + row["push_note"] = "" + + if row.get("status") == "skipped": + row["push_note"] = "nothing was merged — nothing pushed" + return + + # The decision below rests on what is published RIGHT NOW, so the namespace + # is refreshed first. A failure is a note, not a stop — same shape as the + # fetch in `integrate_repo`. + fetched = _git("-C", str(wt), "fetch", "origin", "--quiet", + "+refs/heads/integration/*:refs/remotes/origin/integration/*", + timeout=300) + if fetched.returncode != 0: + notes.append(f"{row['repo']}: could not fetch the integration namespace " + f"({_tail(fetched)}) — the publication decision rests on " + f"the refs already here, which may be stale") + + base = branch_name(slot) + remote = f"origin/{base}" + target = base + + if _git("-C", str(wt), "rev-parse", "--verify", remote).returncode == 0: + theirs = _git("-C", str(wt), "rev-parse", f"{remote}^{{tree}}") + ours = _git("-C", str(wt), "rev-parse", "HEAD^{tree}") + same = (theirs.returncode == 0 and ours.returncode == 0 + and theirs.stdout.strip() == ours.stdout.strip()) + if same: + row["remote_branch"] = base + row["push_note"] = (f"origin/{base} already carries this exact " + f"tree — not re-pushed") + return + ff = _git("-C", str(wt), "merge-base", "--is-ancestor", remote, "HEAD") + if ff.returncode != 0: + cand = "" + for n in range(2, MAX_SUFFIX): + probe = f"{base}-{n}" + if _git("-C", str(wt), "rev-parse", "--verify", + f"origin/{probe}").returncode != 0: + cand = probe + break + if not cand: + row["push_note"] = ( + f"origin/{base} is not an ancestor of this branch, and " + f"-2 … -{MAX_SUFFIX - 1} are all published already — not " + f"pushed; sweep the old refs or collect a new slot") + notes.append(f"{row['repo']}: {row['push_note']}") + return + made = _git("-C", str(wt), "branch", "-f", cand, "HEAD") + if made.returncode != 0: + row["push_note"] = (f"could not name the local ref {cand}: " + f"{_tail(made)}") + notes.append(f"{row['repo']}: {row['push_note']}") + return + target = cand + row["push_note"] = (f"origin/{base} is not an ancestor of this " + f"branch — never force-pushed; published as " + f"{cand} instead") + + proc = _git("-C", str(wt), "push", "origin", + f"{target}:refs/heads/{target}", timeout=300) + if proc.returncode == 0: + row["remote_branch"] = target + row["pushed"] = True + return + row["pushed"] = False + row["remote_branch"] = "" + row["push_note"] = f"push failed: {_tail(proc)}" + notes.append(f"{row['repo']}: {row['push_note']}") + + # ------------------------------------------------------------------- the leg -- -def run(members: list, order: list, slot: str, *, lane: str) -> tuple: +def run(members: list, order: list, slot: str, *, lane: str, + push: bool = False) -> tuple: """`(block | None, notes)` — the whole `--integration` leg. Refuses any lane but `local-dev` with a pointer rather than a caught error, exactly as `fetch_evidence` refuses a session with no `gh`: real git worktrees under `$PYAUTO_WT_ROOT` are a laptop thing, and a cloud session - that tried would fail halfway rather than up front. + that tried would fail halfway rather than up front. `push=True` refuses the + same lanes for a second reason, and says that one instead: a remote + session's credential cannot write a ref at all. """ notes: list[str] = [] if lane != "local-dev": - return None, [NOT_LOCAL] + return None, [NOT_LOCAL_PUSH if push else NOT_LOCAL] jobs = plan_jobs(members, order, notes) if not jobs: notes.append("batch collect --integration: no member PR has a " @@ -332,11 +451,18 @@ def run(members: list, order: list, slot: str, *, lane: str) -> tuple: if root is None: return None, notes repos = [integrate_repo(j, root / j["dir"], slot, notes) for j in jobs] + if push: + for j, r in zip(jobs, repos): + push_repo(r, root / j["dir"], slot, notes) block = { "slot": slot, "root": str(root), "activate": str(root / "activate.sh"), "branch": branch_name(slot), "at": _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%MZ"), + # `sweep_after` is filled by the conductor: it is a fact about the + # RECORD (`review-at:` plus a week, or the human's own date), and this + # module never reads a record. + "pushed": bool(push), "sweep_after": "", "repos": repos, "notes": list(notes), } return block, notes diff --git a/agents/conductors/batch/batch.sh b/agents/conductors/batch/batch.sh index 95398d4a..8158f80a 100755 --- a/agents/conductors/batch/batch.sh +++ b/agents/conductors/batch/batch.sh @@ -21,6 +21,7 @@ # 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 --integration --push # laptop only: publish each integration/ # batch.sh collect --evidence ev.json --apply [--stamp ISO] # the form that writes # batch.sh collect --out report.md --json # @@ -34,6 +35,14 @@ # 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. +# +# --push (needs --integration) publishes each of those branches to origin as a +# throwaway review ref, so the preview can be read from another machine. Never +# a pull request and never a base for one; never forced -- an unchanged refresh +# is not re-pushed, a fast-forward is, and anything else is published as +# integration/-2 rather than moving what is already there. The ref +# expires at the record's sweep-after: date, when branch_sweep.sh may delete +# it. No record can ask for --push: the human types it. set -uo pipefail diff --git a/bin/branch_sweep.sh b/bin/branch_sweep.sh index d3b9e37f..ede3599a 100755 --- a/bin/branch_sweep.sh +++ b/bin/branch_sweep.sh @@ -25,6 +25,13 @@ # the Gut exists to provide. The Gut voids them, not us. # * any branch that is the head of an OPEN pull request # * any branch git cannot prove is already contained in the base +# * `integration/*` — batch review refs, +# published by `batch collect --integration --push`. These are deliberately +# NOT contained in the base — previewing a merge before it happens is the +# whole point — so the containment proof can never clear them, and they +# would otherwise be kept forever. They are cleared BY DATE ALONE: the +# `sweep-after:` on the batch record that published them, read from +# `--records`. No records dir, no record, or no date -> protected. # # Containment is decided by branch_contribution.sh — the blessed tool, never a # hand-rolled ahead-count (see docs/agent_failure_modes.md D1/D2: that question @@ -40,13 +47,18 @@ # # Usage: # branch_sweep.sh --repo --owner --name [--mode audit|delete] -# [--base origin/main] [--limit N] +# [--base origin/main] [--limit N] [--records

] +# +# --records points at a checkout of PyAutoMind's `batches/` — the only thing +# that knows when an `integration/*` ref stops being worth keeping. Omitted or +# unreadable, every integration branch is protected: the failure mode of a +# missing Mind is "keep", which is the direction that cannot lose work. # # Exit: 0 clean · 1 usage/setup error · 2 one or more deletions failed. set -uo pipefail -REPO="" OWNER="" NAME="" MODE="audit" BASE="origin/main" LIMIT=0 +REPO="" OWNER="" NAME="" MODE="audit" BASE="origin/main" LIMIT=0 RECORDS="" while [[ $# -gt 0 ]]; do case "$1" in --repo) REPO="$2"; shift 2 ;; @@ -55,11 +67,13 @@ while [[ $# -gt 0 ]]; do --mode) MODE="$2"; shift 2 ;; --base) BASE="$2"; shift 2 ;; --limit) LIMIT="$2"; shift 2 ;; + --records) RECORDS="$2"; shift 2 ;; *) echo "branch_sweep: unknown argument '$1'" >&2; exit 1 ;; esac done [[ -n "$REPO" && -n "$OWNER" && -n "$NAME" ]] || { echo "usage: branch_sweep.sh --repo --owner --name [--mode audit|delete]" >&2 + echo " [--base origin/main] [--limit N] [--records ]" >&2 exit 1 } [[ "$MODE" == "audit" || "$MODE" == "delete" ]] || { @@ -134,6 +148,36 @@ merged_pr_for() { 2>/dev/null | head -1 } +TODAY="$(date -u +%F)" + +# The date after which one `integration/*` branch may be deleted, or empty. +# +# An integration ref is a merge preview: it is cut from the base and carries +# every member's head, so it is unmergeable-by-construction and the containment +# proof will never clear it. Its licence to exist is a date, not an ancestry — +# the `- sweep-after:` on the batch record that published it, found by that +# record naming this repo and this branch in its `- integration-remote:` line +# (`:`, comma-separated, written under the same repo NAME this +# script was given as --name). No record, no date, no deletion. +integration_sweep_after() { + local b="$1" f line want pat + [[ -n "$RECORDS" && -d "$RECORDS" ]] || return 0 + # Compared as a literal: a dotted repo name (a Pages site, say) would + # otherwise bring regex wildcards to a question whose wrong answer deletes + # a branch. + want=$(printf '%s:%s' "$NAME" "$b" | sed 's/[][^$.*+?(){}|\\]/\\&/g') + # The entry must sit on its own between separators, so `MyRepo:x` + # cannot answer for `Repo:x`. + pat="^- integration-remote:.*[[:space:],:]${want}([,[:space:]]|\$)" + for f in "$RECORDS"/*.md; do + [[ -f "$f" ]] || continue + grep -qE "$pat" "$f" || continue + line=$(sed -nE 's/^- sweep-after:[[:space:]]*([0-9]{4}-[0-9]{2}-[0-9]{2}).*/\1/p' "$f" | head -1) + printf '%s' "$line" + return 0 + done +} + # Returns 0 and echoes the proving commit when `branch` is a confirmed squash # of a PR already on the base; returns 1 otherwise. squash_proof() { @@ -175,6 +219,19 @@ while read -r b; do is_trunk "$b" && continue case "$b" in archive/condemned/*) protected+=("$b gut-transit-ref"); continue ;; + integration/*) + # ISO dates compare correctly as strings. The test is >= TODAY, + # not > TODAY: `sweep-after: ` is the day the human sits + # down to read the preview, and a sweep firing that morning deletes + # the branch out from under the review it exists for. Expiry starts + # the day AFTER. + d=$(integration_sweep_after "$b") + if [[ -z "$d" ]]; then + protected+=("$b integration-no-sweep-after"); continue + elif [[ "$d" > "$TODAY" || "$d" == "$TODAY" ]]; then + protected+=("$b integration-until-$d"); continue + fi + safe+=("$b integration-expired-$d"); continue ;; esac if [[ -n "$open_prs" ]] && grep -qxF "$b" <<<"$open_prs"; then protected+=("$b open-pr"); continue diff --git a/skills/batch/batch.md b/skills/batch/batch.md index a37d8468..f954eb80 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -133,7 +133,10 @@ bin/pyauto-brain batch collect --slot - --evidence ev.json --apply `/`. 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. + no remote ref is touched. If the reviewer needs it on another machine or in + CI, add `--push`: one real `integration/` per repo, pushed with the + laptop's own git auth, never forced, never a PR, and swept after the record's + `sweep-after:` date. The first push of a slot is the human's call. - **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. diff --git a/tests/test_batch_integration.py b/tests/test_batch_integration.py index dd49159c..38086128 100644 --- a/tests/test_batch_integration.py +++ b/tests/test_batch_integration.py @@ -301,6 +301,139 @@ def test_the_worktree_root_carries_activate_sh_and_the_symlinks(ws): assert (root / "some_workspace").is_symlink() +# ---------------------------------------------------------------- the push -- +def _on_origin(wt: Path, ref: str) -> str: + """The SHA of `refs/heads/` as it really is on the origin. + + Read with `ls-remote`, never from a remote-tracking ref: the whole claim + under test is about what is published, and a stale `origin/…` in the local + checkout is exactly the thing that could fake it.""" + out = _out(wt, "ls-remote", "origin", f"refs/heads/{ref}") + return out.splitlines()[0].split("\t")[0] if out else "" + + +def test_push_puts_the_branch_on_origin_equal_to_the_local_one(ws): + """**Witness claim 1.** `--push` publishes exactly the branch the human just + previewed: same commit, one real ref, under `integration/` where the sweep + can find it. Nothing else on the remote is written.""" + ws.seed("MyRepo") + block, _notes = INTEG.run( + [member("alpha", "feature/alpha"), member("gamma", "feature/gamma")], + ["alpha", "gamma"], SLOT, lane="local-dev", push=True) + + assert block["pushed"] is True + # The conductor fills this: the date lives on the RECORD, and the merge + # engine never reads one. + assert block["sweep_after"] == "" + r = block["repos"][0] + assert r["status"] == "clean" + assert r["pushed"] is True + assert r["remote_branch"] == f"integration/{SLOT}" + assert r["push_note"] == "" + + wt = Path(r["path"]) + assert _on_origin(wt, f"integration/{SLOT}") == _out(wt, "rev-parse", "HEAD") + assert _on_origin(wt, f"integration/{SLOT}-2") == "" + + +def test_a_second_run_after_main_moves_never_moves_the_first_ref(ws): + """**Witness claim 2.** `origin/main` moved, so the honest refresh re-cuts + from the new base and the published ref is no longer an ancestor of it. A + force push would silently destroy what a reviewer may already be reading — + so the earlier ref is left exactly where it is and the refresh is published + beside it as `-2`.""" + repo = ws.seed("MyRepo") + args = ([member("alpha", "feature/alpha")], ["alpha"], SLOT) + first, _n = INTEG.run(*args, lane="local-dev", push=True) + wt = Path(first["repos"][0]["path"]) + was = _on_origin(wt, f"integration/{SLOT}") + assert was + + _git(repo, "checkout", "main") + (repo / "c.py").write_text("main moved on\n") + _git(repo, "add", "c.py") + _git(repo, "commit", "-m", "main moves") + _git(repo, "push", "origin", "main") + + second, _n = INTEG.run(*args, lane="local-dev", push=True) + r = second["repos"][0] + assert _on_origin(wt, f"integration/{SLOT}") == was # untouched + assert r["pushed"] is True + assert r["remote_branch"] == f"integration/{SLOT}-2" + assert "never force-pushed" in r["push_note"] + assert (_on_origin(wt, f"integration/{SLOT}-2") + == _out(wt, "rev-parse", "HEAD")) + + +def test_an_unchanged_refresh_does_not_mint_a_second_branch(ws): + """`integrate_repo` re-cuts the branch every run, so the commit SHA differs + on every refresh even when nothing changed. Comparing commits would make + every refresh look non-fast-forwardable and pile up `-2 … -20`; the tree + check asks what the human means — is what is published still this?""" + ws.seed("MyRepo") + args = ([member("alpha", "feature/alpha")], ["alpha"], SLOT) + first, _n = INTEG.run(*args, lane="local-dev", push=True) + wt = Path(first["repos"][0]["path"]) + was = _on_origin(wt, f"integration/{SLOT}") + + second, _n = INTEG.run(*args, lane="local-dev", push=True) + r = second["repos"][0] + assert r["pushed"] is False + assert r["remote_branch"] == f"integration/{SLOT}" + assert "already carries this exact tree" in r["push_note"] + assert _on_origin(wt, f"integration/{SLOT}") == was + assert _on_origin(wt, f"integration/{SLOT}-2") == "" + + +def test_a_conflicted_repo_still_publishes_its_partial_branch(ws): + """A conflict is a finding, not a failure — and the partial branch is the + runnable thing. It is published, and the member left out of it is named.""" + ws.seed("MyRepo") + block, _n = INTEG.run( + [member("alpha", "feature/alpha"), member("beta", "feature/beta")], + ["alpha", "beta"], SLOT, lane="local-dev", push=True) + r = block["repos"][0] + assert r["status"] == "conflicted" + assert r["merged"] == ["alpha"] + assert [c["member"] for c in r["conflicts"]] == ["beta"] + assert r["pushed"] is True + assert r["remote_branch"] == f"integration/{SLOT}" + wt = Path(r["path"]) + assert _on_origin(wt, f"integration/{SLOT}") == _out(wt, "rev-parse", "HEAD") + + +def test_a_failed_push_is_a_note_and_the_merge_verdict_stands(ws, tmp_path): + """A network failure must not turn a clean integration into a conflicted + one: the merge verdict is a fact about the merge. The push says so in its + own field and in the notes, and `status` is untouched.""" + ws.seed("MyRepo") + block, _n = INTEG.run([member("alpha", "feature/alpha")], ["alpha"], SLOT, + lane="local-dev") + r = block["repos"][0] + wt = Path(r["path"]) + _git(wt, "remote", "set-url", "origin", str(tmp_path / "not-a-repo.git")) + + notes: list = [] + INTEG.push_repo(r, wt, SLOT, notes) + assert r["status"] == "clean" + assert r["merged"] == ["alpha"] + assert r["pushed"] is False + assert r["remote_branch"] == "" + assert "push failed" in r["push_note"] + assert any("push failed" in n for n in notes) + + +def test_the_push_leg_carries_no_force_flag_at_all(): + """The property the whole design rests on, asserted against the source: a + reviewer's ref is never destroyed. The one `-f` in the module names a LOCAL + branch whose name was just proven absent on origin.""" + src = Path(INTEG.__file__).read_text(encoding="utf-8") + assert "--force" not in src + assert "--force-with-lease" not in src + assert [l.strip() for l in src.splitlines() + if '"-f"' in l and "branch" not in l] == [] + + # ------------------------------------------------- the packet and the record -- sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) _spec = importlib.util.spec_from_file_location( @@ -359,10 +492,16 @@ def mini_mind(tmp_path, *members, keys="") -> Path: return mind -def block_for(root="/tmp/wt/integration-x", slug="beta") -> dict: - return { +def block_for(root="/tmp/wt/integration-x", slug="beta", + pushed=False) -> dict: + """The block a laptop `--integration` returns. `pushed=True` is the same + block after `--push`: both repos published, including the conflicted one — + its PARTIAL branch is the runnable thing, and the member left out of it is + named on the same line.""" + block = { "slot": SLOT, "root": root, "activate": f"{root}/activate.sh", "branch": f"integration/{SLOT}", "at": STAMP, "notes": [], + "pushed": pushed, "sweep_after": "", "repos": [ {"repo": "Example/MyRepo", "dir": "MyRepo", "path": f"{root}/MyRepo", "branch": f"integration/{SLOT}", "base": "origin/main", @@ -374,6 +513,11 @@ def block_for(root="/tmp/wt/integration-x", slug="beta") -> dict: "conflicts": [{"member": slug, "branch": "feature/beta", "paths": ["a.py"]}], "status": "conflicted", "note": ""}]} + if pushed: + for r in block["repos"]: + r.update({"remote_branch": f"integration/{SLOT}", "pushed": True, + "push_note": ""}) + return block def collected(mind, block=None) -> dict: @@ -442,8 +586,9 @@ def test_a_cloud_session_says_run_it_from_the_laptop(tmp_path, capsys): def _recorder(monkeypatch) -> list: calls: list = [] - def run(members, order, slot, *, lane): - calls.append({"order": list(order), "slot": slot, "lane": lane}) + def run(members, order, slot, *, lane, push=False): + calls.append({"order": list(order), "slot": slot, "lane": lane, + "push": push}) return None, [] monkeypatch.setattr(_batch, "load_integration", @@ -458,6 +603,9 @@ def test_the_record_can_ask_for_it_at_dispatch(tmp_path, monkeypatch): mind = mini_mind(tmp_path, keys="- integration: yes") _batch.main(["collect", "--mind", str(mind), "--slot", SLOT]) assert [c["order"] for c in calls] == [["alpha"]] + # The record asks for the LOCAL preview. Putting a ref on GitHub is a + # separate act, and no key in a record may ever perform it. + assert [c["push"] for c in calls] == [False] calls.clear() off = mini_mind(tmp_path / "off", keys="- integration: no") @@ -500,3 +648,126 @@ def test_plan_refuses_the_collect_flag(tmp_path): mind = mini_mind(tmp_path) (mind / "draft").mkdir(exist_ok=True) assert _batch.main(["plan", "--mind", str(mind), "--integration"]) == 2 + + +# --------------------------------------------------------- the push, wired -- +def test_push_without_integration_is_a_usage_error(tmp_path, capsys): + """`--push` publishes what `--integration` built. Alone it would either + silently do nothing or push a branch nobody previewed; it is neither.""" + mind = mini_mind(tmp_path) + rc = _batch.main(["collect", "--mind", str(mind), "--slot", SLOT, "--push"]) + assert rc == 2 + assert "pass both" in capsys.readouterr().err + + +def test_plan_refuses_the_push_flag(tmp_path): + """`batch plan --push` means something, and it is not "plan".""" + mind = mini_mind(tmp_path) + (mind / "draft").mkdir(exist_ok=True) + assert _batch.main(["plan", "--mind", str(mind), "--push"]) == 2 + + +def test_a_cloud_session_says_run_the_push_from_the_laptop(tmp_path, capsys): + """A second reason for the same refusal, said instead of the first: a + remote session's GH_TOKEN is a proxy placeholder that cannot write a ref at + all, so "build a worktree on the laptop" would be the wrong advice.""" + mind = mini_mind(tmp_path) + rc = _batch.main(["collect", "--mind", str(mind), "--slot", SLOT, + "--integration", "--push", "--lane", "web-github"]) + out = capsys.readouterr().out + assert rc == 1 + assert "Run it from the laptop" in out + assert "GITHUB_ACCESS.md" in out + assert "## alpha — " in out # the members are still scored + + +def test_apply_stamps_the_remote_branches_and_a_default_sweep_after(tmp_path): + """What was PUBLISHED, per repo, under the name the branch sweep matches + on — and the date after which it may delete them. The default hangs off + `review-at:`, because the review is the branch's reason to exist.""" + mind = mini_mind(tmp_path, keys="- integration: yes") + d = collected(mind, block_for(pushed=True)) + assert d["review_at"] == "2026-09-04T08:00Z" + notes: list = [] + d["integration"]["sweep_after"] = _batch.sweep_after_default( + d["review_at"], notes) + assert notes == [] + + before = (mind / "batches" / f"{SLOT}.md").read_text(encoding="utf-8") + after = _batch.record_update(before, d, STAMP) + assert _batch._rehearse_record(mind, before, after) == [] + assert (f"- integration-remote: MyRepo:integration/{SLOT}, " + f"Other:integration/{SLOT}") in after + assert "- sweep-after: 2026-09-11" in after + assert "- integration: yes" in after and "- integration-root: " in after + + _batch.apply_collect(mind, d, STAMP) + written = (mind / "batches" / f"{SLOT}.md").read_text(encoding="utf-8") + assert "- integration-remote: " in written + assert "- sweep-after: 2026-09-11" in written + + +def test_a_human_written_sweep_after_is_never_overwritten(tmp_path): + """The default is a default. A date the human typed is a decision about + their own review, and a second `- sweep-after:` line would leave the sweep + reading whichever it hit first.""" + mind = mini_mind(tmp_path, + keys="- integration: yes\n- sweep-after: 2026-12-01") + d = collected(mind, block_for(pushed=True)) + assert d["sweep_after"] == "2026-12-01" + d["integration"]["sweep_after"] = d["sweep_after"] + _batch.apply_collect(mind, d, STAMP) + written = (mind / "batches" / f"{SLOT}.md").read_text(encoding="utf-8") + assert "- sweep-after: 2026-12-01" in written + assert written.count("- sweep-after:") == 1 + assert "2026-09-11" not in written + + +def test_an_unreadable_review_at_falls_back_to_today_plus_seven(tmp_path): + """A silently guessed deletion date is the one guess a branch sweep must + never act on unexplained — so the fallback says so in the notes.""" + import datetime as dt + notes: list = [] + got = _batch.sweep_after_default("(not given)", notes) + want = (dt.datetime.now(dt.timezone.utc).date() + + dt.timedelta(days=_batch.SWEEP_DAYS)).isoformat() + assert got == want + assert len(notes) == 1 + assert "does not read as a date" in notes[0] + assert "edit the record to change it" in notes[0] + + +def test_the_panel_and_the_report_name_the_remote_and_the_expiry(tmp_path): + """Written once in `_integ_detail`, so the terminal and the page cannot + report the same publication differently — and the expiry is stated on both, + because a ref with a deletion date the reader never saw is a trap.""" + mind = mini_mind(tmp_path) + block = block_for(pushed=True) + block["sweep_after"] = "2026-09-11" + d = collected(mind, block) + + body = _batch.collect_report(d) + assert f"pushed to origin/integration/{SLOT}" in body + assert "may delete these after **2026-09-11**" in body + assert "Never a PR, never a base." in body + assert "collides on a.py — left out" in body + + page, _n = _batch.packet_html(d) + region = region_of(page) + assert f"pushed to origin/integration/{SLOT}" in region + assert "2026-09-11" in region + assert "Never a PR, never a base." in region + assert "Nothing is pushed" not in region # it no longer is true + assert page.count("") == 1 + assert "data-" not in region + + +def test_an_unpushed_block_still_promises_nothing_is_pushed(tmp_path): + """The default leg's promise is unchanged — and it is the promise, not the + prose, that the flag has to be able to withdraw.""" + mind = mini_mind(tmp_path) + page, _n = _batch.packet_html(collected(mind, block_for())) + region = region_of(page) + assert "Nothing is pushed and nothing is resolved" in region + assert "pushed to origin/" not in region + assert "sweep" not in region diff --git a/tests/test_branch_sweep.py b/tests/test_branch_sweep.py index ec1d0848..41510788 100644 --- a/tests/test_branch_sweep.py +++ b/tests/test_branch_sweep.py @@ -16,6 +16,16 @@ destroys the only copy open PR heads someone's in-flight review unproven CONTRIBUTES unmerged work, gone + integration/* a batch review branch whose slot is still open — + these can never be proven contained (a merge + preview is unmergeable by construction), so a date + on the batch record is the ONLY thing standing + between one and deletion + +The integration gate is the inverse of the others: those keep a branch the +containment proof would clear, this one clears a branch the containment proof +never could. That makes its failure mode the loud kind — a missing records dir +must read as "keep", never as "no date, therefore expired". `gh` is stubbed: the script refuses to run without it (it cannot rule out open PRs blind), and these tests pin that refusal too. @@ -23,6 +33,7 @@ from __future__ import annotations +import datetime as dt import os import shutil import subprocess @@ -32,6 +43,14 @@ TOOL = Path(__file__).resolve().parents[1] / "bin" / "branch_sweep.sh" +# Dates relative to the day the test runs, never literals: a fixture pinned to +# 2026-09-03 stops testing "expired" the moment the calendar passes it, and +# would then pass for the wrong reason forever. +_TODAY = dt.date.today() +EXPIRED = (_TODAY - dt.timedelta(days=30)).isoformat() +LIVE = (_TODAY + dt.timedelta(days=30)).isoformat() +TODAY = _TODAY.isoformat() + def _git(repo: Path, *args: str) -> str: return subprocess.run( @@ -72,6 +91,27 @@ def world(tmp_path: Path): _git(origin, "checkout", "-q", "-b", name, "main") _git(origin, "checkout", "-q", "main") + # Three batch review branches, each carrying unique content main has never + # seen — exactly what a merge preview looks like. Without the integration + # arm all three read as CONTRIBUTES/unmerged and are kept forever; with it, + # only the date on the record decides. + records = tmp_path / "records" + records.mkdir() + for slot, after in ((EXPIRED, EXPIRED), (LIVE, LIVE), (TODAY, TODAY)): + branch = f"integration/{slot}-pm" + _git(origin, "checkout", "-q", "-b", branch, "main") + _commit(origin, f"i-{slot}", slot, f"integration preview {slot}") + _git(origin, "checkout", "-q", "main") + # `n` is the --name this fixture sweeps under, which is the name the + # record writes into `integration-remote:`. + (records / f"{slot}-pm.md").write_text( + f"# Batch {slot} pm\n" + f"- dispatched: {slot}T17:40Z\n" + f"- integration-remote: other-repo:integration/{slot}-pm, " + f"n:integration/{slot}-pm\n" + f"- sweep-after: {after}\n" + ) + clone = tmp_path / "clone" subprocess.run( ["git", "clone", "-q", str(origin), str(clone)], check=True @@ -92,6 +132,12 @@ def world(tmp_path: Path): return clone, origin, bin_dir +def _records(clone: Path) -> Path: + """The `world` fixture's records dir. Derived rather than returned, so the + three-value unpacking every existing test does keeps working.""" + return clone.parent / "records" + + def _gh_free_path(tmp_path: Path) -> str: """A PATH with everything the script needs except `gh`. @@ -108,17 +154,18 @@ def _gh_free_path(tmp_path: Path) -> str: return str(lean) -def _sweep(clone: Path, bin_dir: Path | None, mode: str = "audit") -> subprocess.CompletedProcess: +def _sweep(clone: Path, bin_dir: Path | None, mode: str = "audit", + records: Path | None = None) -> subprocess.CompletedProcess: env = dict(os.environ) if bin_dir is not None: env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}" else: env["PATH"] = _gh_free_path(clone.parent) - return subprocess.run( - ["bash", str(TOOL), "--repo", str(clone), "--owner", "o", "--name", "n", - "--mode", mode], - capture_output=True, text=True, env=env, timeout=120, - ) + cmd = ["bash", str(TOOL), "--repo", str(clone), "--owner", "o", "--name", "n", + "--mode", mode] + if records is not None: + cmd += ["--records", str(records)] + return subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=120) def test_audit_classifies_every_branch(world): @@ -265,3 +312,88 @@ def test_rejects_unknown_mode(world): proc = _sweep(clone, bin_dir, mode="purge") assert proc.returncode == 1 assert "must be 'audit' or 'delete'" in proc.stderr + + +# --- integration/* : cleared by date, or not at all -------------------------- + + +def test_an_expired_integration_branch_is_sweepable(world): + """The only gate here that ever RELEASES a branch, so it has to be exact. + + An integration ref is a merge preview: cut from the base with every + member's head merged in, it is unmergeable by construction and no + containment proof will ever clear it. Left to the other gates it would sit + on origin forever. Its licence is the `sweep-after:` on the batch record + that published it, and once that date is behind us the branch is spent. + """ + clone, _, bin_dir = world + out = _sweep(clone, bin_dir, records=_records(clone)).stdout + assert f"integration/{EXPIRED}-pm\tintegration-expired-{EXPIRED}" in out + # released into the delete set, not merely reported somewhere + assert out.index("CONTAINED IN") < out.index(f"integration/{EXPIRED}-pm\tinteg") + + +def test_an_unexpired_integration_branch_is_protected(world): + """Two branches the sweep must not touch: one whose date is still ahead, + and one whose date is TODAY. + + The same-day case is the one worth pinning. `sweep-after: ` is the + day the human sits down to read the preview, and a sweep that fires that + morning deletes the branch out from under the review it exists for. The + comparison is strictly greater-than-today, never greater-or-equal. + """ + clone, _, bin_dir = world + out = _sweep(clone, bin_dir, records=_records(clone)).stdout + protected = out.split("PROTECTED (never swept)")[1].split("\n\n")[0] + assert f"integration/{LIVE}-pm\tintegration-until-{LIVE}" in protected + assert f"integration/{TODAY}-pm\tintegration-until-{TODAY}" in protected + + +def test_an_integration_branch_with_no_record_is_protected(world): + """No records dir means no dates, and no dates must mean KEEP. + + The whole mechanism hangs off a checkout of PyAutoMind's `batches/` that a + workflow may simply fail to make. If a missing Mind read as "no date, + therefore expired", one bad checkout step would delete every open slot's + review branch across the org — the precise failure this direction exists to + make impossible. + """ + clone, origin, bin_dir = world + out = _sweep(clone, bin_dir).stdout + protected = out.split("PROTECTED (never swept)")[1].split("\n\n")[0] + for slot in (EXPIRED, LIVE, TODAY): + assert f"integration/{slot}-pm\tintegration-no-sweep-after" in protected + + assert _sweep(clone, bin_dir, mode="delete").returncode == 0 + remaining = set(_git(origin, "for-each-ref", "--format=%(refname:short)", + "refs/heads").split()) + assert {f"integration/{slot}-pm" for slot in (EXPIRED, LIVE, TODAY)} <= remaining + + +def test_delete_removes_only_the_expired_integration_branch(world): + clone, origin, bin_dir = world + assert _sweep(clone, bin_dir, mode="delete", + records=_records(clone)).returncode == 0 + remaining = set(_git(origin, "for-each-ref", "--format=%(refname:short)", + "refs/heads").split()) + assert f"integration/{EXPIRED}-pm" not in remaining + assert {f"integration/{LIVE}-pm", f"integration/{TODAY}-pm"} <= remaining + # the other gates are unmoved by the new arm + assert {"main", "unmerged", "open-pr-head", + "archive/condemned/something"} <= remaining + + +def test_a_record_naming_another_repo_does_not_answer_for_this_one(world): + """`integration-remote:` is `:`, comma-separated, and the repo + half is load-bearing: one slot publishes the same branch NAME into every + affected repo, so matching on the branch alone would let one repo's record + expire another repo's ref. + """ + clone, _, bin_dir = world + records = _records(clone) + for f in records.glob("*.md"): + f.write_text(f.read_text().replace(f"n:integration/", "nn:integration/")) + out = _sweep(clone, bin_dir, records=records).stdout + assert "integration-expired" not in out + for slot in (EXPIRED, LIVE, TODAY): + assert f"integration/{slot}-pm\tintegration-no-sweep-after" in out