From 35aa7b49c9908cd84ba5330c11396c1af8b779e9 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 19 Nov 2026 16:19:16 +0000 Subject: [PATCH 1/3] =?UTF-8?q?M3.7e:=20shift-end=20cloud=20sweep=20?= =?UTF-8?q?=E2=80=94=20dispatch=20at=20close,=20read=20each=20tick,=20bloc?= =?UTF-8?q?k=20on=20red=20(#692)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ruling S4 and the red handling (AUTONOMY.md "Shift speed — 2026-11-19"): - finish_shift dispatches workspace-smoke.yml once (no inputs, marker sweep.dispatched) when GitHub confirmed a library or workspace PR merged this shift; never in a shadow or fake shift; a failed dispatch is reported in the digest and never retried. - One gh run list a shift tick; each run's artifacts downloaded once per run id (at most 3 tries), cached in /sweep/ across shifts. - A red latest run blocks unattended close-outs on its failing workspaces' install chains (Heart config/repos.yaml smoke:) and workspace repos; unmapped or unreadable means every library repo. Running close-outs get a .sweep-red marker the close-out template checks before merging. - A later green run or the new /clear-sweep steer command clears it. - One bug draft per red run through the one Mind writer, with failing scripts and suspect PRs from one compare read per affected repo. - Digest: dispatch state, verified-through SHA per library, red line. - All sweep calls under the human's gh login (decision b); repo and workflow from config/policy.yaml shift_watcher: sweep_*. - AUTONOMY.md network-surface amendment, batch AGENTS.md, cockpit skill. Co-Authored-By: Claude Opus 5.5 --- AUTONOMY.md | 60 +- agents/conductors/batch/AGENTS.md | 28 +- agents/conductors/batch/_digest.py | 61 ++ agents/conductors/batch/_orchestrator.py | 159 ++++- agents/conductors/batch/_sweep.py | 605 +++++++++++++++++++ agents/conductors/batch/_watch.py | 2 +- agents/conductors/batch/closeout_template.md | 5 +- config/policy.yaml | 15 + skills/cockpit/cockpit.md | 4 +- tests/conftest.py | 8 + tests/test_cockpit_skill.py | 2 +- tests/test_shift_end_sweep.py | 565 +++++++++++++++++ 12 files changed, 1499 insertions(+), 15 deletions(-) create mode 100644 agents/conductors/batch/_sweep.py create mode 100644 tests/test_shift_end_sweep.py diff --git a/AUTONOMY.md b/AUTONOMY.md index 6eeca9f5..918a06b8 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -342,7 +342,8 @@ never an assumption: speed — 2026-11-19" below; M3.7b, PyAutoBrain#688). The pre-merge smoke is the worker's targeted smoke, and PR CI must be green. The full sweep runs in the cloud after the merge: the Workspace Smoke workflow, nightly - (M3.7d) and at shift end (M3.7e). Until S2 the close-out ran + (M3.7d), and at the close of every shift that merged a library or + workspace PR (M3.7e, live; S4 below). Until S2 the close-out ran `pyauto-heart smoke --affected-by --jobs 3` on the PR head; S2's revert condition brings that back. - *PRs bound for the human's `/prm`* (`decision-taken`, `judge`, a @@ -569,7 +570,34 @@ Watcher latency (M3.7c, the human's plan decisions of 2026-11-19): close resumes it in a later shift. A shift that never started anything, or a shadow shift, stays open to `review-at:`. -A later ruling from the same review (S4) is added to this section. +- **S4, the shift-end sweep** (M3.7e, PyAutoBrain#692). A shift that + merged at least one library or workspace PR dispatches the Workspace + Smoke workflow once at its close: after the last merge, before the digest. + The dispatch has no inputs, so the workflow's own SHA gate decides whether + to sweep; it is never forced. A shift with no such merge, or a shadow + shift, dispatches nothing. A failed dispatch is not retried: the digest + says "sweep not dispatched", and the human runs it from chat. The sweep + takes about 30 minutes. The digest is not held for it: it says "sweep + running" or "not yet listed", and the next shift's ticks read the result. + Each tick of a shift reads the workflow's latest runs on `main`. The + digest names, per library, the SHA the latest green sweep verified. +- **Red handling** (M3.7e). When the latest completed sweep on `main` is red + (failure, cancelled or timed out), no unattended close-out starts on a + repo in a failing workspace's install chain (Heart `config/repos.yaml` + `smoke:`) or on that workspace's own repo. The PR is refused for `/prm` + as `workspace sweep red: `. PRs on other repos still close out. + A failing workspace the watcher cannot map, or a report it cannot read, + blocks every library repo. A close-out already running on a blocked repo + finds a `.sweep-red` marker and refuses before it merges. The block holds + in this shift and the next, until a later sweep on `main` is green or the + human posts `/clear-sweep` on the shift issue. `/clear-sweep` clears the + latest red run only; a newer red run blocks again. The red run files one + bug draft through the one Mind writer, naming the failing scripts, the + blocked repos and the suspect PRs (merged between the last green sweep's + SHAs and the red one's). Reverts are draft PRs opened for the human; + nothing is reverted unattended. Bisection is dispatched from a chat + session (`workspace-smoke-pinned.yml` with `commit_shas`), never by the + watcher. ## Merge authority follows Consequence — 2026-10-02 @@ -1280,6 +1308,34 @@ per shift. When GitHub cannot say it reads again, at most once a tick; after 3 misses over 15 minutes from first seeing the PR, the PR goes to `/prm`. The kick file that starts a tick early is local and adds no network act. +**Amendment — 2026-11-19 (M3.7e, PyAutoBrain#692), approved by the human +(ruling S4; decision b).** For the shift-end sweep ("Shift speed — +2026-11-19", S4 and red handling) the watcher's surface gains: + +- **one `gh workflow run`** of the Workspace Smoke workflow per shift, at + its close, with no inputs. Its marker is claimed exclusively before the + call, and a failed dispatch is never retried. This is the one watcher + write not made under the App token: it runs under the human's own `gh` + login (decision b); +- **one `gh run list`** of that workflow's runs on `main` a tick, while a + shift's tick runs; +- **`gh run download`** of a run's two artifacts (`workspace-smoke-shas`, + and `workspace-validation-report` for a run that did not succeed), once + per run id, at most 3 tries ever, cached in the watcher's home; +- **one `compare` read** (`gh api repos///compare/…`) per + affected repo per red run, cached, for the suspect PRs; +- **the bug draft** for a red run, one per run id, through the one Mind + writer (no new network act); +- **`/clear-sweep`** joins the command set, under the same rules as the + others (the configured login, the first line, after `dispatched:`, once by + id). It clears the block for the latest red run only and is acknowledged + in the status comment. + +These reads use the human's `gh` login too. The run list, downloads and +compares make no writes. *Revert condition:* a second dispatch in one +shift, more than one run list a tick, or a download or compare for the same +run id beyond its tries retires the watcher to fake mode. + **Login probe — 2026-11-17.** The watcher runs `claude auth status --json` (local, no model call) on a shift's first tick and when a worker shows as blocked. `loggedIn: false`, or a `loginExpiresAt` already passed, is a `login-expired` event, never "blocked on a person", and no worker starts until it passes. ## Human override for Heart RED (development only) diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 5b38aedd..5c71110b 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -394,6 +394,30 @@ close-out, no merge slot and no CI read. It stays an earlier PR in the merge order, so later PRs on its library wait until GitHub says MERGED or CLOSED. The digest's `### Waited behind your /prm` names them, one line per library. +**S4: the shift-end sweep and the red block (M3.7e, PyAutoBrain#692).** +`_sweep.py` holds the mechanics; `config/policy.yaml` `shift_watcher:` +names the workflow (`sweep_repo`, `sweep_workflow`, `sweep_siblings`). At +close, `finish_shift` dispatches the Workspace Smoke workflow once +(`gh workflow run`, no inputs, marker `sweep.dispatched`) when GitHub +confirmed a library or workspace PR merged this shift. A shadow shift +never does, and a failed dispatch is not retried. Each shift tick makes one +`gh run list` of the workflow on `main`, before steering. Each run's +artifacts are downloaded once per run id, at most 3 tries, into +`/sweep/`, which every shift shares. When the latest completed run is +red and not cleared, `_start_closeouts` refuses a PR on a failing +workspace's chain (Heart `config/repos.yaml` `smoke:`, read locally, plus +the workspace repo from Heart's validation workflow) as `workspace sweep +red: `, right after the S7 check. An unmapped workspace or an +unreadable report blocks every library repo. A running close-out on a +blocked repo gets `leases/.sweep-red` and refuses before it merges. +A later green run clears the block, as does `/clear-sweep`. The red run +files one bug draft (`draft/bug// +workspace_sweep_red_.md`, marker `sweep/drafted/`) through the one +Mind writer, with suspect PRs from one compare read per affected repo. All +these calls use the human's own `gh` login (decision b). The digest's +`### Workspace sweep` names the dispatch, the verified SHA per library and +any red block. Nothing in the watcher reverts or bisects. + **Deploy.** Installing the units is the human's step, when no shift is live: cp bin/systemd/pyauto-orchestrator.{service,timer,path} ~/.config/systemd/user/ @@ -760,7 +784,9 @@ per command; the draft on origin/main becomes a named task, refused within 30 min of `review-at:`; it overrides `exclude:` and an earlier shift's parked hold, never the organ rule) and `/kill ` (the watcher runs a local `claude stop` on that task's running worker; the reap marks the exit `killed`, not crashed, -and it is re-dispatched once unless dropped first). Each comment acts once, by id, and is acknowledged +and it is re-dispatched once unless dropped first). M3.7e adds `/clear-sweep`, making +eight: it clears the red sweep block for the latest red run id only +(`/sweep/cleared.json`, kept for later shifts). Each comment acts once, by id, and is acknowledged once in the status comment's `Commands` list. Without a login, nothing is read and the comment says steering is off. The dashboard's copy is the record's `- live:` line (`record-key` op, one Mind writer, on a change of state), shown in diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index c9ef6b2f..6f062070 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -763,6 +763,7 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, lines += cap_lines(counters) lines += ["", WORKERS_HEADING] + (worker_lines(counters, links) or [NO_PICKS]) lines += ["", REFUSALS_HEADING] + (refusal_lines(counters) or [NO_PICKS]) + lines += sweep_lines(counters) lines += report_lines(slot) lines += identity_lines(counters) # The readiness pass's count is the digest's last line (M3.3, #671). @@ -776,6 +777,66 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, return "\n".join(lines) + "\n" +SWEEP_HEADING = "### Workspace sweep" +#: The prefix of the close-out refusal a red sweep gives (M3.7e). +SWEEP_RED_WHY = "workspace sweep red: " + + +def _sweep_own(sweep: dict, at: str) -> dict | None: + """The run the shift's own dispatch started (`_sweep.own_run`).""" + import _sweep # noqa: E402 — deferred: the digest builds without it + return _sweep.own_run({"runs": sweep.get("runs") or []}, at) + + +def sweep_lines(counters: dict) -> list[str]: + """The shift-end cloud sweep (M3.7e, PyAutoBrain#692): the shift's own + dispatch and its run, what the latest green sweep verified per library, + and a red sweep's block, refusals and bug draft. The digest is never held + for the sweep. Nothing when the sweep is off.""" + sweep, disp = counters.get("sweep") or {}, counters.get("sweep_dispatch") or {} + if not sweep and not disp: + return [] + out = [] + if disp: + if not disp.get("ok"): + out.append(f"- sweep not dispatched ({disp.get('error') or '?'}) — run it from chat") + else: + own = _sweep_own(sweep, disp.get("at", "")) + if own is None: + out.append(f"- sweep dispatched at {disp.get('at', '?')}, not yet listed") + elif own.get("status") != "completed": + out.append(f"- sweep running: {own.get('url')}") + else: + out.append(f"- this shift's sweep finished: {own.get('conclusion') or '?'} — " + f"{own.get('url')}") + read = sweep.get("read") or {} + if read.get("at") and not read.get("ok"): + out.append(f"- sweep runs unreadable at {read['at']} ({read.get('error') or '?'}); " + "the last known state is below") + if sweep.get("error"): + out.append(f"- sweep state could not be worked out: {sweep['error']}") + green = sweep.get("green") or {} + run = green.get("full_sweep_run_id") or green.get("id") or "?" + for lib, sha in (green.get("verified") or {}).items(): + out.append(f"- {lib}: workspaces verified through `{sha}` (run {run})") + blk = sweep.get("block") + if blk: + repos = ", ".join((["every library repo"] if blk.get("all_libraries") else []) + + list(blk.get("repos") or [])) or "?" + refused = [pr_ref(pr) for pr, co in (counters.get("closeouts") or {}).items() + if str(co.get("why") or "").startswith(SWEEP_RED_WHY)] + draft = f"`{blk['draft']}`" if blk.get("draft") else "not filed yet" + out.append(f"- workspace sweep red: {blk.get('url')} — blocked: {repos}; PRs refused: " + f"{', '.join(refused) or 'none'}; bug draft: {draft}") + cleared = sweep.get("cleared") + if cleared: + out.append(f"- red sweep {cleared.get('url')} cleared by /clear-sweep " + f"({cleared.get('by', '?')}, {cleared.get('at', '?')})") + if not out: + out.append("- no sweep run known yet") + return ["", SWEEP_HEADING] + out + + _REPORT_WORDS = { "skipped": "note: Mind ledger op skipped", "set-aside": "warning: Mind ledger op set aside, not committed", diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 47d19528..432ef918 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -29,8 +29,8 @@ PyAutoMind `questions.md` through the one Mind writer, and the digest counts it. Each open tick also reads the shift issue's comments once, for the human's `/pause` `/resume` `/drop` -`/stop` (#622) and `/add` `/cap` `/kill` (#644). Every tick that does work -appends what it did to the slot's `events.jsonl` (`_events`, #644), which +`/stop` (#622), `/add` `/cap` `/kill` (#644) and `/clear-sweep` (M3.7e). Every +tick that does work appends what it did to the slot's `events.jsonl` (`_events`, #644), which `batch watch --stream` prints; a needs-you event is also one short comment on the shift issue, at most `EVENT_COMMENTS_MAX` a shift. """ @@ -54,6 +54,7 @@ import _merge_slots # noqa: E402 — one merge-cap count per shift (R3, #661) import _mind_writer # noqa: E402 import _questions # noqa: E402 +import _sweep # noqa: E402 — the shift-end cloud sweep (M3.7e, PyAutoBrain#692) STOP_FILE = "STOP" LOCK_FILE = "tick.lock" @@ -2227,6 +2228,10 @@ def known(task: str) -> bool: named = {task_id(p) for p in _brief.tasks_of(brief)} return task in named or task in {task_id(m["path"]) for m in plan()["members"]} + # The cloud sweep (M3.7e): one run-list read a tick, before steering, so a + # `/clear-sweep` this tick clears the red run this tick reads. + if not _brief.is_shadow(brief): + _sweep_read(slot, counters, now) # The human steers from the shift issue (#622): read once, before anything # this tick starts, so a /pause or /drop binds on the tick that reads it. ctx = {"brief": brief, "now": now, "mind": mind, @@ -2243,6 +2248,9 @@ def known(task: str) -> bool: # A /stop this tick: from here on it is the STOP file's tick. return {"action": "stopped", "reason": f"{STOP_FILE} written by /stop", "reaped": reaped, "commands": commands} + if not _brief.is_shadow(brief): + _sweep_tick(slot, counters, now) # the red block and its one bug draft + _write_counters(slot, counters) # One Mind writer: whatever the workers queued is committed here, by the # orchestrator alone, from a temporary worktree — never by a worker. ledger = {"committed": None, "ops": 0} @@ -2803,10 +2811,10 @@ def _mentions(slot: Path, counters: dict, shift: dict, poster, now: _dt.datetime #: rewritten through the one Mind writer when the shift's state changes. LIVE_KEY_FILE = "live.key" #: The steering commands, read from the human's comments on the shift issue -#: (#622; `/add`, `/cap` and `/kill` from #644). -COMMANDS = ("pause", "resume", "drop", "stop", "add", "cap", "kill") +#: (#622; `/add`, `/cap` and `/kill` from #644; `/clear-sweep` from M3.7e, #692). +COMMANDS = ("pause", "resume", "drop", "stop", "add", "cap", "kill", "clear-sweep") _COMMAND_RE = re.compile( - r"^/(pause|resume|drop|stop|add|cap|kill)\b[ \t]*(\S+)?(?:[ \t]+(\S+))?[ \t]*$") + r"^/(pause|resume|drop|stop|add|cap|kill|clear-sweep)\b[ \t]*(\S+)?(?:[ \t]+(\S+))?[ \t]*$") #: The one verb that takes two arguments (`/cap `). _TWO_ARGS = ("cap",) _TASK_ARG_RE = re.compile(r"^[A-Za-z0-9_./-]+$") @@ -2927,10 +2935,11 @@ def _apply_command(slot: Path, counters: dict, cmd: str, arg: str, who: str, whether a task belongs to this shift (a pick, a lease, a brief or plan member). `ctx` is what `/add`, `/cap` and `/kill` judge against: the brief as written, `now`, `review_at` and the Mind checkout.""" - if cmd in ("add", "cap", "kill"): + if cmd in ("add", "cap", "kill", "clear-sweep"): ctx = ctx or {} try: - return {"add": _cmd_add, "cap": _cmd_cap, "kill": _cmd_kill}[cmd]( + return {"add": _cmd_add, "cap": _cmd_cap, "kill": _cmd_kill, + "clear-sweep": _cmd_clear_sweep}[cmd]( slot, counters, arg, who, at, ctx) except Exception as e: # one command's failure is its ack, never the tick's return f"refused: /{cmd} could not be judged ({str(e)[:200]})" @@ -3286,6 +3295,130 @@ def _cmd_kill(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict return f"stopping {task}'s worker {key} (claude stop). {tail}" +# --- the shift-end cloud sweep (M3.7e, PyAutoBrain#692; ruling S4) ------------------- + +def _sweep_cfg() -> dict: + """The sweep's repo and workflow (`config/policy.yaml` `shift_watcher:` + `sweep_repo`, `sweep_workflow`, `sweep_siblings`); empty: the sweep is + off — always in fake mode (a dry shift makes no GitHub call).""" + if os.environ.get(FAKE_ENV) == "1": + return {} + return _sweep.config(POLICY_PATH) + + +def _is_library(repo: str) -> bool: + from _sizing import LIBRARY_REPOS # noqa: E402 — the batch conductor's path + return _repo_key(repo) in LIBRARY_REPOS if repo else False + + +def _is_flow_repo(repo: str) -> bool: + """A library or workspace repo: a merge there is one the sweep covers.""" + from _sizing import LIBRARY_REPOS, WORKSPACE_REPOS # noqa: E402 + return _repo_key(repo) in (LIBRARY_REPOS | WORKSPACE_REPOS) if repo else False + + +def _sweep_blocks(blk: dict | None, pr: str) -> bool: + """Whether the red sweep `blk` blocks an unattended merge of `pr`.""" + return _sweep.blocks(blk, pr_repos(pr), _repo_key, _is_library) + + +def _sweep_dispatch(slot: Path, counters: dict, now: _dt.datetime, + start: _dt.datetime | None = None) -> None: + """The one `gh workflow run` of the sweep at shift close (S4), under the + human's own `gh` login (decision b): only when GitHub confirmed at least + one library or workspace PR merged this shift (`counters["github"]`, + read just before). `sweep.dispatched` is claimed exclusively first, so a + retried close never dispatches twice; a failed dispatch is recorded for + the digest and never retried.""" + cfg = _sweep_cfg() + if not cfg: + return + merged = [] + for url, gh in (counters.get("github") or {}).items(): + if not (isinstance(gh, dict) and gh.get("in_window")) or not _is_flow_repo(pr_repos(url)): + continue + at = _iso_or_none(gh.get("mergedAt") or "") + if start is not None and at is not None and at < start: + continue # a carried PR merged before this shift began + merged.append(url) + if not merged: + return + if not _create_exclusive(slot / _sweep.DISPATCH_MARKER, {"at": _iso(now), "prs": merged}): + return + try: + res = _sweep.dispatch(cfg) + except Exception as e: # noqa: BLE001 — a failed dispatch is the digest's line + res = {"ok": False, "error": f"{type(e).__name__}: {e}"[:200]} + counters["sweep_dispatch"] = {"at": _iso(now), "prs": merged, **res} + + +def _sweep_tick(slot: Path, counters: dict, now: _dt.datetime) -> None: + """The sweep this tick: the one run-list read (skipped when this tick has + made it), the red block, the red run's one bug draft (queued for the one + Mind writer) and the snapshot the close-outs and the digest read + (`counters["sweep"]`). A failure keeps the last known block.""" + cfg = _sweep_cfg() + if not cfg: + return + home = slot.parent + try: + state = _sweep.observe(home, cfg, now) + # Heart's maps are read (locally) only when a red run needs them. + hmap = _sweep.heart_map() if _sweep.red_run(home, state) else {} + blk = _sweep.block(home, cfg, hmap, _repo_key, state) + if blk: + _sweep.file_draft(home, cfg, hmap, blk, slot / _mind_writer.LEDGER_DIR, now, + _repo_key, _is_library, _mind_writer.queue_op) + counters["sweep"] = _sweep.snapshot(home, cfg, state, blk, _repo_key, _is_library) + except Exception as e: # noqa: BLE001 — never the tick's failure + counters["sweep"] = {**(counters.get("sweep") or {}), + "error": f"{type(e).__name__}: {e}"[:200]} + + +def _sweep_read(slot: Path, counters: dict, now: _dt.datetime) -> None: + """The tick's one run-list read, made before steering.""" + cfg = _sweep_cfg() + if not cfg: + return + try: + _sweep.observe(slot.parent, cfg, now) + except Exception as e: # noqa: BLE001 + counters["sweep"] = {**(counters.get("sweep") or {}), + "error": f"{type(e).__name__}: {e}"[:200]} + + +def _sweep_red_markers(slot: Path, counters: dict) -> None: + """`/.sweep-red` (the run URL) for each running close-out + on a blocked repo: the session checks it right before merging and refuses + (closeout_template.md step 7). Once the block is gone (a green run, + `/clear-sweep`) the markers are removed.""" + blk = (counters.get("sweep") or {}).get("block") + if not blk: + for marker in (slot / "leases").glob(f"*{_sweep.SWEEP_RED_SUFFIX}"): + marker.unlink(missing_ok=True) + return + for pr, co in (counters.get("closeouts") or {}).items(): + if co.get("state") != "running" or not co.get("task") or not _sweep_blocks(blk, pr): + continue + marker = slot / "leases" / f"{co['task']}{_sweep.SWEEP_RED_SUFFIX}" + if not marker.exists(): + marker.parent.mkdir(parents=True, exist_ok=True) + marker.write_text(blk["url"] + "\n", encoding="utf-8") + + +def _cmd_clear_sweep(slot: Path, counters: dict, arg: str, who: str, at: str, + ctx: dict) -> str: + """`/clear-sweep`: the human clears the red block for the latest red run id + only, recorded in `/sweep/cleared.json` (it carries to later shifts). + A newer red run blocks again.""" + if arg: + return "ignored: /clear-sweep takes no argument" + if not _sweep_cfg(): + return ("ignored: no workspace sweep is configured (`config/policy.yaml` " + "`shift_watcher: sweep_repo:`)") + return _sweep.clear(slot.parent, who, at) + + # --- the event stream's watcher side (#644) -------------------------------------------- #: Needs-you event comments a shift may post (human ruling H4b), then one @@ -3776,6 +3909,11 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, if not _brief.is_shadow(brief): _github_merges(counters, closed_at or _brief._iso( (top.get("review-at") or {}).get("value", "")), pr_state) + # S4 (M3.7e): the one sweep dispatch, after the last merge and before + # the digest; then this tick's one read of the sweep, if not made yet. + _sweep_dispatch(slot, counters, now, + _brief._iso((top.get("dispatched") or {}).get("value", ""))) + _sweep_tick(slot, counters, now) issue = (top.get("issue") or {}).get("value", "") if issue.startswith("http"): # The digest is about to be posted: an App identity that cannot be had @@ -3948,6 +4086,7 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti counters["slot_holders"] = _merge_slots.holders(slot) except (_merge_slots.MergeSlotError, OSError) as e: events["slots_error"] = str(e)[:300] # a take reads what is there, or cannot tell + _sweep_red_markers(slot, counters) if _brief.is_shadow(brief) or counters.get("paused"): return events # paused (#622): an open PR waits; it is not refused return _start_closeouts(slot, brief, counters, spawner, now, health, events, @@ -4444,6 +4583,12 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: if DECISION_TAKEN in labels: refuse(pr, task, DECISION_TAKEN_WHY, held=again) continue + # The red sweep (M3.7e): a PR on a failing workspace's install chain + # is the human's /prm until a later sweep is green or /clear-sweep. + blk = (counters.get("sweep") or {}).get("block") + if _sweep_blocks(blk, pr): + refuse(pr, task, blk["why"], held=again) + continue # Merge order (M3.6j): an earlier library PR of this shift still open # holds this one back. Waiting is not a refusal and takes no slot. An # earlier PR whose close-out is running (waiting in-turn on its CI, diff --git a/agents/conductors/batch/_sweep.py b/agents/conductors/batch/_sweep.py new file mode 100644 index 00000000..fa2ccb54 --- /dev/null +++ b/agents/conductors/batch/_sweep.py @@ -0,0 +1,605 @@ +"""The shift-end cloud workspace sweep (M3.7e, PyAutoBrain#692; ruling S4). + +AUTONOMY.md "Shift speed — 2026-11-19" (S4 and the red handling) and "The +watcher's network surface" (amendment 2026-11-19, M3.7e). The watcher: + +- dispatches the sweep workflow once at shift close, when the shift merged + at least one library or workspace PR (`dispatch`), with no inputs — never + `force`, never the pinned (bisect) entry; +- reads the workflow's latest runs on `main` once a tick (`observe`): one + `gh run list`, then each run's two artifacts (`workspace-smoke-shas`, and + `workspace-validation-report` for a run that did not succeed) downloaded + once per run id, at most `DOWNLOAD_TRIES` tries ever, cached in + `/sweep/` and shared by every shift; +- blocks unattended merges on the repos of a red run's failing workspaces + (`block`) until a later run on `main` is green or the human posts + `/clear-sweep` (`clear`); +- files one bug draft per red run through the one Mind writer (`file_draft`), + naming the failing scripts and the suspect PRs (one `compare` read per + affected repo per red run, cached). + +Every call runs under the human's own `gh` login (decision b): `run_gh` passes +no App token. Which repo and workflow come from `config/policy.yaml` +`shift_watcher:` (`sweep_repo`, `sweep_workflow`, `sweep_siblings`); the +install chains from Heart's `config/repos.yaml` `smoke:` block and the +workspace map of its validation workflow, read from the local Heart checkout. +Nothing here names an instance repo. +""" + +from __future__ import annotations + +import datetime as _dt +import json +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +#: The artifacts the sweep uploads (PyAutoHeart workspace-smoke.yml, M3.7d). +SHAS_ARTIFACT = "workspace-smoke-shas" +SHAS_FILE = "shas.json" +REPORT_ARTIFACT = "workspace-validation-report" +REPORT_FILE = "report.json" +#: Tries per artifact per run id, ever (the first included). +DOWNLOAD_TRIES = 3 +#: Runs listed a tick: the latest completed one and any still running. +RUN_LIST_LIMIT = 10 +#: Conclusions that make a run red. A gate run that skipped the sweep ends +#: `success` and is green. +RED = ("failure", "cancelled", "timed_out", "startup_failure") +SWEEP_DIR = "sweep" +STATE_FILE = "state.json" +CLEARED_FILE = "cleared.json" +DRAFTED_DIR = "drafted" +#: `/sweep.dispatched`: claimed exclusively before the one dispatch. +DISPATCH_MARKER = "sweep.dispatched" +#: `/.sweep-red`: a running close-out checks it before merging. +SWEEP_RED_SUFFIX = ".sweep-red" +RED_WHY = "workspace sweep red: {url}" +#: A dispatched run is matched by `createdAt` at most this long before the +#: recorded dispatch time (the two clocks differ). +DISPATCH_SLACK_S = 120 +ALL_LIBRARIES = "every library repo" +_MERGE_RE = re.compile(r"^Merge pull request #(\d+)\b") +_SQUASH_RE = re.compile(r"\(#(\d+)\)\s*$") +_WS_MAP_RE = re.compile(r"declare -A WS=\((.*?)\)\n", re.S) +_WS_PAIR_RE = re.compile(r"\[(\w+)\]=([\w.-]+)") + + +def _iso(t: _dt.datetime) -> str: + return t.astimezone(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _parse(text: str) -> _dt.datetime | None: + try: + return _dt.datetime.fromisoformat(str(text).replace("Z", "+00:00")) + except ValueError: + return None + + +def _first_line(text: str) -> str: + return next((ln.strip() for ln in (text or "").splitlines() if ln.strip()), "")[:200] + + +# --- configuration (declared surfaces only) --------------------------------------------- + +def config(policy_path: Path) -> dict: + """`shift_watcher:` `sweep_repo` (`/`), `sweep_workflow` and + `sweep_siblings` from the Brain's policy file. No repo: the sweep is off.""" + try: + import yaml + cfg = (yaml.safe_load(Path(policy_path).read_text(encoding="utf-8")) or {}) + sw = cfg.get("shift_watcher") or {} + except Exception: # noqa: BLE001 — an unreadable policy turns the sweep off + sw = {} + repo = str(sw.get("sweep_repo") or "").strip() + workflow = str(sw.get("sweep_workflow") or "").strip() + if not re.fullmatch(r"[\w.-]+/[\w.-]+", repo) or not workflow: + return {} + sib = sw.get("sweep_siblings") or {} + return {"repo": repo, "workflow": workflow, + "siblings": {str(k): str(v) for k, v in sib.items()} if isinstance(sib, dict) else {}} + + +def heart_root() -> Path | None: + """The Heart checkout: `$PYAUTO_HEART`, else the shared repo resolver.""" + env = os.environ.get("PYAUTO_HEART") + if env: + return Path(env) + try: + sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + from _pyauto_root import pyauto_root # noqa: E402 + from _repo_paths import repo_path # noqa: E402 + return repo_path(pyauto_root(), "PyAutoHeart") + except Exception: # noqa: BLE001 — no Heart: every name is unknown + return None + + +def heart_map(root: Path | None = None) -> dict: + """{"chains": {workspace: [repo, …]}, "dirs": {workspace: repo}, + "projects": {cloud project: repo}} from the Heart checkout: `smoke:` in + `config/repos.yaml` and the `declare -A WS=(…)` map of + `.github/workflows/workspace-validation.yml`. Local reads; a file that + cannot be read gives empty maps (every name unknown).""" + root = root if root is not None else heart_root() + out = {"chains": {}, "dirs": {}, "projects": {}} + if root is None: + return out + try: + import yaml + cfg = yaml.safe_load((Path(root) / "config" / "repos.yaml").read_text()) or {} + for name, ws in ((cfg.get("smoke") or {}).get("workspaces") or {}).items(): + if isinstance(ws, dict): + out["chains"][str(name)] = [str(r) for r in ws.get("chain") or []] + if ws.get("directory"): + out["dirs"][str(name)] = str(ws["directory"]) + except Exception: # noqa: BLE001 + pass + try: + text = (Path(root) / ".github" / "workflows" / "workspace-validation.yml").read_text() + m = _WS_MAP_RE.search(text) + if m: + out["projects"] = dict(_WS_PAIR_RE.findall(m.group(1))) + except OSError: + pass + return out + + +# --- the one runner: the human's own gh login (decision b) ------------------------------- + +def run_gh(argv: list[str], timeout: int = 120) -> subprocess.CompletedProcess: + """Run one `gh` call under the human's own login: no `GH_TOKEN` from the + watcher's App is passed (AUTONOMY.md amendment 2026-11-19, M3.7e). The + test suite replaces this function (tests/conftest.py).""" + return subprocess.run(argv, capture_output=True, text=True, timeout=timeout) + + +def _call(argv: list[str], timeout: int = 120) -> tuple[int, str, str]: + try: + res = run_gh(argv, timeout) + except subprocess.TimeoutExpired: + return 124, "", "gh timed out" + except OSError as e: + return 127, "", f"gh could not run: {e}" + return res.returncode, res.stdout or "", res.stderr or "" + + +def dispatch(cfg: dict) -> dict: + """The one `gh workflow run` at shift close, with no inputs: the workflow's + own SHA gate decides whether to sweep. Never retried by the caller.""" + rc, out, err = _call(["gh", "workflow", "run", cfg["workflow"], "-R", cfg["repo"]]) + if rc == 0: + return {"ok": True} + return {"ok": False, "error": _first_line(err or out) or f"exit {rc}"} + + +def list_runs(cfg: dict) -> tuple[list[dict] | None, str]: + """The workflow's latest runs on `main`, newest first; (None, why) when + GitHub could not say.""" + rc, out, err = _call(["gh", "run", "list", "-R", cfg["repo"], "--workflow", cfg["workflow"], + "--branch", "main", "--limit", str(RUN_LIST_LIMIT), "--json", + "databaseId,status,conclusion,url,createdAt,event"], timeout=60) + if rc != 0: + return None, _first_line(err or out) or f"exit {rc}" + try: + data = json.loads(out or "") + except ValueError: + return None, "gh run list: not JSON" + if not isinstance(data, list): + return None, "gh run list: not a list" + runs = [] + for r in data: + if not isinstance(r, dict) or r.get("databaseId") in (None, ""): + continue + runs.append({"id": str(r["databaseId"]), "status": str(r.get("status") or ""), + "conclusion": str(r.get("conclusion") or ""), "url": str(r.get("url") or ""), + "createdAt": str(r.get("createdAt") or ""), "event": str(r.get("event") or "")}) + runs.sort(key=lambda r: (r["createdAt"], int(r["id"]) if r["id"].isdigit() else 0), + reverse=True) + return runs, "" + + +def _download(cfg: dict, run_id: str, artifact: str, name: str) -> dict | None: + """One `gh run download` of one artifact; its JSON file, else None. The + artifact is data: only `json.loads` reads it.""" + with tempfile.TemporaryDirectory(prefix="pyauto-sweep-") as d: + rc, _out, _err = _call(["gh", "run", "download", str(run_id), "-R", cfg["repo"], + "-n", artifact, "-D", d], timeout=120) + if rc != 0: + return None + try: + data = json.loads((Path(d) / name).read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return data if isinstance(data, dict) else None + + +def compare_prs(cfg: dict, repo: str, base: str, head: str) -> list[int] | None: + """The PR numbers merged in `base...head` of `/` (the sweep + repo's owner): "Merge pull request #N" first lines and squash "(#N)" + suffixes. None when GitHub could not say.""" + owner = cfg["repo"].split("/", 1)[0] + rc, out, _err = _call(["gh", "api", f"repos/{owner}/{repo}/compare/{base}...{head}", + "--jq", "[.commits[].commit.message]"], timeout=60) + if rc != 0: + return None + try: + msgs = json.loads(out or "") + except ValueError: + return None + if not isinstance(msgs, list): + return None + prs: list[int] = [] + for msg in msgs: + first = str(msg or "").split("\n", 1)[0].strip() + m = _MERGE_RE.match(first) or _SQUASH_RE.search(first) + if m and int(m.group(1)) not in prs: + prs.append(int(m.group(1))) + return prs + + +# --- state under /sweep ----------------------------------------------------------- + +def sweep_dir(home: Path) -> Path: + return Path(home) / SWEEP_DIR + + +def _read(path: Path) -> dict: + try: + data = json.loads(Path(path).read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +def _write(path: Path, data: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(data, indent=2, sort_keys=True), encoding="utf-8") + os.replace(tmp, path) + + +def load_state(home: Path) -> dict: + return _read(sweep_dir(home) / STATE_FILE) + + +def run_record(home: Path, run_id: str) -> dict: + return _read(sweep_dir(home) / "runs" / f"{run_id}.json") + + +def _report_of(data: dict) -> dict: + """The failing scripts and projects of a `report.json` (PyAutoHands' + aggregate, read the way Heart's test_run leg reads it: `failures` entries + with `project`, `directory`, `file`, `status`; `per_project` counts).""" + failing, projects = [], [] + for e in data.get("failures") or []: + if not isinstance(e, dict): + continue + path = str(e.get("file") or "") + directory = str(e.get("directory") or "").strip("/") + name = path.rsplit("/", 1)[-1] + proj = str(e.get("project") or "") + failing.append({"project": proj, "status": str(e.get("status") or ""), + "script": f"{directory}/{name}" if directory else path.lstrip("/")}) + if proj and proj not in projects: + projects.append(proj) + per = data.get("per_project") or {} + if isinstance(per, dict): + for proj, s in per.items(): + if isinstance(s, dict) and (int(s.get("failed") or 0) or int(s.get("timeout") or 0)) \ + and proj not in projects: + projects.append(str(proj)) + return {"failing": failing, "projects": projects, "ready": data.get("ready")} + + +def _fetch(home: Path, cfg: dict, run: dict, red: bool) -> dict: + """The run's artifacts, each downloaded once per run id (at most + DOWNLOAD_TRIES tries ever), kept in `/sweep/runs/.json`.""" + path = sweep_dir(home) / "runs" / f"{run['id']}.json" + rec = _read(path) or {"id": run["id"]} + rec.update(url=run["url"], conclusion=run["conclusion"], createdAt=run["createdAt"]) + wants = [("shas", SHAS_ARTIFACT, SHAS_FILE)] + if red: + wants.append(("report", REPORT_ARTIFACT, REPORT_FILE)) + for key, artifact, name in wants: + tries = int(rec.get(f"{key}_tries") or 0) + if rec.get(key) is not None or tries >= DOWNLOAD_TRIES: + continue + rec[f"{key}_tries"] = tries + 1 + data = _download(cfg, run["id"], artifact, name) + if data is not None: + rec[key] = data if key == "shas" else _report_of(data) + _write(path, rec) + return rec + + +def settled(rec: dict, red: bool) -> bool: + """Whether every artifact of a run is read, or its tries are spent.""" + keys = ("shas", "report") if red else ("shas",) + return all(rec.get(k) is not None or int(rec.get(f"{k}_tries") or 0) >= DOWNLOAD_TRIES + for k in keys) + + +def is_red(run: dict | None) -> bool: + return bool(run) and run.get("status") == "completed" and run.get("conclusion") in RED + + +def observe(home: Path, cfg: dict, now: _dt.datetime) -> dict: + """The tick's one read of the sweep (once a tick: `read_at`). Returns the + state; a failed list keeps the last known runs, with the error noted.""" + state = load_state(home) + if not cfg or state.get("read_at") == _iso(now): + return state + state["read_at"] = _iso(now) + runs, why = list_runs(cfg) + if runs is None: + state.update(ok=False, error=why) + _write(sweep_dir(home) / STATE_FILE, state) + return state + state.update(ok=True, error="", runs=runs) + done = [r for r in runs if r["status"] == "completed"] + state["latest"] = done[0] if done else state.get("latest") + state["running"] = [r for r in runs if r["status"] != "completed"] + greens = [r for r in done if r["conclusion"] == "success"] + old = state.get("last_green") or {} + if greens and greens[0]["createdAt"] >= str(old.get("createdAt") or ""): + state["last_green"] = greens[0] + latest = state.get("latest") + if latest: + _fetch(home, cfg, latest, is_red(latest)) + green = state.get("last_green") + if green and (not latest or green["id"] != latest["id"]): + _fetch(home, cfg, green, False) + _write(sweep_dir(home) / STATE_FILE, state) + return state + + +# --- the block --------------------------------------------------------------------------- + +def cleared(home: Path) -> dict: + return _read(sweep_dir(home) / CLEARED_FILE) + + +def red_run(home: Path, state: dict | None = None) -> dict | None: + """The latest completed run, when it is red and not cleared.""" + latest = (state if state is not None else load_state(home)).get("latest") + if not is_red(latest) or latest["id"] in cleared(home): + return None + return latest + + +def _repos_for(project: str, hmap: dict, cfg: dict) -> list[str] | None: + """The install chain plus the workspace repo of one failing cloud project, + or None when the name cannot be mapped.""" + chains, dirs = hmap.get("chains") or {}, hmap.get("dirs") or {} + own = (hmap.get("projects") or {}).get(project) or dirs.get(project) + if project in chains: + return list(chains[project]) + ([own] if own else []) + sib = (cfg.get("siblings") or {}).get(project) + if sib and sib in chains and own: + return list(chains[sib]) + [own] + return None + + +def block(home: Path, cfg: dict, hmap: dict, key, state: dict | None = None) -> dict | None: + """The red block, or None: {run_id, url, repos (as Heart writes them), + keys (canonical keys, `key`), all_libraries, projects}. A failing project + that cannot be mapped, or a report that cannot be read, blocks every + library repo (fail closed).""" + run = red_run(home, state) + if run is None: + return None + rec = run_record(home, run["id"]) + report = rec.get("report") + projects = list((report or {}).get("projects") or []) + repos: list[str] = [] + unknown = not projects + for p in projects: + got = _repos_for(p, hmap, cfg) + if got is None: + unknown = True + continue + repos += [r for r in got if r not in repos] + return {"run_id": run["id"], "url": run["url"], "repos": repos, + "keys": sorted({key(r) for r in repos}), "all_libraries": unknown, + "projects": projects, "why": RED_WHY.format(url=run["url"])} + + +def blocks(blk: dict | None, repo: str, key, is_library) -> bool: + """Whether a PR on `repo` (its GitHub name) is blocked by `blk`.""" + if not blk or not repo: + return False + if blk.get("all_libraries") and is_library(repo): + return True + return key(repo) in set(blk.get("keys") or []) + + +def clear(home: Path, who: str, at: str, state: dict | None = None) -> str: + """`/clear-sweep`: clear the block for the latest red run id only.""" + state = state if state is not None else load_state(home) + run = red_run(home, state) + if run is None: + latest = state.get("latest") + if is_red(latest): + return (f"nothing to clear: the red sweep {latest['url']} is already cleared") + return "nothing to clear: no red workspace sweep blocks merges" + data = cleared(home) + data[run["id"]] = {"url": run["url"], "by": who, "at": at} + _write(sweep_dir(home) / CLEARED_FILE, data) + return (f"cleared: workspace sweep red {run['url']} no longer blocks unattended merges; " + "a newer red sweep blocks again") + + +# --- the bug draft ----------------------------------------------------------------------- + +def _order(hmap: dict) -> dict[str, int]: + """Upstream first: each repo's earliest place in any install chain.""" + out: dict[str, int] = {} + for chain in (hmap.get("chains") or {}).values(): + for i, r in enumerate(chain): + out[r] = min(out.get(r, i), i) + return out + + +def suspects(home: Path, cfg: dict, blk: dict, base: dict, head: dict) -> dict: + """{repo: [PR numbers] | None} for each affected repo whose SHA moved from + the last green run to the red one: one compare read per repo per red run, + cached (None: unreadable).""" + path = sweep_dir(home) / "compare" / f"{blk['run_id']}.json" + cache = _read(path) + moved = sorted(r for r in head if base.get(r) and head.get(r) and base[r] != head[r]) + wanted = set(blk.get("repos") or []) + affected = [r for r in moved if blk.get("all_libraries") or r in wanted] + for r in affected: + if r in cache: + continue + cache[r] = compare_prs(cfg, r, base[r], head[r]) + _write(path, cache) + return {r: cache.get(r) for r in affected} + + +def draft_text(cfg: dict, blk: dict, rec: dict, green: dict | None, prs: dict | None, + target: str, repos: list[str], day: str) -> str: + owner = cfg["repo"].split("/", 1)[0] + report = rec.get("report") + lines = [f"# Workspace sweep red on main: run {blk['run_id']}", "", + "Type: bug", f"Target: {target}", "Repos:"] + lines += [f"- {r}" for r in repos] + lines += ["Difficulty: medium", "Autonomy: supervised", "Priority: high", + "Status: draft", f"Filed: {day}", + "Consequence: judge", + "", "## Finding", "", + f"The cloud workspace sweep (`{cfg['workflow']}` on `{cfg['repo']}`) concluded " + f"`{rec.get('conclusion') or '?'}` on `main`: {blk['url']}", ""] + if report is None: + lines += ["Failing workspaces and scripts: unknown — the run's " + f"`{REPORT_ARTIFACT}` artifact could not be read.", ""] + else: + lines += ["Failing workspaces: " + (", ".join(f"`{p}`" for p in blk["projects"]) + or "none named in the report"), "", + "Failing scripts:"] + lines += [f"- `{f['project']}`: `{f['script']}` ({f['status'] or '?'})" + for f in report.get("failing") or []] or ["- none named in the report"] + lines += [""] + lines += ["Unattended merges are blocked on: " + + (ALL_LIBRARIES if blk["all_libraries"] else ", ".join(blk["repos"])) + + ". A later green sweep on `main` clears the block, or `/clear-sweep` " + "on a shift issue.", "", "## Suspect PRs", ""] + if not green: + lines += ["No green sweep on `main` is known to compare against: no suspects named."] + elif prs is None: + lines += ["The last green sweep's or this run's tested SHAs could not be read: " + "no suspects named."] + else: + lines += [f"Merged between the last green sweep ({green.get('url', '?')}) and this run:", ""] + for repo, nums in prs.items(): + if nums is None: + lines.append(f"- `{repo}`: compare unreadable — check its merges by hand") + elif nums: + lines.append(f"- `{repo}`: " + ", ".join( + f"[#{n}](https://github.com/{owner}/{repo}/pull/{n})" for n in nums)) + else: + lines.append(f"- `{repo}`: moved, but no PR merge found in the compare") + if not prs: + lines.append("- no affected repo moved between the two runs") + lines += ["", "## What to do", "", + "Reverts are draft PRs opened for the human; nothing is reverted unattended. " + "Bisect from a chat session: dispatch `workspace-smoke-pinned.yml` with its " + "`commit_shas` input set to the SHAs to test (the red run's are in its " + f"`{SHAS_ARTIFACT}` artifact).", ""] + return "\n".join(lines) + + +def draft_path(blk: dict, prs: dict | None, hmap: dict, cfg: dict, key, is_library) -> str: + """`draft/bug//…`; no suspect + library: the sweep repo's key.""" + order = _order(hmap) + sus = [r for r, nums in (prs or {}).items() if nums and is_library(r)] + sus.sort(key=lambda r: order.get(r, 999)) + target = key(sus[0]) if sus else key(cfg["repo"].split("/", 1)[1]) + return f"draft/bug/{target}/workspace_sweep_red_{blk['run_id']}.md" + + +def file_draft(home: Path, cfg: dict, hmap: dict, blk: dict | None, ledger_dir: Path, + now: _dt.datetime, key, is_library, queue_op) -> str | None: + """One bug draft per red run id, ever: once its artifacts are settled, + the compares are read (cached), the marker `/sweep/drafted/` is + claimed exclusively, then one `write` op is queued for the one Mind + writer. Returns the draft path when this call filed it.""" + if not blk: + return None + rec = run_record(home, blk["run_id"]) + if not settled(rec, True): + return None + marker = sweep_dir(home) / DRAFTED_DIR / str(blk["run_id"]) + if marker.exists(): + return None + state = load_state(home) + green = state.get("last_green") + if green and green.get("id") == blk["run_id"]: + green = None + base = (run_record(home, green["id"]).get("shas") or {}).get("commit_shas") if green else None + head = (rec.get("shas") or {}).get("commit_shas") + prs = suspects(home, cfg, blk, base, head) \ + if isinstance(base, dict) and isinstance(head, dict) else None + path = draft_path(blk, prs, hmap, cfg, key, is_library) + sus = [r for r, nums in (prs or {}).items() if nums] + repos = sus or [cfg["repo"].split("/", 1)[1]] + text = draft_text(cfg, blk, rec, green, prs, path.split("/")[2], repos, + now.strftime("%Y-%m-%d")) + marker.parent.mkdir(parents=True, exist_ok=True) + try: + fd = os.open(marker, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) + except FileExistsError: + return None + with os.fdopen(fd, "w") as fh: + fh.write(path + "\n") + queue_op(ledger_dir, {"op": "write", "path": path, "text": text}) + return path + + +def drafted(home: Path, run_id: str) -> str: + try: + return (sweep_dir(home) / DRAFTED_DIR / str(run_id)).read_text().strip() + except OSError: + return "" + + +# --- what the digest reads --------------------------------------------------------------- + +def own_run(state: dict, dispatched_at: str) -> dict | None: + """The run the shift's own dispatch started: event `workflow_dispatch`, + created at or after the dispatch (less DISPATCH_SLACK_S), the earliest.""" + at = _parse(dispatched_at) + if at is None: + return None + floor = at - _dt.timedelta(seconds=DISPATCH_SLACK_S) + mine = [r for r in state.get("runs") or [] + if r.get("event") == "workflow_dispatch" and (_parse(r.get("createdAt", "")) or at) >= floor] + return min(mine, key=lambda r: r["createdAt"]) if mine else None + + +def snapshot(home: Path, cfg: dict, state: dict, blk: dict | None, key=None, + is_library=None) -> dict: + """What the digest says about the sweep, kept in `counters["sweep"]`.""" + out = {"read": {"ok": bool(state.get("ok")), "at": state.get("read_at", ""), + "error": state.get("error", "")}, + "repo": cfg.get("repo", ""), "runs": state.get("runs") or []} + green = state.get("last_green") + if green: + shas = run_record(home, green["id"]).get("shas") or {} + commit = shas.get("commit_shas") if isinstance(shas.get("commit_shas"), dict) else {} + out["green"] = {"id": green["id"], "url": green["url"], "createdAt": green["createdAt"], + "full_sweep_run_id": str(shas.get("full_sweep_run_id") or ""), + "verified": {r: str(s)[:12] for r, s in sorted(commit.items()) + if is_library is None or is_library(r)}} + latest = state.get("latest") + if latest: + out["latest"] = latest + if is_red(latest) and latest["id"] in cleared(home): + out["cleared"] = {"run_id": latest["id"], **cleared(home)[latest["id"]]} + if blk: + out["block"] = {**blk, "draft": drafted(home, blk["run_id"])} + return out diff --git a/agents/conductors/batch/_watch.py b/agents/conductors/batch/_watch.py index 991ec013..673be8ee 100644 --- a/agents/conductors/batch/_watch.py +++ b/agents/conductors/batch/_watch.py @@ -250,7 +250,7 @@ def render(snap: dict) -> str: COMMAND_HELP = ("Steer it with a comment from the human's login, its first line one of: " "`/pause`, `/resume`, `/drop `, `/stop`, `/add `, " - "`/cap merges|workers|sessions|tokens `, `/kill `.") + "`/cap merges|workers|sessions|tokens `, `/kill `, `/clear-sweep`.") def render_status(snap: dict) -> str: diff --git a/agents/conductors/batch/closeout_template.md b/agents/conductors/batch/closeout_template.md index 25e06232..b47489f7 100644 --- a/agents/conductors/batch/closeout_template.md +++ b/agents/conductors/batch/closeout_template.md @@ -73,7 +73,10 @@ targeted smoke, and the full sweep runs in the cloud after the merge. 7. Immediately before you merge — after every check above, and again right before the merge command itself — look for {lease_dir}/{task}.dropped. If it exists, the human dropped this task with `/drop` mid-shift: do not merge; - refuse with why `dropped by /drop`. + refuse with why `dropped by /drop`. Look, at the same two moments, for + {lease_dir}/{task}.sweep-red. If it exists, the cloud workspace sweep on + `main` went red on a repo this PR touches: do not merge; refuse with why + `workspace sweep red: → /prm`. 8. Take the merge slot yourself, as a bare call, immediately before the merge (AUTONOMY.md "Shift speed", decision A of M3.7b): diff --git a/config/policy.yaml b/config/policy.yaml index a8845307..5b4b3855 100644 --- a/config/policy.yaml +++ b/config/policy.yaml @@ -184,3 +184,18 @@ shift_watcher: # Decision H7): `end` — one line in the digest at review-at, "N questions # added to your inbox" with the dashboard link; no @mention mid-shift. question_notice: end + # The shift-end cloud workspace sweep (M3.7e, PyAutoBrain#692; AUTONOMY.md + # "Shift speed — 2026-11-19", S4). The watcher dispatches `sweep_workflow` + # on `sweep_repo` (/) once at a shift's close when the shift + # merged a library or workspace PR, reads its latest runs on main each tick, + # and blocks unattended merges on a red run's failing workspaces. The + # install chains come from that repo's config/repos.yaml `smoke:` block; + # `sweep_siblings` maps a cloud project with no `smoke:` entry to the + # workspace whose chain it shares. Blank `sweep_repo` turns the sweep off. + sweep_repo: PyAutoLabs/PyAutoHeart + sweep_workflow: workspace-smoke.yml + sweep_siblings: + howtofit: autofit + howtogalaxy: autogalaxy + autofit_test: autofit + autogalaxy_test: autogalaxy diff --git a/skills/cockpit/cockpit.md b/skills/cockpit/cockpit.md index 67773541..84deb9a1 100644 --- a/skills/cockpit/cockpit.md +++ b/skills/cockpit/cockpit.md @@ -117,6 +117,7 @@ within 3 ticks (about 3 min), or `steer-unread` arrives, say so once. | "one worker only" (a number) | `/cap workers ` | **yes**, with n shown | | "fewer workers" (no number) | nothing yet: ask "how many workers at most?" | ask | | "keep it under 400k" | `/cap tokens 400000` | **yes**, with n shown | +| "the red sweep is fine", "unblock merges" | `/clear-sweep` (clears the latest red workspace sweep only) | **yes**, naming the run | | "merge #347" | not a comment: the `/prm` procedure on that PR, in this chat. If a close-out is `running` on it, say so and ask the human to wait or `/drop` first | /prm's own | | "put X on the queue", "move X up" | not a shift command: the `/queue` procedure | /queue's own | | "go through my questions", "answer Q17" | not a shift command: `/questions` (section 6) | n/a | @@ -136,8 +137,7 @@ within 3 ticks (about 3 min), or `steer-unread` arrives, say so once. n = merged + running. Confirm every `/cap` in one line with the number, e.g. "Post `/cap merges 3` (2 merged, 0 running, so one more)?" - **Unclear wording: ask.** Never guess a verb, a task or a number. One short - question, then post on the answer. -- Only the verbs above; the watcher ignores any other first line. + question, then post on the answer; the watcher ignores any other first line. ## Stop watching diff --git a/tests/conftest.py b/tests/conftest.py index dcd1be1a..b314e981 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -80,6 +80,14 @@ def _no_real_github(monkeypatch): for key in ("PYAUTO_SHIFT_APP_ID", "PYAUTO_SHIFT_APP_INSTALLATION_ID", "PYAUTO_SHIFT_APP_KEY"): # PyAutoBrain#630 monkeypatch.delenv(key, raising=False) + sweep = sys.modules.get("_sweep") + if sweep is not None: + # M3.7e: the sweep's `gh workflow run`, `gh run list`, `gh run + # download` and compare reads are offline; a test fakes `run_gh`. + import subprocess + + monkeypatch.setattr(sweep, "run_gh", lambda argv, timeout=120: + subprocess.CompletedProcess(argv, 1, "", "offline (tests)")) if digest is not None: real_health = digest.pr_health monkeypatch.setattr(digest, "pr_health", lambda url, run=None: diff --git a/tests/test_cockpit_skill.py b/tests/test_cockpit_skill.py index eacf16f3..2b8feb43 100644 --- a/tests/test_cockpit_skill.py +++ b/tests/test_cockpit_skill.py @@ -185,7 +185,7 @@ def test_the_steering_table_covers_exactly_the_watchers_verbs(): # A comment cell starts with the command; "not a comment: the `/prm` …" # rows route elsewhere and post nothing. comments = [cell for cell in cells if cell.startswith("`/")] - named = set(re.findall(r"`/([a-z]+)\b", " ".join(comments))) + named = set(re.findall(r"`/([a-z]+(?:-[a-z]+)?)\b", " ".join(comments))) # /clear-sweep assert named == set(_watcher_verbs()), named # The rest route elsewhere ("not a comment: …") or ask first ("nothing yet: ask"). assert all(cell.startswith(("not ", "nothing yet: ask")) for cell in cells diff --git a/tests/test_shift_end_sweep.py b/tests/test_shift_end_sweep.py new file mode 100644 index 00000000..06205ef0 --- /dev/null +++ b/tests/test_shift_end_sweep.py @@ -0,0 +1,565 @@ +"""M3.7e (PyAutoBrain#692): the shift-end cloud sweep — dispatch, read, red block. + +The human's rulings of 2026-11-19 (AUTONOMY.md "Shift speed — 2026-11-19", S4 +and the red handling; "The watcher's network surface", amendment M3.7e): + +1. A shift that merged at least one library or workspace PR dispatches the + sweep workflow exactly once at its close; one that merged none, or a + shadow shift, dispatches nothing; a failed dispatch is reported, never + retried. +2. The digest names, per library, the SHA the latest green sweep verified, + the shift's own sweep while it runs (or "not yet listed"), and a red one. +3. A red latest sweep refuses close-outs on its failing workspaces' install + chains (`workspace sweep red: `); other repos still close out; an + unknown workspace blocks every library repo; a later green run or + `/clear-sweep` clears it, and a newer red run blocks again; a running + close-out on a blocked repo gets a `.sweep-red` marker it checks. +4. One bug draft per red run through the one Mind writer, with the failing + scripts and the suspect PRs; nothing more on a second tick or shift; one + run list a tick, artifacts once per run id. +5. No revert, bisect or forced dispatch anywhere in the watcher. +6. AUTONOMY.md records S4, the network-surface amendment and `/clear-sweep`. +""" + +from __future__ import annotations + +import ast +import datetime as _dt +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +BATCH = BRAIN / "agents" / "conductors" / "batch" +sys.path.insert(0, str(BRAIN / "tests")) +import test_orchestrator_closeout as tc # noqa: E402 — the 4b and M3.6j fixtures +from test_orchestrator_closeout import FIT8, GA7, Agents # noqa: E402 +from test_orchestrator_digest import _brief, _digest, orch # noqa: E402 +import _mind_writer as mw # noqa: E402 + +t = tc.t +NOW = t.NOW +HEART = "example-org/example-heart" +WORKFLOW = "workspace-smoke.yml" +CFG = {"repo": HEART, "workflow": WORKFLOW, + "siblings": {"howtofit": "autofit", "autofit_test": "autofit"}} +RUN = "https://github.com/example-org/example-heart/actions/runs/{}" +LOGIN = "the-human" +DISPATCH = ["gh", "workflow", "run", WORKFLOW, "-R", HEART] + +REPOS_YAML = """\ +smoke: + workspaces: + autofit: + directory: example_fit_ws + chain: [autonerves, autofit] + autogalaxy: + directory: example_galaxy_ws + chain: [autonerves, autofit, autoarray, autogalaxy] +""" +VALIDATION_YML = """\ +jobs: + find_scripts: + steps: + - run: | + declare -A WS=( + [autofit]=example_fit_ws [autogalaxy]=example_galaxy_ws + [howtofit]=example_howtofit [autofit_test]=example_fit_ws_test + ) + for proj in "${!WS[@]}"; do +""" + + +def _at(minutes): + return NOW + _dt.timedelta(minutes=minutes) + + +def _sha(c): + return c * 40 + + +def _run(rid, conclusion="success", minutes=-600, status="completed", event="schedule"): + return {"databaseId": int(rid), "status": status, "conclusion": conclusion, + "url": RUN.format(rid), "createdAt": orch._iso(_at(minutes)), "event": event} + + +def _shas(rid, fit="a", galaxy="b"): + return {"schema": 1, "run_id": str(rid), "run_url": RUN.format(rid), "swept": True, + "full_sweep_run_id": str(rid), + "commit_shas": {"autofit": _sha(fit), "autogalaxy": _sha(galaxy), + "example_fit_ws": _sha("c")}} + + +def _report(*fails): + return {"ready": False, "summary": {"failed": len(fails)}, + "failures": [{"project": p, "directory": "scripts/x", "file": f"/w/{s}", + "status": "failed"} for p, s in fails], + "per_project": {}} + + +class FakeGH: + """`gh` for the sweep: the run list, artifact downloads, compares and the + dispatch, each call recorded.""" + + def __init__(self, runs=None, artifacts=None, compares=None, dispatch_err=""): + self.runs = [] if runs is None else runs + self.artifacts = artifacts or {} + self.compares = compares or {} + self.dispatch_err = dispatch_err + self.calls = [] + + def __call__(self, argv, timeout=120): + argv = list(argv) + self.calls.append(argv) + + def done(rc=0, out="", err=""): + return subprocess.CompletedProcess(argv, rc, out, err) + if argv[:3] == ["gh", "workflow", "run"]: + return done(1, "", self.dispatch_err) if self.dispatch_err else done() + if argv[:3] == ["gh", "run", "list"]: + if self.runs is None: + return done(1, "", "HTTP 502") + return done(0, json.dumps(self.runs)) + if argv[:3] == ["gh", "run", "download"]: + rid, name = argv[3], argv[argv.index("-n") + 1] + dest = Path(argv[argv.index("-D") + 1]) + files = self.artifacts.get((rid, name)) + if files is None: + return done(1, "", "no artifact") + for fname, data in files.items(): + (dest / fname).write_text(json.dumps(data)) + return done() + if argv[:2] == ["gh", "api"]: + got = self.compares.get(argv[2]) + return done(1, "", "404") if got is None else done(0, json.dumps(got)) + raise AssertionError(f"unexpected gh call {argv}") + + def of(self, *head): + return [c for c in self.calls if c[:len(head)] == list(head)] + + +@pytest.fixture +def sweep(monkeypatch, tmp_path): + """The sweep configured, Heart's maps in a fixture checkout, gh faked.""" + heart = tmp_path / "heart" + (heart / "config").mkdir(parents=True) + (heart / "config" / "repos.yaml").write_text(REPOS_YAML) + (heart / ".github" / "workflows").mkdir(parents=True) + (heart / ".github" / "workflows" / "workspace-validation.yml").write_text(VALIDATION_YML) + monkeypatch.setenv("PYAUTO_HEART", str(heart)) + monkeypatch.setattr(orch, "_sweep_cfg", lambda: dict(CFG)) + gh = FakeGH() + monkeypatch.setattr(orch._sweep, "run_gh", gh) + return gh + + +# --- 1. the dispatch at close --------------------------------------------------------- + +class MergeSpawner(tc.Spawner): + def __init__(self, done): + t.FilesSpawner.__init__(self, done=done, proofs={}) + self.closeouts = [] + + +def _merged_shift(tmp_path, done, extra=""): + mind = t._mind(tmp_path / "mind") + brief = tmp_path / "shift.md" + brief.write_text(t.BRIEF.format(issue=t.ISSUE, packet="") + extra) + home = tmp_path / "home" + sp = MergeSpawner(done) + return mind, brief, home, sp + + +def _close(mind, brief, home, sp, states=None, poster=None): + """Tick the shift through its end: dispatch, reap (maybe close early), + then a tick past review-at.""" + pr_state = tc._gh_states(states or {}) + for minutes in (0, 1, 181): + orch.tick(brief, mind, home=home, now=_at(minutes), spawner=sp, agents=Agents(), + health=lambda u: "FAILED", pr_state=pr_state, poster=poster or t.Poster()) + return orch.slot_dir(brief, home) + + +def test_a_shift_that_merged_a_library_pr_dispatches_once_at_close(tmp_path, sweep): + mind, brief, home, sp = _merged_shift(tmp_path, {"named": "merged " + GA7 + "\n", + "picked": ""}) + slot = _close(mind, brief, home, sp, {GA7: ("MERGED", "2026-11-04T09:00:30Z")}) + assert sweep.of("gh", "workflow", "run") == [DISPATCH] # no -f force + assert (slot / orch._sweep.DISPATCH_MARKER).exists() + c = orch.read_counters(slot) + assert c["sweep_dispatch"]["ok"] is True + # finish_shift again, retried after a lost digest: never a second dispatch. + (slot / orch.DIGEST_MARKER).unlink() + orch.finish_shift(brief, mind, slot, _at(182), poster=t.Poster(), agents=Agents(), + pr_state=tc._gh_states({GA7: ("MERGED", "2026-11-04T09:00:30Z")})) + assert sweep.of("gh", "workflow", "run") == [DISPATCH] + + +def test_a_shift_that_merged_nothing_dispatches_nothing(tmp_path, sweep): + mind, brief, home, sp = _merged_shift(tmp_path, {"named": GA7 + "\n", "picked": ""}) + slot = _close(mind, brief, home, sp) + assert sweep.of("gh", "workflow", "run") == [] + assert not (slot / orch._sweep.DISPATCH_MARKER).exists() + + +def test_a_merge_on_a_repo_neither_library_nor_workspace_dispatches_nothing(tmp_path, sweep): + mind, brief, home, sp = _merged_shift(tmp_path, {"named": "merged " + tc.PR1 + "\n", + "picked": ""}) + _close(mind, brief, home, sp, {tc.PR1: ("MERGED", "2026-11-04T09:00:30Z")}) + assert sweep.of("gh", "workflow", "run") == [] + + +def test_a_shadow_shift_never_dispatches_nor_reads(tmp_path, sweep): + mind, brief, home, sp = _merged_shift(tmp_path, {"named": "merged " + GA7 + "\n"}, + extra=" - shadow: yes\n") + sp.spawn = lambda *a, **k: (_ for _ in ()).throw(AssertionError("shadow spawned")) + _close(mind, brief, home, sp, {GA7: ("MERGED", "2026-11-04T09:00:30Z")}) + assert sweep.calls == [] + + +def test_a_failed_dispatch_is_reported_and_never_retried(tmp_path, sweep): + sweep.dispatch_err = "HTTP 403: Resource not accessible\nmore detail" + mind, brief, home, sp = _merged_shift(tmp_path, {"named": "merged " + GA7 + "\n", + "picked": ""}) + poster = t.Poster() + slot = _close(mind, brief, home, sp, {GA7: ("MERGED", "2026-11-04T09:00:30Z")}, poster) + c = orch.read_counters(slot) + assert c["sweep_dispatch"]["ok"] is False + d = (slot / orch.DIGEST_FILE).read_text() + assert ("sweep not dispatched (HTTP 403: Resource not accessible) — run it from chat" + in d) + (slot / orch.DIGEST_MARKER).unlink() + orch.finish_shift(brief, mind, slot, _at(182), poster=t.Poster(), agents=Agents(), + pr_state=tc._gh_states({GA7: ("MERGED", "2026-11-04T09:00:30Z")})) + assert len(sweep.of("gh", "workflow", "run")) == 1 + + +# --- 2. the digest lines -------------------------------------------------------------- + +def test_digest_verified_through_per_library_from_the_latest_green_run(tmp_path, sweep): + sweep.runs = [_run(100)] + sweep.artifacts = {("100", "workspace-smoke-shas"): {"shas.json": _shas(100)}} + mind, brief, home, sp = _merged_shift(tmp_path, {"named": GA7 + "\n", "picked": ""}) + slot = _close(mind, brief, home, sp) + d = (slot / orch.DIGEST_FILE).read_text() + assert "### Workspace sweep" in d + assert "- autofit: workspaces verified through `aaaaaaaaaaaa` (run 100)" in d + assert "- autogalaxy: workspaces verified through `bbbbbbbbbbbb` (run 100)" in d + assert "example_fit_ws" not in d.split("### Workspace sweep")[1] # a library line only + + +def test_digest_says_sweep_running_for_the_shifts_own_dispatch(tmp_path, sweep): + # The shift closes at its review-at tick (minute 181); its run follows. + sweep.runs = [_run(101, conclusion="", minutes=181, status="in_progress", + event="workflow_dispatch"), _run(100)] + sweep.artifacts = {("100", "workspace-smoke-shas"): {"shas.json": _shas(100)}} + mind, brief, home, sp = _merged_shift(tmp_path, {"named": "merged " + GA7 + "\n", + "picked": ""}) + slot = _close(mind, brief, home, sp, {GA7: ("MERGED", "2026-11-04T09:00:30Z")}) + d = (slot / orch.DIGEST_FILE).read_text() + assert f"sweep running: {RUN.format(101)}" in d + + +def test_digest_says_not_yet_listed_when_the_dispatch_is_not_seen(tmp_path, sweep): + sweep.runs = [_run(100)] + sweep.artifacts = {("100", "workspace-smoke-shas"): {"shas.json": _shas(100)}} + mind, brief, home, sp = _merged_shift(tmp_path, {"named": "merged " + GA7 + "\n", + "picked": ""}) + slot = _close(mind, brief, home, sp, {GA7: ("MERGED", "2026-11-04T09:00:30Z")}) + d = (slot / orch.DIGEST_FILE).read_text() + c = orch.read_counters(slot) + assert f"sweep dispatched at {c['sweep_dispatch']['at']}, not yet listed" in d + + +# --- 3. the red block ----------------------------------------------------------------- + +class TwoLibs(tc.Spawner): + """`named` opens a PR on autofit, `picked` one on autogalaxy.""" + + def __init__(self): + t.FilesSpawner.__init__(self, done={"named": FIT8 + "\n", "picked": GA7 + "\n"}, + proofs={}) + self.closeouts = [] + + +def _red(sweep, project="autofit", rid=200, fit="d"): + sweep.runs = [_run(rid, "failure", minutes=-60), _run(100)] + sweep.artifacts = { + ("100", "workspace-smoke-shas"): {"shas.json": _shas(100)}, + (str(rid), "workspace-smoke-shas"): {"shas.json": _shas(rid, fit=fit)}, + (str(rid), "workspace-validation-report"): { + "report.json": _report((project, "start_here.py"))}} + + +def _libs_shift(tmp_path): + mind = t._mind(tmp_path / "mind") + brief = tmp_path / "shift.md" + brief.write_text(t.BRIEF.format(issue=t.ISSUE, packet="") + .replace("merge-cap: 1", "merge-cap: 2")) + return mind, brief, tmp_path / "home", TwoLibs() + + +def _ltick(mind, brief, home, sp, minutes, agents=None): + return orch.tick(brief, mind, home=home, now=_at(minutes), spawner=sp, + agents=agents or Agents(), health=lambda u: "HEALTHY", + pr_state=tc._gh_states({})) + + +def test_a_red_sweep_refuses_a_chain_repo_pr_and_closes_out_the_others(tmp_path, sweep): + _red(sweep, "autofit") + mind, brief, home, sp = _libs_shift(tmp_path) + _ltick(mind, brief, home, sp, 0) + _ltick(mind, brief, home, sp, 1) + slot = orch.slot_dir(brief, home) + c = orch.read_counters(slot) + assert c["closeouts"][FIT8] == {"task": "named", "state": "refused", + "why": f"workspace sweep red: {RUN.format(200)}"} + assert [pr for _, pr in sp.closeouts] == [GA7] # the unaffected repo + assert orch._merge_slots.pr_key(FIT8) not in tc._slots(brief, home) + blk = c["sweep"]["block"] + assert blk["repos"] == ["autonerves", "autofit", "example_fit_ws"] + assert blk["all_libraries"] is False + + +def test_a_sibling_project_maps_to_its_siblings_chain(tmp_path, sweep): + _red(sweep, "howtofit") + mind, brief, home, sp = _libs_shift(tmp_path) + _ltick(mind, brief, home, sp, 0) + blk = orch.read_counters(orch.slot_dir(brief, home))["sweep"]["block"] + assert blk["repos"] == ["autonerves", "autofit", "example_howtofit"] + + +def test_an_unknown_workspace_blocks_every_library_repo(tmp_path, sweep): + _red(sweep, "mystery") + mind, brief, home, sp = _libs_shift(tmp_path) + _ltick(mind, brief, home, sp, 0) + _ltick(mind, brief, home, sp, 1) + c = orch.read_counters(orch.slot_dir(brief, home)) + assert c["closeouts"][FIT8]["state"] == "refused" + assert c["closeouts"][GA7]["state"] == "refused" + assert sp.closeouts == [] + assert c["sweep"]["block"]["all_libraries"] is True + + +def test_a_later_green_run_clears_the_block(tmp_path, sweep): + _red(sweep, "autofit") + mind, brief, home, sp = _libs_shift(tmp_path) + _ltick(mind, brief, home, sp, 0) + assert orch.read_counters(orch.slot_dir(brief, home))["sweep"]["block"] + sweep.runs = [_run(201, minutes=0)] + sweep.runs + sweep.artifacts[("201", "workspace-smoke-shas")] = {"shas.json": _shas(201, fit="d")} + _ltick(mind, brief, home, sp, 1) + c = orch.read_counters(orch.slot_dir(brief, home)) + assert not c["sweep"].get("block") + assert sorted(pr for _, pr in sp.closeouts) == sorted([FIT8, GA7]) + + +def test_clear_sweep_clears_the_latest_red_run_and_a_newer_red_blocks_again( + tmp_path, sweep, monkeypatch): + monkeypatch.setenv(orch.MENTION_ENV, LOGIN) + comments = [] + monkeypatch.setattr(orch, "gh_issue_comments", lambda *a, **k: list(comments)) + _red(sweep, "autofit") + mind, brief, home, sp = _libs_shift(tmp_path) + _ltick(mind, brief, home, sp, 0) + comments.append({"id": "1", "login": LOGIN, "body": "/clear-sweep\nlooked at it", + "created_at": "2026-11-04T09:00:30Z", "url": t.ISSUE + "#issuecomment-1"}) + r = _ltick(mind, brief, home, sp, 1) + ack = r["commands"][0]["ack"] + assert ack.startswith(f"cleared: workspace sweep red {RUN.format(200)}") + slot = orch.slot_dir(brief, home) + assert "200" in json.loads((home / "sweep" / "cleared.json").read_text()) + assert sorted(pr for _, pr in sp.closeouts) == sorted([FIT8, GA7]) + # A newer red run blocks again. + _red(sweep, "autofit", rid=300) + _ltick(mind, brief, home, sp, 2) + assert orch.read_counters(slot)["sweep"]["block"]["run_id"] == "300" + + +def test_clear_sweep_with_nothing_red_says_nothing_to_clear(tmp_path, sweep, monkeypatch): + monkeypatch.setenv(orch.MENTION_ENV, LOGIN) + monkeypatch.setattr(orch, "gh_issue_comments", lambda *a, **k: [ + {"id": "1", "login": LOGIN, "body": "/clear-sweep", "created_at": + "2026-11-04T08:59:00Z", "url": t.ISSUE + "#issuecomment-1"}]) + sweep.runs = [_run(100)] + mind, brief, home, sp = _libs_shift(tmp_path) + r = _ltick(mind, brief, home, sp, 0) + assert r["commands"][0]["ack"] == "nothing to clear: no red workspace sweep blocks merges" + assert "clear-sweep" in orch.COMMANDS + assert orch._parse_command("/clear-sweep") == ("clear-sweep", "") + + +@pytest.mark.usefixtures("shift_held_open") +def test_a_running_closeout_on_a_blocked_repo_gets_the_sweep_red_marker(tmp_path, sweep): + sweep.runs = [_run(100)] + sweep.artifacts = {("100", "workspace-smoke-shas"): {"shas.json": _shas(100)}} + mind, brief, home, sp = _libs_shift(tmp_path) + _ltick(mind, brief, home, sp, 0) + _ltick(mind, brief, home, sp, 1) + slot = orch.slot_dir(brief, home) + assert orch.read_counters(slot)["closeouts"][FIT8]["state"] == "running" + _red(sweep, "autofit") + _ltick(mind, brief, home, sp, 2) + marker = slot / "leases" / "named.sweep-red" + assert marker.read_text().strip() == RUN.format(200) + assert not (slot / "leases" / "picked.sweep-red").exists() + template = orch.closeout_prompt("named", FIT8, "x.md", brief, slot / "leases") + assert f"{slot / 'leases'}/named.sweep-red" in template + assert "workspace sweep red: → /prm" in template + # A later green run lifts the block, and the marker with it. + sweep.runs = [_run(201, minutes=2)] + sweep.runs + sweep.artifacts[("201", "workspace-smoke-shas")] = {"shas.json": _shas(201, fit="d")} + _ltick(mind, brief, home, sp, 3) + assert not marker.exists() + + +# --- 4. the bug draft, and the reads' budget ------------------------------------------ + +def _draft_ops(slot): + out = [] + for f in mw.pending_ops(slot): + op = json.loads(f.read_text()) + if op.get("op") == "write" and "workspace_sweep_red" in op.get("path", ""): + out.append(op) + return out + + +def test_one_bug_draft_names_failing_scripts_and_suspect_prs(tmp_path, sweep): + _red(sweep, "autofit") + sweep.compares = {f"repos/example-org/autofit/compare/{_sha('a')}...{_sha('d')}": [ + "Merge pull request #41 from example-org/feature/x\n\nbody", + "Fix the prior (#42)", "a plain commit"]} + mind, brief, home, sp = _libs_shift(tmp_path) + _ltick(mind, brief, home, sp, 0) + slot = orch.slot_dir(brief, home) + ops = _draft_ops(slot) + assert [o["path"] for o in ops] == ["draft/bug/autofit/workspace_sweep_red_200.md"] + text = ops[0]["text"] + for needle in ("Type: bug", "Target: autofit", "Status: draft", "Filed: 2026-11-04", + "Consequence: judge", RUN.format(200), "`autofit`: `scripts/x/start_here.py`", + "autonerves, autofit, example_fit_ws", + "[#41](https://github.com/example-org/autofit/pull/41)", + "[#42](https://github.com/example-org/autofit/pull/42)", + "workspace-smoke-pinned.yml", "commit_shas", "draft PRs opened for the human"): + assert needle in text, needle + # A second tick and a later shift file nothing more; reads stay in budget. + _ltick(mind, brief, home, sp, 1) + assert len(_draft_ops(slot)) == 1 + mind2 = t._mind(tmp_path / "mind2") + brief2 = tmp_path / "shift2.md" + brief2.write_text(t.BRIEF.format(issue=t.ISSUE, packet="")) + orch.tick(brief2, mind2, home=home, now=_at(2), spawner=TwoLibs(), agents=Agents(), + health=lambda u: "HEALTHY", pr_state=tc._gh_states({})) + assert _draft_ops(orch.slot_dir(brief2, home)) == [] + assert len(sweep.of("gh", "run", "list")) == 3 # one a tick + downloads = [(c[3], c[c.index("-n") + 1]) for c in sweep.of("gh", "run", "download")] + assert sorted(downloads) == sorted([("200", "workspace-smoke-shas"), + ("200", "workspace-validation-report"), + ("100", "workspace-smoke-shas")]) + assert len(sweep.of("gh", "api")) == 1 # one compare + + +def test_no_green_baseline_says_so_and_targets_the_sweep_repo(tmp_path, sweep): + sweep.runs = [_run(200, "failure", minutes=-60)] + sweep.artifacts = {("200", "workspace-smoke-shas"): {"shas.json": _shas(200)}, + ("200", "workspace-validation-report"): { + "report.json": _report(("autofit", "start_here.py"))}} + mind, brief, home, sp = _libs_shift(tmp_path) + _ltick(mind, brief, home, sp, 0) + ops = _draft_ops(orch.slot_dir(brief, home)) + assert [o["path"] for o in ops] == ["draft/bug/example-heart/workspace_sweep_red_200.md"] + assert "No green sweep on `main` is known to compare against" in ops[0]["text"] + + +def test_an_unreadable_report_is_tried_three_times_then_blocks_every_library(tmp_path, sweep): + _red(sweep, "autofit") + del sweep.artifacts[("200", "workspace-validation-report")] + mind, brief, home, sp = _libs_shift(tmp_path) + for minutes in (0, 1, 2, 3, 4): + _ltick(mind, brief, home, sp, minutes) + tries = [c for c in sweep.of("gh", "run", "download") + if c[3] == "200" and "workspace-validation-report" in c] + assert len(tries) == 3 + c = orch.read_counters(orch.slot_dir(brief, home)) + assert c["sweep"]["block"]["all_libraries"] is True + ops = _draft_ops(orch.slot_dir(brief, home)) + assert len(ops) == 1 and "could not be read" in ops[0]["text"] + + +def test_the_digest_red_line_names_the_block_the_refusals_and_the_draft(tmp_path, sweep): + _red(sweep, "autofit") + mind, brief, home, sp = _libs_shift(tmp_path) + _ltick(mind, brief, home, sp, 0) + _ltick(mind, brief, home, sp, 1) + slot = orch.slot_dir(brief, home) + d = _digest.build(_brief.parse(brief.read_text())["brief"], slot, + orch.read_counters(slot), health=t._health) + assert (f"- workspace sweep red: {RUN.format(200)} — blocked: autonerves, autofit, " + "example_fit_ws; PRs refused: autofit#8; bug draft: " + "`draft/bug/example-heart/workspace_sweep_red_200.md`") in d + + +def test_a_failed_run_list_keeps_the_last_known_block(tmp_path, sweep): + _red(sweep, "autofit") + mind, brief, home, sp = _libs_shift(tmp_path) + _ltick(mind, brief, home, sp, 0) + sweep.runs = None + _ltick(mind, brief, home, sp, 1) + c = orch.read_counters(orch.slot_dir(brief, home)) + assert c["closeouts"][FIT8]["state"] == "refused" + + +# --- 5. no revert, bisect or forced dispatch ------------------------------------------ + +WATCHER_CODE = [BATCH / "_orchestrator.py", BATCH / "_sweep.py"] +TEMPLATES = [BATCH / "closeout_template.md", BATCH / "closeout_update_template.md", + BATCH / "worker_template.md"] + + +def _argv_lists(path): + """Every list or tuple literal of strings that starts a `gh`/`git` call.""" + out = [] + for node in ast.walk(ast.parse(path.read_text())): + if isinstance(node, (ast.List, ast.Tuple)) and node.elts \ + and isinstance(node.elts[0], ast.Constant) and node.elts[0].value in ("gh", "git"): + out.append([e.value if isinstance(e, ast.Constant) else "" for e in node.elts]) + return out + + +def test_nothing_in_the_watcher_reverts_bisects_or_forces_a_sweep(): + calls = [argv for f in WATCHER_CODE for argv in _argv_lists(f)] + assert ["gh", "workflow", "run", "", "-R", ""] in calls # the one dispatch + for argv in calls: + words = [str(w) for w in argv] + assert "revert" not in words, argv + assert not any("workspace-smoke-pinned" in w for w in words), argv + assert not any("force" in w for w in words), argv + assert "-f" not in words and "--field" not in words and "--raw-field" not in words, argv + policy = (BRAIN / "config" / "policy.yaml").read_text() + assert "sweep_workflow: workspace-smoke.yml" in policy + for f in TEMPLATES: + text = f.read_text() + for bad in ("git revert", "gh pr revert", "gh workflow run", "force=true"): + assert bad not in text, (f.name, bad) + + +# --- 6. the doctrine ------------------------------------------------------------------ + +def test_autonomy_records_s4_the_network_amendment_and_clear_sweep(): + text = (BRAIN / "AUTONOMY.md").read_text() + speed = text.split("## Shift speed — 2026-11-19", 1)[1].split("\n## ", 1)[0] + assert "**S4, the shift-end sweep**" in speed + assert "/clear-sweep" in speed + assert "S4) is added to this section" not in speed + net = text.split("## The watcher's network surface — 2026-11-03", 1)[1].split("\n## ", 1)[0] + amend = net.split("**Amendment — 2026-11-19 (M3.7e, PyAutoBrain#692)", 1)[1] + for needle in ("gh workflow run", "gh run list", "gh run download", "compare", + "decision b", "fake mode", "/clear-sweep"): + assert needle in amend.split("\n\n**", 1)[0], needle + agents = (BATCH / "AGENTS.md").read_text() + assert "/clear-sweep" in agents and "M3.7e" in agents + cockpit = (BRAIN / "skills" / "cockpit" / "cockpit.md").read_text() + assert "/clear-sweep" in cockpit From 904ded7e515ffb1bbb835187d1e225b65286cd68 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 19 Nov 2026 16:32:30 +0000 Subject: [PATCH 2/3] M3.7e review round 1: fail closed on every repo a merge could break (#692) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. The fallback block (unmapped workspace, unreadable report or Heart maps) covers every library, chain and workspace repo, Nerves included. 2. A run list never read, or unread for 30 minutes, blocks the same set: "workspace sweep unknown: run list unreadable since → /prm", in the digest too. 3. Heart chain repos count as flow repos: their merges dispatch, they get a verified-through line and can be the bug draft's target. 4. Failing scripts are named from // on in `file` (else after /workspace/); tested on a trimmed real report. 5. A cancelled run is no verdict: the run before it on main counts. 6. late_sweep makes the shift's one dispatch when a close-out merged after the close and none was made (same sweep.dispatched marker). 7. A .sweep-red marker the current block does not cover is removed. 8. The bug draft is filed from the latest red run, cleared or not. Tests default the sweep off (conftest); AUTONOMY.md and batch AGENTS.md updated. Co-Authored-By: Claude Opus 5.5 --- AUTONOMY.md | 18 ++- agents/conductors/batch/AGENTS.md | 21 +-- agents/conductors/batch/_digest.py | 12 +- agents/conductors/batch/_orchestrator.py | 127 +++++++++++----- agents/conductors/batch/_sweep.py | 93 ++++++++---- tests/conftest.py | 4 + tests/fixtures/sweep_report_red.json | 162 +++++++++++++++++++++ tests/test_shift_end_sweep.py | 178 ++++++++++++++++++++++- 8 files changed, 531 insertions(+), 84 deletions(-) create mode 100644 tests/fixtures/sweep_report_red.json diff --git a/AUTONOMY.md b/AUTONOMY.md index 918a06b8..8afde8ba 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -575,19 +575,24 @@ Watcher latency (M3.7c, the human's plan decisions of 2026-11-19): Smoke workflow once at its close: after the last merge, before the digest. The dispatch has no inputs, so the workflow's own SHA gate decides whether to sweep; it is never forced. A shift with no such merge, or a shadow - shift, dispatches nothing. A failed dispatch is not retried: the digest - says "sweep not dispatched", and the human runs it from chat. The sweep + shift, dispatches nothing. A close-out that merges after the close, in + the late window, makes the shift's one dispatch if none was made. A + failed dispatch is not retried: the digest says "sweep not dispatched", + and the human runs it from chat. The sweep takes about 30 minutes. The digest is not held for it: it says "sweep running" or "not yet listed", and the next shift's ticks read the result. Each tick of a shift reads the workflow's latest runs on `main`. The digest names, per library, the SHA the latest green sweep verified. - **Red handling** (M3.7e). When the latest completed sweep on `main` is red - (failure, cancelled or timed out), no unattended close-out starts on a + (failure or timed out), no unattended close-out starts on a repo in a failing workspace's install chain (Heart `config/repos.yaml` `smoke:`) or on that workspace's own repo. The PR is refused for `/prm` as `workspace sweep red: `. PRs on other repos still close out. - A failing workspace the watcher cannot map, or a report it cannot read, - blocks every library repo. A close-out already running on a blocked repo + A cancelled run is no verdict: the run before it on `main` counts. A + failing workspace the watcher cannot map, or a report it cannot read, + blocks every library, chain and workspace repo. So does a run list + unreadable for 30 minutes, or never read: the PR is refused as + `workspace sweep unknown: run list unreadable since