Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/workflows/branch_sweep.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 }}
Expand All @@ -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.
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/branch_sweep_all.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

{
Expand Down
17 changes: 15 additions & 2 deletions AUTONOMY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<slot>` 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.
Expand Down
69 changes: 66 additions & 3 deletions agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<slot>` 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.
Expand Down Expand Up @@ -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/<slot>` is a separate, later decision.
finish. Pushing `integration/<slot>` is a separate, later decision, and a
separate flag — see `--push` below.

```jsonc
{"slot": "2026-09-03-pm",
Expand All @@ -338,10 +340,19 @@ finish. Pushing `integration/<slot>` 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**,
Expand Down Expand Up @@ -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/<slot>` — 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/<slot>-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 <a checkout of
PyAutoMind/batches>` 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/<slot>.html` in place and at the same path,
Expand All @@ -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 `<HEALTH> (<one line of evidence>)` —
with a path). After an `--integration --push` run it also writes
`integration-remote:` — `<Repo>:<branch>`, 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 `<HEALTH> (<one line of evidence>)` —
**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
Expand Down
101 changes: 92 additions & 9 deletions agents/conductors/batch/_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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/<slot>` 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(" -- ", " — ")
Expand Down Expand Up @@ -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": "",
}

Expand Down Expand Up @@ -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


Expand All @@ -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 + [""]

Expand Down Expand Up @@ -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&#x27;s head '
'branch per repo, off <code>origin/main</code>. '
+ ('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 = ['<section class="panel" id="integration">',
' <h2>Integration branches</h2>',
' <p>One throwaway worktree root merges every member&#x27;s head '
'branch per repo, off <code>origin/main</code>. Nothing is pushed and '
'nothing is resolved: a member whose merge conflicts is left out and '
'named.</p>',
f' <p><code>source {_e(block.get("activate", ""))}</code></p>',
' <p class="smallprint">Once that is sourced, a <strong>library</strong> '
f' <p>{lede}</p>',
f' <p><code>source {_e(block.get("activate", ""))}</code></p>']
if pushed:
L.append(
' <p class="smallprint">Pushed for review; the branch sweep may '
'delete these after <strong>'
f'{_e(block.get("sweep_after") or "(no sweep-after)")}</strong>. '
'Never a PR, never a base. A pushed branch carries only the '
'members that merged — each one named <code>left out</code> below '
'is not in it.</p>')
L += [' <p class="smallprint">Once that is sourced, a <strong>library</strong> '
'change is live anywhere — it is on the <code>PYTHONPATH</code>. A '
'<strong>workspace</strong> member is a real worktree but is not on the '
'PYTHONPATH, so run its script from inside '
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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/<slot> 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")
Expand Down Expand Up @@ -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 '<none>'}.md at {mind}",
Expand Down Expand Up @@ -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):
Expand Down
Loading
Loading