From 1dac410fcfd3fdca216381fa28c94e1fdcdb9c0c Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 13 Nov 2026 15:04:25 +0000 Subject: [PATCH 1/2] =?UTF-8?q?feat(batch):=20live=20shift=20view=20you=20?= =?UTF-8?q?can=20steer=20=E2=80=94=20status=20comment,=20/pause=20/resume?= =?UTF-8?q?=20/drop=20/stop,=20/batch=20watch=20(#622)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The watcher keeps one status comment per shift on the brief's issue: created once (status.json claimed before the create), then only edited, at most once a tick (on a change of state, or every 10 minutes). A create that may have landed is never re-made; the comments read adopts it by its hidden tag. A failed edit is retried next tick and the tick carries on. After the reap, one `gh api .../comments` read per tick takes the human's commands: the first line of a comment by mention_login, made after dispatched:. /pause holds new spawns, proposals and close-outs until /resume; /drop keeps a pick from ever being picked (a running worker is shown "dropped, still running", never re-dispatched or merged unattended, and stopping it stays the human's); /stop writes STOP. Each comment is enacted once by id and acknowledged once in the status comment. The dashboard shows the same status as the record's `- live:` line (new `record-key` Mind-writer op, written on a change of state) in the batch box. `batch watch` shows pause, refusals, commands and the comment link. AUTONOMY.md: the watcher network-surface amendment dated 2026-11-13. Co-Authored-By: Claude Opus 5.5 --- AUTONOMY.md | 45 ++- agents/conductors/batch/AGENTS.md | 23 +- agents/conductors/batch/_digest.py | 16 +- agents/conductors/batch/_mind_writer.py | 43 ++- agents/conductors/batch/_orchestrator.py | 409 ++++++++++++++++++++++- agents/conductors/batch/_status.py | 21 ++ agents/conductors/batch/_watch.py | 106 +++++- skills/batch/batch.md | 4 +- skills/batch/reference.md | 18 + tests/conftest.py | 7 + tests/test_orchestrator_steering.py | 362 ++++++++++++++++++++ 11 files changed, 1029 insertions(+), 25 deletions(-) create mode 100644 tests/test_orchestrator_steering.py diff --git a/AUTONOMY.md b/AUTONOMY.md index 11b62019..f414f324 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -889,6 +889,47 @@ writes use a separate bot or machine account's token, set by the human as is set they post as the human's account and the digest warns that the mention will not notify. +**Amendment — 2026-11-13 (PyAutoBrain#622), authorized by the human.** The +human approved the live shift view as drafted on 2026-11-13: a running shift +they can watch and steer from its digest issue. The watcher's network surface +gains, and only: + +- **one status comment per shift** on the brief's `issue:`, created once and + from then on only **edited** in place: at most one edit a tick, when the + shift's state changes or every 10 minutes, and one last edit at + `review-at:` marking it closed. It shows the picks and workers with their + state, tokens against the budget, blocks and parks, refusals, time to + `review-at:` and every command with its acknowledgement. It never + @-mentions anyone, so an edit notifies nobody. Its marker is claimed + exclusively before the create, as above. A create `gh` said failed is made + again next tick. A create that timed out, or a claim whose tick died, is + never made again: the comments read adopts it by its hidden tag if it + landed. A failed edit is retried next tick, and the tick carries on; +- **one read a tick of that issue's comments** (`gh api + repos///issues//comments`, one page, under the posting + token), for the steering commands; +- **the command set**, enacted from that read: `/pause` (no new workers or + close-outs until `/resume`; workers already out keep running and are + reaped), `/resume`, `/drop ` (a pick not yet spawned is never + picked; a running worker is not killed by the watcher: it is shown + "dropped, still running", never re-dispatched and its PR never merged + unattended, and stopping it stays the human's act, by hand) and `/stop` + (writes the `STOP` kill-switch file, with exactly its effect). A command + counts only when it is the first line of a comment by the login in + `PYAUTO_SHIFT_MENTION` or `config/policy.yaml` `shift_watcher: + mention_login:`, made after the brief's `dispatched:`. The status comment + is skipped by its tag and its id, so the watcher never reads its own text + as a command. Each comment is enacted once, by id, and acknowledged once, as + a line of the status comment, with no extra comment or reaction. + +The dashboard shows the same status as a `- live:` line in the brief record, +written through the one Mind writer when the shift's state changes. That adds +no network act beyond the Mind push the writer already makes. The revert +condition now also covers a second status comment in one shift, more than +one comments read or one status write in a tick, and a command enacted from +any other login or enacted twice: any of these retires the watcher to fake +mode. + ## Human override for Heart RED (development only) Heart RED still parks every autonomous run and blocks every release. After the @@ -1181,6 +1222,8 @@ Codex hook list. - `batch` (the close-out session) — "Stage-2 adversary amendment" (2026-11-04): the independent close-out session is the adversary leg, same model allowed. - `batch` (the watcher) — "The watcher's network surface" (2026-11-03): what - the watcher may reach, and that it is opt-in, laptop-only and never writes. + the watcher may reach, and that it is opt-in, laptop-only and never writes; + amended 2026-11-12 (mentions, #611) and 2026-11-13 (the live status comment + and the steering commands, #622). Skills must link here rather than copying the tables. diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index cd7c447b..92d3b374 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -386,6 +386,26 @@ trigger is durable state (a parked task or an issue-only `.done` with no marker yet), so a tick that dies between parking and posting mentions on the next; a failed mention is also retried by the late sweep. +**Watching and steering a shift from its issue (PyAutoBrain#622).** Each open +tick ends with the shift's **status comment** on the brief's `issue:`: the +`batch watch` snapshot as Markdown (`_watch.render_status`, no tick log), +created once (`/status.json` claimed before the create) and then only +edited, at most once a tick, when the state changes or every 10 minutes +(`STATUS_REFRESH_S`). A create that may have landed is never made again; the +comments read adopts it by its hidden tag. A failed edit is retried next tick. +After the reap, one `gh api …/comments` read takes the human's commands, each +the first line of a comment by `mention_login`, made after `dispatched:`: +`/pause` (no new spawns, proposals or close-outs; workers out run on and are +reaped), `/resume`, `/drop ` (`counters.json` `dropped`; never picked, +never re-dispatched, its PR refused for close-out; a live worker is shown +`dropped, still running` and stopping it is the human's, `claude stop `) +and `/stop` (writes `STOP`). 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 +the batch box. Doctrine: AUTONOMY.md watcher network surface, amendment +2026-11-13. + **The watcher's GitHub identity (human ruling 2026-11-12, #611).** `PYAUTO_SHIFT_GH_TOKEN` holds a separate bot or machine account's token, **fine-grained, PyAutoMind issues:write only**, set by the human in the @@ -418,7 +438,8 @@ live shift 1 (2026-11-06) lost all three workers about 30 seconds after spawn (`daemon-reload`). Separately, a worker or close-out whose `claude agents` state is in `_digest.ENDED_STATES` (`failed`, `killed`, `error`, …) is reaped at once, as a crash (worker, re-dispatched once) or a refusal (close-out), -never read as alive. To stop a shift, `touch /STOP`; to remove the +never read as alive. To stop a shift, `touch /STOP` (or comment `/stop` on +its issue); to remove the watcher, `systemctl --user disable --now pyauto-orchestrator.timer`. ## Running diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 67d2cd07..e0dea7fa 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -147,7 +147,21 @@ def task_state(task: str, counters: dict, health, *, live: bool = False, digest and `batch watch` share, so the live view and the digest never disagree. Only the live view passes `live=True` (with the task's `lease` and the `agents` view): at `review-at:` the watcher has already reaped - every lease, and the digest's wording stays exactly as it was.""" + every lease, and the digest's wording stays exactly as it was. A task the + human dropped by `/drop` (PyAutoBrain#622) says so first.""" + state, tiered = _task_state(task, counters, health, live=live, lease=lease, + agents=agents) + if task not in (counters.get("dropped") or {}): + return state, tiered + if live and lease is not None: + return f"dropped, still running — {state}", tiered + if state == "not started": + return "dropped by /drop — not started", False + return f"dropped by /drop — {state}", tiered + + +def _task_state(task: str, counters: dict, health, *, live: bool = False, + lease: dict | None = None, agents=None) -> tuple[str, bool]: out = counters.get("outcomes", {}).get(task) if counters.get("picks", {}).get(task, {}).get("proposed"): return PROPOSED, True diff --git a/agents/conductors/batch/_mind_writer.py b/agents/conductors/batch/_mind_writer.py index 0b1afe2c..4bc78883 100644 --- a/agents/conductors/batch/_mind_writer.py +++ b/agents/conductors/batch/_mind_writer.py @@ -20,6 +20,7 @@ {"op": "set-header", "path": "draft/a/b/x.md", "key": "Verified", "value": "2026-11-12 abc123 (Repo)"} {"op": "jsonl-upsert", "path": "batches/pilot/pilot.jsonl", "key": "slot", "row": {...}} {"op": "table-upsert", "path": "batches/pilot/pilot.md", "key": "", "row": "| … |", "header": "…"} + {"op": "record-key", "path": "batches/.md", "key": "live", "value": "…"} `jsonl-upsert` keeps one JSON line per `row[key]`: the line with that key is replaced (its other fields kept), else the row is appended. `table-upsert` @@ -28,6 +29,11 @@ first into a missing file. Both are how the shift watcher writes its one pilot row per shift and amends it on a late arrival (PyAutoBrain#610). +`record-key` sets one top-level `- key: value` line of a batch record — the +key's own line replaced, else inserted after `- issue:` (else `- review-at:`). +The watcher writes the dashboard's `- live:` status line this way +(PyAutoBrain#622); a record no longer on main is skipped, like `set-header`. + `set-header` sets one `Key: value` line in a prompt's header block (replacing the key's line if present) — how a shift worker records the premise check's `Verified:` stamp (`batch premise --record`) without touching the file itself. @@ -48,7 +54,7 @@ from pathlib import Path OPS = ("append", "write", "move", "remove", "drop-section", "table-append", - "set-header", "jsonl-upsert", "table-upsert") + "set-header", "jsonl-upsert", "table-upsert", "record-key") PUSH_TRIES = 3 LEDGER_DIR = "ledger" COMMITTED_DIR = "committed" @@ -118,6 +124,14 @@ def validate_op(op: dict, lm) -> list[str]: errs.append("table-upsert: row must be one `| … |` line") elif _cells(row)[0] != op.get("key"): errs.append("table-upsert: the row's first cell must be its key") + if kind == "record-key": + key, value, path = op.get("key"), op.get("value"), str(op.get("path", "")) + if not isinstance(key, str) or not re.fullmatch(r"[a-z][a-z0-9-]*", key): + errs.append("record-key: key must be one lower-case record key") + if not isinstance(value, str) or not value.strip() or "\n" in value: + errs.append("record-key: value must be one non-empty line") + if not (path.startswith("batches/") and path.endswith(".md")): + errs.append("record-key: path must be a batch record (batches/*.md)") if kind == "set-header": key, value = op.get("key"), op.get("value") if not isinstance(key, str) or not re.fullmatch(r"[A-Z][A-Za-z-]*", key): @@ -171,6 +185,11 @@ def apply_op(tree: Path, op: dict, lm) -> str | None: f"since the check) — {op['key']}: skipped") target.write_text(set_header(target.read_text(encoding="utf-8"), op["key"], op["value"]), encoding="utf-8") + elif kind == "record-key": + if not target.exists(): + return f"record-key: {op['path']} is not on main — {op['key']}: skipped" + target.write_text(record_key(target.read_text(encoding="utf-8"), + op["key"], op["value"]), encoding="utf-8") elif kind == "table-append": target.write_text(table_append(target.read_text(encoding="utf-8") if target.exists() else "", @@ -188,6 +207,28 @@ def apply_op(tree: Path, op: dict, lm) -> str | None: encoding="utf-8") +def record_key(text: str, key: str, value: str, + after: tuple[str, ...] = ("issue", "review-at")) -> str: + """`text` with one top-level `- key: value` line above the first `## ` + heading: the key's line replaced if present, else inserted after the + first of `after` present, else after the title. Every other line is kept.""" + lines = text.split("\n") + end = next((i for i, ln in enumerate(lines) if ln.startswith("## ")), len(lines)) + new = f"- {key}: {value}" + for i in range(end): + if lines[i].startswith(f"- {key}:"): + lines[i] = new + return "\n".join(lines) + at = next((i + 1 for i, ln in enumerate(lines) if ln.startswith("# ")), 0) + for anchor in after: + hit = next((i for i in range(end) if lines[i].startswith(f"- {anchor}:")), None) + if hit is not None: + at = hit + 1 + break + lines.insert(at, new) + return "\n".join(lines) + + def table_append(text: str, heading: str, row: str) -> str: """`row` inserted after the last table line under the `## ` heading that starts with `heading` — whatever follows that section stays where it is.""" diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index cea131e2..20706af2 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -23,8 +23,11 @@ Nothing here commits, merges or arms a timer: the systemd timer that calls `bin/orchestrator_watch.py` is installed by the human. Its only GitHub writes are the comments AUTONOMY.md "The watcher's network surface" lists — the -digest, one @mention per worker per state that needs the human (#611) and -one correction for a late arrival (#610) — each claimed by marker first. +digest, one @mention per worker per state that needs the human (#611), one +correction for a late arrival (#610) and one live status comment, then only +edited (#622) — each claimed by marker first. Each open tick also reads the +shift issue's comments once, for the human's `/pause` `/resume` `/drop` +`/stop` (#622). """ from __future__ import annotations @@ -147,6 +150,10 @@ def read_counters(slot: Path) -> dict: c.setdefault("workers", []) c.setdefault("github", {}) c.setdefault("pushes", 0) # @mentions sent (PyAutoBrain#611) + # PyAutoBrain#622: tasks the human dropped, and every steering command + # enacted with its acknowledgement (`paused` is present only while paused). + c.setdefault("dropped", {}) + c.setdefault("commands", []) return c @@ -822,9 +829,12 @@ def tick(brief_path: Path, mind: Path, *, home: Path | None = None, grace_s: float = LEASE_GRACE_S, records: list[dict] | None = None, agents: AgentsView | None = None, tokens=transcript_usage, poster=None, health=None, pr_state=None, - token_reserve: int | None = None, whoami=None) -> dict: + token_reserve: int | None = None, whoami=None, github=None) -> dict: """One watcher tick. Returns what it did; also appended to `tick.log`. + `github` is the `run` seam for the live status comment and the steering + read (PyAutoBrain#622) — a test's fake `gh`; unset, the real one. + After `review-at:` the one remaining act is the digest (phase 3d), once — then the late sweep, while a worker is still out, an op is queued or a failed post is due its retry.""" @@ -845,7 +855,7 @@ def tick(brief_path: Path, mind: Path, *, home: Path | None = None, try: result = finish_shift( brief_path, mind, slot, now, poster=poster, health=health, - agents=agents, tokens=tokens, grace_s=grace_s, + agents=agents, tokens=tokens, grace_s=grace_s, github=github, pr_state=(pr_state or getattr(spawner, "pr_state", None) or _default_pr_state())) finally: @@ -869,7 +879,9 @@ def tick(brief_path: Path, mind: Path, *, home: Path | None = None, top = _brief.parse(brief_path.read_text(encoding="utf-8"))["top"] shift = {"issue": (top.get("issue") or {}).get("value", ""), - "review_at": (top.get("review-at") or {}).get("value", "")} + "review_at": (top.get("review-at") or {}).get("value", ""), + "dispatched": (top.get("dispatched") or {}).get("value", ""), + "brief_path": brief_path} (slot / "leases").mkdir(parents=True, exist_ok=True) if not _take_lock(slot, now): return {"action": "busy", "reason": "another tick holds the lock"} @@ -878,7 +890,7 @@ def tick(brief_path: Path, mind: Path, *, home: Path | None = None, spawner or default_spawner(brief_path, brief), grace_s, records, agents, tokens, health, pr_state, poster=poster, shift=shift, token_reserve=token_reserve, - whoami=whoami) + whoami=whoami, github=github) finally: _drop_lock(slot) _log(slot, now, result) @@ -892,10 +904,35 @@ def active_leases(slot: Path) -> dict[str, dict]: def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, tokens, health=None, pr_state=None, *, poster=None, shift=None, - token_reserve=None, whoami=None) -> dict: + token_reserve=None, whoami=None, github=None) -> dict: + """The tick under its lock, then the live status (PyAutoBrain#622): one + `claude agents` view and one set of `gh pr checks` reads serve both.""" + shift = shift or {} + agents = agents or AgentsView() + health = _TickHealth(health) + out = _tick_body(slot, brief, mind, now, spawner, grace_s, records, agents, tokens, + health, pr_state, poster=poster, shift=shift, + token_reserve=token_reserve, whoami=whoami, github=github) + status = _live_status(slot, mind, shift, now, agents, health.cached, github) + if status: + out["status"] = status + return out + + +def _tick_body(slot, brief, mind, now, spawner, grace_s, records, agents, + tokens, health=None, pr_state=None, *, poster=None, shift=None, + token_reserve=None, whoami=None, github=None) -> dict: counters = read_counters(slot) counters["usage_unavailable"] = [] # this tick's reads decide reaped = _reap(slot, counters, now, grace_s, agents, tokens) + # 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. + commands = _steer(slot, counters, shift or {}, now, github) + _write_counters(slot, counters) + if (slot / STOP_FILE).exists(): + # 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} # 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} @@ -929,12 +966,16 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, queue=_batch.read_queue(mind)) counters["backlog_gates"] = {"lane_absent": sorted(d["lane_absent"]), "queue_stop": d["queue_stop"]} + paused = bool(counters.get("paused")) if _brief.is_shadow(brief): - proposed = _propose(d["members"], brief, counters, max_sessions) + proposed = [] if paused else _propose( + [m for m in d["members"] if task_id(m["path"]) not in counters["dropped"]], + brief, counters, max_sessions) _write_counters(slot, counters) - return {"action": "shadow", "reaped": reaped, "spawned": [], - "proposed": proposed, "refused": [], "live": sorted(live), - "ledger": ledger} + out = {"action": "shadow", "reaped": reaped, "spawned": [], + "proposed": proposed, "refused": [], "live": sorted(live), + "ledger": ledger} + return _steered(out, commands, paused) budget = _brief._nonneg_int(brief.get("token-budget", {}).get("value", "")) # A real worker holds a reservation from its spawn until its measured # usage passes it, so the budget binds on the first tick (#610). A fake @@ -944,10 +985,10 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, reserve = token_reserve if token_reserve is not None \ else default_token_reserve(budget, max_sessions) spawned, refused = [], [] - for member in d["members"]: + for member in [] if paused else d["members"]: task = task_id(member["path"]) if task in live or task in counters["done"] or task in counters["abandoned"] \ - or task in counters["parked"]: + or task in counters["parked"] or task in counters["dropped"]: continue if len(live) >= max_workers: refused.append({"task": task, "why": f"max-workers {max_workers} reached"}) @@ -1012,6 +1053,15 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, "closeouts": closeouts} if mentions: out["mentions"] = mentions + return _steered(out, commands, paused) + + +def _steered(out: dict, commands: list, paused: bool) -> dict: + """A tick's result with what the human's commands did to it.""" + if commands: + out["commands"] = commands + if paused: + out["paused"] = True return out @@ -1249,6 +1299,301 @@ def _mentions(slot: Path, counters: dict, shift: dict, poster, now: _dt.datetime return out +# --- the live shift view you can steer (PyAutoBrain#622) ---------------------------- + +#: The one live status comment of a shift: claimed by this marker before its +#: create, then only edited — never a second (AUTONOMY.md watcher network +#: surface, amendment 2026-11-13). +STATUS_MARKER = "status.json" +STATUS_FILE = "status.md" +#: An unchanged status is re-edited this often (time left, tokens); any change +#: of state edits it on the tick that sees it. Never more than one edit a tick. +STATUS_REFRESH_S = 600 +#: The hidden first line of the status comment; the comments read adopts a +#: create that may have landed (a timeout, a crash after the claim) by it. +STATUS_TAG = "" +STATUS_TAG_PREFIX = "" in c["body"].split("\n", 1)[0] and c["url"]: + # A create that timed out (or a tick that died after its + # claim) did land: adopt it, and edit it from now on. + rec.update(state="posted", url=c["url"], due=True, adopted_at=_iso(now)) + marker.write_text(json.dumps(rec, sort_keys=True)) + continue + if c["id"] in seen or (rec and c["url"] and c["url"] == rec.get("url")): + continue + if c["login"].lower() != login.lower(): + continue + try: + created = _parse_iso(c["created_at"]) + except ValueError: + continue + if start is not None and created < start: + continue + parsed = _parse_command(c["body"]) + if parsed is None: + continue + cmd, arg = parsed + seen.add(c["id"]) + ack = _apply_command(slot, counters, cmd, arg, c["login"], c["created_at"]) + counters["commands"].append({"id": c["id"], "command": "/" + cmd + (f" {arg}" if arg else ""), + "by": c["login"], "at": c["created_at"], "url": c["url"], + "ack": ack}) + out.append({"command": cmd, "arg": arg, "ack": ack}) + counters["commands_seen"] = sorted(seen) + return out + + +class _TickHealth: + """One tick's `gh pr checks` reads, remembered: the status comment shows + what the close-outs read and never makes a read of its own.""" + + def __init__(self, health=None): + self._health, self.seen = health, {} + + def __call__(self, url: str) -> str: + if url not in self.seen: + self.seen[url] = (self._health or _digest.pr_health)(url) + return self.seen[url] + + def cached(self, url: str) -> str: + return self.seen.get(url, "open (CI not read this tick)") + + +def _post_status(slot: Path, issue: str, text: str, key: str, now: _dt.datetime, + github=None) -> dict: + """At most one GitHub write: create the status comment (marker claimed + first, exclusively), or edit it. A create `gh` said failed landed nothing + and is made again next tick; one that timed out, or a claim whose tick + died, may have landed: it is never made again, only adopted by the + comments read. An edit that fails is retried next tick.""" + marker, body = slot / STATUS_MARKER, slot / STATUS_FILE + rec = _read_json(marker) + if rec is None or rec.get("state") == "failed": + if rec is None: + rec = {"at": _iso(now), "issue": issue, "state": "claimed", "tries": 1, + "nonce": os.urandom(6).hex()} + if not _create_exclusive(marker, rec): + return {"status": "busy"} + else: + rec.update(state="claimed", tries=int(rec.get("tries", 1)) + 1, error=None) + marker.write_text(json.dumps(rec, sort_keys=True)) + body.write_text(STATUS_TAG.format(slot=slot.name, nonce=rec["nonce"]) + "\n" + text, + encoding="utf-8") + res = gh_comment(issue, body, run=github) + if res.get("posted") and "#issuecomment-" in res.get("url", ""): + rec.update(state="posted", url=res["url"], key=key, edited_at=_iso(now), due=False) + elif res.get("posted"): + # Landed, but gh printed no comment URL: adopted by the next read. + rec.update(state="unknown", error="posted without a comment URL") + else: + rec.update(state="failed" if res.get("retry", True) else "unknown", + error=res.get("error", "")) + marker.write_text(json.dumps(rec, sort_keys=True)) + return {"status": "created" if rec["state"] == "posted" else "create " + rec["state"]} + if rec.get("state") != "posted": + return {"status": "unknown — never re-created; adopted when the comments read sees it"} + try: + stale = (now - _parse_iso(rec.get("edited_at") or "")).total_seconds() >= STATUS_REFRESH_S + except ValueError: + stale = True + if not (rec.get("due") or rec.get("key") != key or stale): + return {"status": "unchanged"} + body.write_text(STATUS_TAG.format(slot=slot.name, nonce=rec["nonce"]) + "\n" + text, + encoding="utf-8") + res = gh_comment_edit(rec.get("url", ""), body, run=github) + if res.get("edited"): + rec.update(key=key, edited_at=_iso(now), due=False, edits=int(rec.get("edits", 0)) + 1) + rec.pop("error", None) + else: + rec.update(due=True, error=res.get("error", "")) + marker.write_text(json.dumps(rec, sort_keys=True)) + return {"status": "edited" if res.get("edited") else "edit failed — retried next tick"} + + +def _live_status(slot: Path, mind: Path, shift: dict, now: _dt.datetime, agents, + health, github=None) -> dict | None: + """The end of every open tick: the status comment (create once, then edit) + and the dashboard's `- live:` line. Built from the same snapshot as + `batch watch`, from what this tick already read — no read of its own.""" + brief_path = shift.get("brief_path") + if brief_path is None: + return None + import _watch # noqa: E402 — deferred: _watch imports this module + snap = _watch.snapshot(brief_path, slot, now, agents=agents, health=health) + out = {} + issue = shift.get("issue", "") + if issue.startswith("http"): + snap["commands_on"] = bool(mention_login()) + out = _post_status(slot, issue, _watch.render_status(snap), + _watch.status_key(snap), now, github) + snap["status_url"] = status_url(slot) + line, key = _watch.live_line(snap) + rel = _record_rel(Path(brief_path), mind) + keyfile = slot / LIVE_KEY_FILE + old = keyfile.read_text(encoding="utf-8") if keyfile.exists() else "" + if rel is not None and key != old: + _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, + {"op": "record-key", "path": rel, "key": "live", "value": line}) + keyfile.write_text(key, encoding="utf-8") + try: + out["ledger"] = _mind_writer.commit_ledger(slot, mind, + f"shift {slot.name}: live status") + except _mind_writer.MindWriteError as e: + out["ledger"] = {"committed": None, "error": str(e)} + return out or None + + # --- the digest (phase 3d) ---------------------------------------------------------- def _record_rel(brief_path: Path, mind: Path) -> str | None: @@ -1379,7 +1724,7 @@ def _github_merges(counters: dict, review_at, pr_state) -> None: def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, poster=None, health=None, agents=None, tokens=transcript_usage, - grace_s: float = LEASE_GRACE_S, pr_state=None) -> dict: + grace_s: float = LEASE_GRACE_S, pr_state=None, github=None) -> dict: """Reap, then write the digest into the record and post it on the brief's issue. Reaping first (#610) puts a `.done` written after the last live tick into @@ -1398,6 +1743,7 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, brief, top = rec["brief"] or {}, rec["top"] counters = read_counters(slot) counters["usage_unavailable"] = [] + agents = agents or AgentsView() # one `claude agents` read serves the closing status _reap(slot, counters, now, grace_s, agents, tokens) counters["pending_redispatch"] = [] # the grant has ended: never re-dispatched if not _brief.is_shadow(brief): @@ -1416,6 +1762,12 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, # The pilot ledger (phase 4a; jsonl #610): one row per shift, in the # same commit, upserted by slot so a rerun never writes a second. _queue_pilot(slot, brief, counters, amended=False) + if (slot / LIVE_KEY_FILE).exists(): + # The dashboard's live line ends with the shift (#622). + _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, { + "op": "record-key", "path": rel, "key": "live", + "value": "closed at review-at — the digest is below" + + (f" — status: {status_url(slot)}" if status_url(slot) else "")}) try: result["ledger"] = _mind_writer.commit_ledger( slot, mind, f"shift {slot.name}: digest") @@ -1430,9 +1782,29 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, result["post"] = {"posted": False, "error": "already posted this shift"} return result result["post"] = {k: posted[k] for k in ("posted", "url", "error") if k in posted} + closing = _close_status(brief_path, slot, issue, now, agents, github) + if closing: + result["status"] = closing return result +def _close_status(brief_path: Path, slot: Path, issue: str, now: _dt.datetime, + agents, github=None) -> dict | None: + """One last edit of the status comment at `review-at:`, saying the shift + is closed (#622); never retried — the digest is the record from here.""" + rec = _read_json(slot / STATUS_MARKER) + if not rec or rec.get("state") != "posted": + return None + import _watch # noqa: E402 + snap = _watch.snapshot(brief_path, slot, now, agents=agents, + health=lambda u: "see the digest") + snap["commands_on"] = False + rec["due"] = True + (slot / STATUS_MARKER).write_text(json.dumps(rec, sort_keys=True)) + return _post_status(slot, issue, _watch.render_status(snap), _watch.status_key(snap), + now, github) + + def _write_packet(slot: Path, digest: str) -> Path: """The opt-in HTML packet (`packet: yes`): the digest on one page.""" import html @@ -1565,14 +1937,19 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti _write_counters(slot, counters) verdict_file.unlink(missing_ok=True) - if _brief.is_shadow(brief): - return events + if _brief.is_shadow(brief) or counters.get("paused"): + return events # paused (#622): a green PR waits; it is not refused cap = _brief._nonneg_int(brief.get("merge-cap", {}).get("value", "")) or 0 for task, out in counters["outcomes"].items(): for pr in out["prs"]: if "/pull/" not in pr or pr in out["merged"] or pr in counters["closeouts"]: continue tier = counters["picks"].get(task, {}).get("tier", "?") + if task in counters["dropped"]: + counters["closeouts"][pr] = {"task": task, "state": "refused", + "why": "dropped by /drop — the human's /prm"} + events["refused"].append(pr) + continue if tier != "glance": counters["closeouts"][pr] = {"task": task, "state": "refused", "why": f"tier {tier} — only glance merges unattended"} diff --git a/agents/conductors/batch/_status.py b/agents/conductors/batch/_status.py index 7a02572f..73e3df43 100644 --- a/agents/conductors/batch/_status.py +++ b/agents/conductors/batch/_status.py @@ -186,6 +186,9 @@ def _status(slot: str, kind: str, keys: dict, rows: list, reviewable: bool, "url": review_url(pages, slot) if reviewable else "", "packet": f"batches/packets/{slot}.html", "freeze": freeze, + # A running shift's status, as its watcher last wrote it into the + # record (`- live:`, PyAutoBrain#622) — a record line, not a clock. + "live": _one(keys, "live"), } @@ -215,6 +218,20 @@ def _headline(st: dict) -> str: return f"Batch {st['slot']} — " + " · ".join(counts) +_URL_RE = re.compile(r"https://[^\s<>\"']+") + + +def _linked(text: str) -> str: + """`text` escaped, with each https URL in it a link.""" + out, last = [], 0 + for m in _URL_RE.finditer(text): + out.append(_html.escape(text[last:m.start()])) + url = _html.escape(m.group(0)) + out.append(f'{url}') + last = m.end() + return "".join(out) + _html.escape(text[last:]) + + def render_html(st: dict | None) -> str: """The box as one `verdict` banner — the theme's existing class.""" if st is None: @@ -224,6 +241,8 @@ def render_html(st: dict | None) -> str: H = [f'
{esc(_headline(st))}'] if st.get("freeze"): H.append(f'

{esc(st["freeze"])}

') + if st.get("live"): + H.append(f'

Live: {_linked(st["live"])}

') for r in st["members"]: line = (f'{esc(r["slug"])}' f'{pills((r["state"], _TONE.get(r["state"], "n")))}') @@ -251,6 +270,8 @@ def render_md(st: dict | None) -> str: L = [f"> **{_headline(st)}**", ">"] if st.get("freeze"): L += [f"> {st['freeze']}", ">"] + if st.get("live"): + L += [f"> Live: {st['live']}", ">"] for r in st["members"]: line = f"> - `{r['slug']}` — {r['state']}" if r["detail"]: diff --git a/agents/conductors/batch/_watch.py b/agents/conductors/batch/_watch.py index e769a606..6dddad9f 100644 --- a/agents/conductors/batch/_watch.py +++ b/agents/conductors/batch/_watch.py @@ -15,6 +15,10 @@ Task wording comes from `_digest.task_state`, the digest's own, so the live view and the digest never disagree. + +The same snapshot is the shift's live status comment on its issue +(`render_status`, written by the watcher, PyAutoBrain#622) and the dashboard's +`- live:` record line (`live_line`); this verb itself still writes nothing. """ from __future__ import annotations @@ -137,6 +141,14 @@ def snapshot(brief_path: Path, slot: Path, now: _dt.datetime, *, agents=None, "digest_posted": (slot / _orchestrator.DIGEST_MARKER).exists(), "started": started, "tasks": rows, + # Steering (PyAutoBrain#622): a pause, the dropped tasks, every command + # enacted with its acknowledgement, and where the status comment is. + "paused": counters.get("paused") or None, + "dropped": sorted(counters.get("dropped") or {}), + "commands": list(counters.get("commands") or []), + "commands_unread": counters.get("commands_unread") or "", + "refusals": _digest.refusal_lines(counters) if started else [], + "status_url": _orchestrator.status_url(slot) if started else "", "budgets": { "workers": f"{sum(l.get('state') != 'parked' for l in held.values())} live of {_brief.cap_of(brief, 'max-workers')}", "sessions": f"{counters.get('sessions', 0)} of {_brief.cap_of(brief, 'max-sessions')}", @@ -158,12 +170,30 @@ def _tick_line(t: dict) -> str: return f" {at} {t.get('action', '?')}" + (f" — {counts}" if counts else "") -def render(snap: dict) -> str: +def _flags(snap: dict) -> list[str]: flags = [snap["mode"], snap["time_left"]] if snap["stop"]: flags.append("STOP present — the watcher does nothing") + if snap.get("paused"): + flags.append(f"PAUSED by {snap['paused'].get('by', '?')} — /resume to continue") if snap["digest_posted"]: flags.append("digest posted") + return flags + + +def _steering_lines(snap: dict) -> list[str]: + """Refusals and commands, as bullets; only the sections that have any.""" + lines = [] + if snap.get("refusals"): + lines += ["", "Refusals"] + snap["refusals"] + if snap.get("commands"): + lines += ["", "Commands"] + [f"- `{c['command']}` by {c['by']} at {c['at']} — {c['ack']}" + for c in snap["commands"]] + return lines + + +def render(snap: dict) -> str: + flags = _flags(snap) lines = [f"Shift {snap['slot']} — " + " · ".join(flags), f" {snap['dispatched']} → {snap['review_at']} (as of {snap['now']})", f" brief: {snap['brief']}", ""] @@ -177,12 +207,82 @@ def render(snap: dict) -> str: lines += ["", "Budgets", f"- workers: {b['workers']}", f"- sessions: {b['sessions']}", f"- tokens: {b['tokens']}", - f"- merges: {b['merges']}", f"- workers crashed: {b['crashes']}", - "", "Last ticks"] + f"- merges: {b['merges']}", f"- workers crashed: {b['crashes']}"] + lines += _steering_lines(snap) + if snap.get("status_url"): + lines += ["", f"Status comment: {snap['status_url']}"] + lines += ["", "Last ticks"] lines += [_tick_line(t) for t in snap["ticks"]] or [" none"] return "\n".join(lines) + "\n" +# --- the live status comment and the dashboard line (PyAutoBrain#622) ----------- + +COMMAND_HELP = ("Steer it with a comment from the human's login, its first line one of: " + "`/pause`, `/resume`, `/drop `, `/stop`.") + + +def render_status(snap: dict) -> str: + """The shift's live status comment: the `render` snapshot as Markdown, + without the tick log. It never names a login with `@` — an edit must not + notify (AUTONOMY.md push test).""" + lines = [f"**Shift `{snap['slot']}` — " + " · ".join(_flags(snap)) + "**", + f"{snap['dispatched']} → {snap['review_at']} (as of {snap['now']}; " + "this comment is edited in place, never re-posted)", "", "**Tasks**"] + lines += [f"- {r['label']} — {r['state']} — {r['tier']} — why: {r['why']}" + + (f" — re-dispatched {r['redispatched']}×" if r["redispatched"] else "") + for r in snap["tasks"]] or ["- none yet"] + b = snap["budgets"] + lines += ["", "**Budgets**", f"- workers: {b['workers']}", f"- sessions: {b['sessions']}", + f"- tokens: {b['tokens']}", f"- merges: {b['merges']}", + f"- workers crashed: {b['crashes']}"] + for line in _steering_lines(snap): + lines.append(f"**{line}**" if line in ("Refusals", "Commands") else line) + if snap.get("commands_unread"): + lines += ["", f"_Commands could not be read at {snap['commands_unread']}; " + "the next tick reads again._"] + if snap.get("commands_on", True) and not snap["digest_posted"]: + lines += ["", COMMAND_HELP] + elif not snap.get("commands_on", True) and not snap["digest_posted"]: + lines += ["", "_Steering is off: no human login is set (`PYAUTO_SHIFT_MENTION` " + "or `shift_watcher: mention_login:`)._"] + return "\n".join(lines).replace("@", "@\u200b") + "\n" + + +def status_key(snap: dict) -> str: + """What makes a status edit due at once: the snapshot without its clock, + its token figure and its tick log — those refresh every + `_orchestrator.STATUS_REFRESH_S` instead.""" + keep = {k: v for k, v in snap.items() + if k not in ("now", "time_left", "ticks", "budgets", "status_url")} + keep["budgets"] = {k: v for k, v in snap["budgets"].items() if k != "tokens"} + keep["refusals"] = [r.rsplit(" — ", 1)[0] for r in snap.get("refusals") or []] + keep["commands_unread"] = bool(snap.get("commands_unread")) + return json.dumps(keep, sort_keys=True, default=str) + + +def live_line(snap: dict) -> tuple[str, str]: + """The dashboard's one-line copy of the status (the brief record's + `- live:` key), and the part of it whose change rewrites it.""" + states = [r["state"] for r in snap["tasks"]] + counts = { + "running": sum(s.startswith(("running", "dropped, still running")) for s in states), + "blocked or parked": sum(s.startswith(("blocked", "parked")) for s in states), + "finished": sum("github.com" in s or s.startswith(("finished", "obsolete")) + for s in states), + "dropped": len(snap.get("dropped") or []), + "refusal reasons": len(snap.get("refusals") or []), + } + head = [snap["mode"]] + (["STOPPED"] if snap["stop"] else []) \ + + (["PAUSED"] if snap.get("paused") else []) \ + + [", ".join(f"{n} {k}" for k, n in counts.items() if n) or "nothing started"] + key = " · ".join(head) + (f" — status: {snap['status_url']}" if snap.get("status_url") else "") + line = (" · ".join(head) + f" · tokens {snap['budgets']['tokens']}" + + f" · review-at {snap['review_at']} (as of {snap['now']})" + + (f" — status: {snap['status_url']}" if snap.get("status_url") else "")) + return " ".join(line.split()), key + + def watch(brief_path: Path, slot: Path, *, interval: float = MIN_INTERVAL_S, once: bool = False, out=None, sleep=time.sleep, clock=None, agents=None, health=None) -> int: diff --git a/skills/batch/batch.md b/skills/batch/batch.md index 797257fc..30e807e1 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -106,9 +106,9 @@ After `review-at:` its one remaining act is the digest: written into the record and posted once on the brief's `issue:`. A `shadow: yes` brief plans and digests but spawns nothing — the pilot's baseline; every shift keeps one line in `PyAutoMind/batches/pilot/pilot.jsonl`, rendered to `pilot.md` (`?` cells the human's at check-in). A parked worker @-mentions the human on that issue, once. Once a worker's `glance` PR is green, the -watcher starts one independent close-out session that merges it or refuses; -each merge adds a row to the stage-2 table in `PyAutoMind/autonomy_log.md`. +watcher starts one independent close-out session that merges it or refuses; each merge adds a row to the stage-2 table in `PyAutoMind/autonomy_log.md`. What a tick does, its state, caps and the install commands: `agents/conductors/batch/AGENTS.md` "The watcher". +**`/batch watch`** ("how is the shift going?"): run `bin/pyauto-brain batch watch --record --once` and relay it as written; with no slot on this machine, read the status comment on its `issue:` ([`reference.md`](reference.md)). The human steers with their own comment there (`/pause`, `/resume`, `/drop `, `/stop`); never post one for them. ## When they come back — collect, review, close (2026-08-31) diff --git a/skills/batch/reference.md b/skills/batch/reference.md index 7094446b..4bbd118e 100644 --- a/skills/batch/reference.md +++ b/skills/batch/reference.md @@ -113,3 +113,21 @@ their own `review-at:` estimate), `delivered:` (`batch.md`: "`delivered:` is not review file's path) and **`review-minutes-actual:`**. That last number is the only calibration the review estimate will ever get, so ask for it if the human does not volunteer it. + +## `/batch watch` and steering a running shift (PyAutoBrain#622) + +- **On the laptop** (the slot is local): `bin/pyauto-brain batch watch --record + PyAutoMind/batches/.md --once`. It is read-only; relay the snapshot as + written, then explain what stands out (a parked worker, a refusal that + repeats, a budget near its cap). +- **Anywhere else**: the watcher keeps the same snapshot as one comment on the + brief's `issue:`, edited in place. Read it with `gh issue view + --comments` (or the GitHub connector) — it is the comment whose first line is + ``. The dashboard's batch box carries a + one-line copy (`Live: …`) with its link. +- **Steering is the human's comment on that issue**, its first line one of + `/pause`, `/resume`, `/drop `, `/stop`, from their own login (the + watcher ignores every other account and its own comments). Each command is + acknowledged once, in the status comment's `Commands` list, on the next tick. + A dropped worker that is already running is not killed: stopping it is the + human's, `claude stop ` on the laptop. Never post a command for them. diff --git a/tests/conftest.py b/tests/conftest.py index 0c9ec17a..765b3583 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -38,6 +38,13 @@ def _no_real_github(monkeypatch): real_login = orch.gh_login monkeypatch.setattr(orch, "gh_login", lambda run=None: real_login(run=run) if run else None) + # PyAutoBrain#622: the status comment's edit and the steering read. + real_edit, real_read = orch.gh_comment_edit, orch.gh_issue_comments + monkeypatch.setattr(orch, "gh_comment_edit", lambda url, body, run=None: + real_edit(url, body, run=run) if run else + {"edited": False, "error": "offline (tests)"}) + monkeypatch.setattr(orch, "gh_issue_comments", lambda issue, since, run=None: + real_read(issue, since, run=run) if run else None) monkeypatch.delenv(orch.MENTION_ENV, raising=False) monkeypatch.delenv(orch.GH_TOKEN_ENV, raising=False) if digest is not None: diff --git a/tests/test_orchestrator_steering.py b/tests/test_orchestrator_steering.py new file mode 100644 index 00000000..734239cb --- /dev/null +++ b/tests/test_orchestrator_steering.py @@ -0,0 +1,362 @@ +"""PyAutoBrain#622: a live shift view you can steer (human ruling 2026-11-13). + +One status comment per shift on its digest issue, created once and then only +edited; `/pause`, `/resume`, `/drop ` and `/stop` read from the human's +comments each tick; the dashboard's `- live:` record line. Every `gh` call +goes to a fake GitHub (`FakeGitHub`), so nothing here reaches the network. +""" + +from __future__ import annotations + +import datetime as _dt +import json +import sys +from pathlib import Path +from types import SimpleNamespace + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "tests")) +import test_orchestrator_dispatch as d # noqa: E402 — the 3b fixtures +from test_orchestrator_dispatch import _brief, orch # noqa: E402 +import _mind_writer # noqa: E402 +import _status # noqa: E402 +import _watch # noqa: E402 + +NOW = d.NOW # 2026-11-04T09:00Z; dispatched 08:30Z +ISSUE = "https://github.com/example-org/example-mind/issues/4242" +LOGIN = "example-human" +BOT = "example-bot" + + +def _at(minutes: float) -> _dt.datetime: + return NOW + _dt.timedelta(minutes=minutes) + + +class FakeGitHub: + """The issue's comments, behind `gh issue comment`, `gh api PATCH` and + `gh api …/comments`. Records each call's kind; fails the next `fail[kind]`.""" + + def __init__(self): + self.comments, self.calls = [], [] + self.fail = {"create": 0, "edit": 0, "read": 0} + self._id = 100 + + def add(self, login: str, body: str, minutes: float) -> str: + self._id += 1 + stamp = orch._iso(_at(minutes)) + self.comments.append({"id": self._id, "user": {"login": login}, "body": body, + "created_at": stamp, "updated_at": stamp, + "html_url": f"{ISSUE}#issuecomment-{self._id}"}) + return self.comments[-1]["html_url"] + + def __call__(self, argv, **kw): + if argv[:3] == ["gh", "issue", "comment"]: + kind = "create" + elif argv[:4] == ["gh", "api", "-X", "PATCH"]: + kind = "edit" + elif argv[:2] == ["gh", "api"] and "/comments" in argv[2]: + kind = "read" + else: + raise AssertionError(f"unexpected gh call {argv}") + self.calls.append(kind) + if self.fail[kind]: + self.fail[kind] -= 1 + return SimpleNamespace(returncode=1, stdout="", stderr="HTTP 502") + if kind == "create": + body = Path(argv[argv.index("--body-file") + 1]).read_text() + return SimpleNamespace(returncode=0, stdout=self.add(BOT, body, 0) + "\n", stderr="") + if kind == "edit": + cid = int(argv[4].rsplit("/", 1)[1]) + body = json.loads(Path(argv[argv.index("--input") + 1]).read_text())["body"] + next(c for c in self.comments if c["id"] == cid)["body"] = body + return SimpleNamespace(returncode=0, stdout="", stderr="") + return SimpleNamespace(returncode=0, stdout=json.dumps(self.comments), stderr="") + + def status(self) -> list[dict]: + return [c for c in self.comments if c["body"].startswith(orch.STATUS_TAG_PREFIX)] + + +def _shift(tmp_path, monkeypatch, names=("t1",), extra=""): + monkeypatch.setenv(orch.MENTION_ENV, LOGIN) + mind, brief, home = d._shift(tmp_path, names=names, extra=extra) + brief.write_text(brief.read_text().replace( + "- review-at: 2026-11-04T11:30Z\n", f"- review-at: 2026-11-04T11:30Z\n- issue: {ISSUE}\n")) + return mind, brief, home, orch.slot_dir(brief, home) + + +def _tick(brief, mind, home, minutes, claude, gh, states=None): + slot = orch.slot_dir(brief, home) + agents = d._agents(states, slot) if states else orch.AgentsView([]) + before = len(gh.calls) + r = orch.tick(brief, mind, home=home, now=_at(minutes), grace_s=0, + spawner=orch.RealSpawner(brief, "auto", run=claude), agents=agents, + tokens=lambda s: 0, health=lambda u: "RUNNING", github=gh, + poster=lambda i, b: {"posted": False, "retry": False, "error": "digest"}) + this = gh.calls[before:] + # The bound (#622): one comments read and one status write a tick, at most. + assert this.count("read") <= 1 and len(this) - this.count("read") <= 1, this + return r + + +def _spawned(claude) -> list[str]: + return [argv[argv.index("--name") + 1] for argv, _ in claude.calls] + + +# --- the status comment --------------------------------------------------------- + +def test_the_status_comment_is_created_once_and_then_only_edited(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + r = _tick(brief, mind, home, 0, claude, gh) + assert r["status"]["status"] == "created" and gh.calls == ["read", "create"] + assert len(gh.status()) == 1 + body = gh.status()[0]["body"] + assert body == (slot / orch.STATUS_FILE).read_text() + assert "**Shift `shift` — LIVE · 2h 30m left**" in body and "- tokens: 0 of 100000" in body + assert "(`t1`; small · pyautobrain) — running? (agent 00000001" in body and "@" not in body + + r = _tick(brief, mind, home, 1, claude, gh, {"t1": "working"}) # now listed: a change + assert r["status"]["status"] == "edited" and "running (agent 00000001, working" in \ + gh.status()[0]["body"] + r = _tick(brief, mind, home, 2, claude, gh, {"t1": "working"}) # nothing changed + assert r["status"]["status"] == "unchanged" and gh.calls[-1] == "read" + (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n") + r = _tick(brief, mind, home, 4, claude, gh, {"t1": "done"}) # a state change + assert r["status"]["status"] == "edited" + assert "https://github.com/o/r/pull/9 — RUNNING" in gh.status()[0]["body"] + r = _tick(brief, mind, home, 20, claude, gh) # the 10-minute refresh + assert r["status"]["status"] == "edited" and "2h 10m left" in gh.status()[0]["body"] + + assert gh.calls.count("create") == 1 and len(gh.status()) == 1 + rec = json.loads((slot / orch.STATUS_MARKER).read_text()) + assert rec["state"] == "posted" and rec["edits"] == 3 + + +def test_a_tick_that_died_after_its_claim_never_makes_a_second_comment(tmp_path, monkeypatch): + """Marker before post: a claim with no recorded result is never re-created; + the comments read adopts the comment if the create did land.""" + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + real = orch.gh_comment + + def create_then_die(issue, body, run=None): + real(issue, body, run=run) + raise RuntimeError("tick died after the create") + monkeypatch.setattr(orch, "gh_comment", create_then_die) + try: + _tick(brief, mind, home, 0, claude, gh) + except RuntimeError: + pass + orch._drop_lock(slot) + monkeypatch.setattr(orch, "gh_comment", real) + assert json.loads((slot / orch.STATUS_MARKER).read_text())["state"] == "claimed" + _tick(brief, mind, home, 2, claude, gh, {"t1": "working"}) # adopted by the read, edited + _tick(brief, mind, home, 5, claude, gh, {"t1": "working"}) + assert gh.calls.count("create") == 1 and len(gh.status()) == 1 + rec = json.loads((slot / orch.STATUS_MARKER).read_text()) + assert rec["state"] == "posted" and rec["url"] == gh.status()[0]["html_url"] + assert gh.calls.count("edit") >= 1 + + +def test_a_failed_status_edit_is_retried_next_tick(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n") + gh.fail.update(edit=1, read=1) # GitHub unreachable this tick + r = _tick(brief, mind, home, 3, claude, gh, {"t1": "done"}) + assert r["action"] == "ticked" and r["reaped"] == [{"task": "t1", "event": "done"}] + assert r["status"]["status"] == "edit failed — retried next tick" + assert "pull/9" not in gh.status()[0]["body"] + r = _tick(brief, mind, home, 4, claude, gh) # nothing new changed: still due + assert r["status"]["status"] == "edited" and "pull/9" in gh.status()[0]["body"] + assert gh.calls.count("create") == 1 + + +def test_a_failed_create_is_made_again_and_still_only_once(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + gh.fail["create"] = 1 + assert _tick(brief, mind, home, 0, claude, gh)["status"]["status"] == "create failed" + assert _tick(brief, mind, home, 3, claude, gh, {"t1": "working"})["status"]["status"] == "created" + _tick(brief, mind, home, 6, claude, gh, {"t1": "working"}) + assert len(gh.status()) == 1 + + +# --- the commands --------------------------------------------------------------- + +def test_pause_holds_new_spawns_until_resume(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch, names=("t1", "t2"), + extra=" - max-workers: 1\n") + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + assert _spawned(claude) == ["shift:t1"] + gh.add(LOGIN, "/pause", 1) + (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n") + r = _tick(brief, mind, home, 3, claude, gh, {"t1": "done"}) + assert r["paused"] and r["spawned"] == [] and r["reaped"][0]["event"] == "done" + assert r["commands"][0]["command"] == "pause" + assert "PAUSED by example-human" in gh.status()[0]["body"] + _tick(brief, mind, home, 6, claude, gh) + assert _spawned(claude) == ["shift:t1"] + gh.add(LOGIN, "/resume", 7) + r = _tick(brief, mind, home, 9, claude, gh) + assert "paused" not in r and r["spawned"][0]["task"] == "t2" + assert "PAUSED" not in gh.status()[0]["body"] + + +def test_drop_removes_a_pick_not_yet_spawned(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch, names=("t1", "t2"), + extra=" - max-workers: 1\n") + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + gh.add(LOGIN, "/drop draft/feature/pyautobrain/t2.md\n\nnot this one today", 1) + (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n") + r = _tick(brief, mind, home, 3, claude, gh, {"t1": "done"}) + assert r["spawned"] == [] and r["commands"][0]["ack"].startswith("dropped `t2`: it will not") + _tick(brief, mind, home, 6, claude, gh) + assert _spawned(claude) == ["shift:t1"] + body = gh.status()[0]["body"] + assert "`t2`" in body and "dropped by /drop — not started" in body + + +def test_drop_of_a_running_worker_leaves_it_running_and_never_merges_it(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + gh.add(LOGIN, "/drop t1", 1) + r = _tick(brief, mind, home, 3, claude, gh, {"t1": "working"}) + assert "`claude stop 00000001`" in r["commands"][0]["ack"] + assert "dropped, still running — running (agent 00000001" in gh.status()[0]["body"] + assert orch.leases(slot)["t1"] # never killed by the watcher + (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n") + _tick(brief, mind, home, 6, claude, gh, {"t1": "done"}) + co = orch.read_counters(slot)["closeouts"]["https://github.com/o/r/pull/9"] + assert co["state"] == "refused" and "dropped by /drop" in co["why"] + + +def test_stop_behaves_like_the_kill_switch_file(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch, names=("t1", "t2"), + extra=" - max-workers: 1\n") + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + gh.add(LOGIN, "/stop", 1) + (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n") + r = _tick(brief, mind, home, 3, claude, gh, {"t1": "done"}) + assert r["action"] == "stopped" and (slot / orch.STOP_FILE).exists() + assert "STOP present — the watcher does nothing" in gh.status()[0]["body"] + calls = len(gh.calls) + r = _tick(brief, mind, home, 6, claude, gh) + assert r == {"action": "stopped", "reason": "STOP present"} + assert len(gh.calls) == calls and _spawned(claude) == ["shift:t1"] + + +def test_a_command_from_another_login_or_the_bot_or_before_the_shift_is_ignored( + tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch, names=("t1", "t2"), + extra=" - max-workers: 1\n") + claude, gh = d.FakeClaude(), FakeGitHub() + gh.add(LOGIN, "/pause", -40) # before dispatched: a past shift's + _tick(brief, mind, home, 0, claude, gh) + gh.add("someone-else", "/stop", 1) + gh.add(BOT, "/pause", 1) # not the human's login + gh.add(LOGIN, "please /pause after this one", 1) # not a command line + (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n") + r = _tick(brief, mind, home, 3, claude, gh, {"t1": "done"}) + assert "commands" not in r and "paused" not in r and r["spawned"][0]["task"] == "t2" + assert not (slot / orch.STOP_FILE).exists() and orch.read_counters(slot)["commands"] == [] + # The status comment itself names every command: it is never read as one, + # even when it posts as the human's own login. + monkeypatch.setenv(orch.MENTION_ENV, BOT) + r = _tick(brief, mind, home, 6, claude, gh, {"t2": "working"}) + assert [c["command"] for c in r.get("commands", [])] == ["pause"] # the bot's own /pause line + assert "/pause" in gh.status()[0]["body"] and orch.read_counters(slot)["commands"][0]["by"] == BOT + + +def test_a_command_is_enacted_and_acknowledged_once(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + gh.add(LOGIN, "/pause", 1) + for minutes in (3, 6, 9, 25): # the fake returns it every read + _tick(brief, mind, home, minutes, claude, gh, {"t1": "working"}) + c = orch.read_counters(slot) + assert len(c["commands"]) == 1 and c["paused"]["by"] == LOGIN + body = gh.status()[0]["body"] + assert body.count("`/pause` by example-human") == 1 + assert "paused: no new workers or close-outs until /resume" in body + gh.add(LOGIN, "/pause", 26) # a second comment is a second command + r = _tick(brief, mind, home, 28, claude, gh, {"t1": "working"}) + assert r["commands"][0]["ack"] == "already paused" + + +def test_steering_is_off_without_a_login_and_reads_nothing(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + monkeypatch.delenv(orch.MENTION_ENV) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + assert gh.calls == ["create"] and "Steering is off" in gh.status()[0]["body"] + + +# --- batch watch and the dashboard ---------------------------------------------- + +def test_batch_watch_shows_the_steering(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + gh.add(LOGIN, "/pause", 1) + _tick(brief, mind, home, 3, claude, gh, {"t1": "working"}) + text = _watch.render(_watch.snapshot(brief, slot, _at(4), agents=d._agents({"t1": "working"}, slot), + health=lambda u: "RUNNING")) + assert "PAUSED by example-human — /resume to continue" in text + assert "Commands\n- `/pause` by example-human" in text + assert f"Status comment: {gh.status()[0]['html_url']}" in text + + +def test_record_key_upserts_the_live_line_and_the_box_shows_it(): + rec = "# Batch x\n- dispatched: a\n- review-at: b\n- issue: c\n- brief:\n - tasks:\n\n## Digest\n- live: no\n" + once = _mind_writer.record_key(rec, "live", "LIVE · 1 running") + assert once.splitlines()[4] == "- live: LIVE · 1 running" + twice = _mind_writer.record_key(once, "live", "LIVE · 1 finished") + assert twice.count("- live:") == 2 and "- live: LIVE · 1 finished" in twice # the digest's untouched + assert twice.endswith("## Digest\n- live: no\n") + assert _brief.parse(twice)["top"]["live"]["value"] == "LIVE · 1 finished" + lm = SimpleNamespace(is_ledger_path=lambda p: True) # Mind's own rule is tested there + assert _mind_writer.validate_op({"op": "record-key", "path": "batches/x.md", "key": "live", + "value": "v"}, lm) == [] + assert _mind_writer.validate_op({"op": "record-key", "path": "active.md", "key": "live", + "value": "v"}, lm) + assert _mind_writer.validate_op({"op": "record-key", "path": "batches/x.md", "key": "live", + "value": "two\nlines"}, lm) + keys = _status.read_record(twice)["keys"] + st = _status.dev_status("x", keys, [], False, "") + assert st["live"] == "LIVE · 1 finished" + assert "> Live: LIVE · 1 finished" in _status.render_md(st) + url = "https://github.com/o/r/issues/1#issuecomment-2" + html = _status.render_html({**st, "live": f"LIVE — status: {url}"}) + assert f'' in html + + +def test_the_live_line_is_rewritten_only_when_the_shift_changes(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + queued = [] + monkeypatch.setattr(orch, "_record_rel", lambda b, m: "batches/shift.md") + + def commit(slot, mind, msg): + for f in _mind_writer.pending_ops(slot): + queued.append(json.loads(f.read_text())) + f.unlink() + return {"committed": "abc", "ops": 1} + monkeypatch.setattr(_mind_writer, "commit_ledger", commit) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + _tick(brief, mind, home, 3, claude, gh, {"t1": "working"}) + _tick(brief, mind, home, 20, claude, gh, {"t1": "working"}) # tokens / clock only + lines = [op["value"] for op in queued if op["op"] == "record-key"] + assert len(lines) == 1 and queued[0]["path"] == "batches/shift.md" + assert lines[0].startswith("LIVE · 1 running · tokens 0 of 100000") + assert lines[0].endswith("— status: " + gh.status()[0]["html_url"]) + (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n") + _tick(brief, mind, home, 23, claude, gh, {"t1": "done"}) + lines = [op["value"] for op in queued if op["op"] == "record-key"] + assert len(lines) == 2 and lines[-1].startswith("LIVE · 1 finished") From dcee25be98f3f4ca1e39aea77d02bbfc95324a78 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 13 Nov 2026 16:15:27 +0000 Subject: [PATCH 2/2] =?UTF-8?q?fix(batch):=20#622=20review=20=E2=80=94=20/?= =?UTF-8?q?drop=20stops=20a=20running=20close-out,=20/stop=20commits=20not?= =?UTF-8?q?hing,=20adoption=20by=20the=20poster?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /drop writes leases/.dropped; closeout_template.md checks it just before merging and refuses. A merge that lands anyway is recorded as "merged outside the close-out after /drop": never counted, no stage-2 row. The ack says a running close-out may still merge the PR. - /drop takes only a task of this shift (picks, leases, outcomes, the brief's named tasks, the plan's members), else "no such task in this shift". - The /stop tick skips the live line and every Mind commit; its one status edit is the ack, so /stop has exactly the STOP file's effect. - /pause wording aligned: holds spawns, re-dispatches and new close-outs; reaps and mentions continue (PAUSE_ACK, AUTONOMY, AGENTS, reference). - The comments read runs for adoption even with no login set, and adopts only a comment written by the posting identity (gh api user, once a shift). - Tests: FakeGitHub honours `since`; an edited enacted command never re-triggers; drop typo; drop vs running close-out; /stop commits nothing; adoption without a login, and never from another author. Co-Authored-By: Claude Opus 5.5 --- AUTONOMY.md | 23 ++- agents/conductors/batch/AGENTS.md | 14 +- agents/conductors/batch/_orchestrator.py | 113 ++++++++++---- agents/conductors/batch/closeout_template.md | 8 +- skills/batch/reference.md | 2 + tests/test_orchestrator_steering.py | 153 +++++++++++++++++-- 6 files changed, 260 insertions(+), 53 deletions(-) diff --git a/AUTONOMY.md b/AUTONOMY.md index f414f324..b65db77b 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -904,17 +904,24 @@ gains, and only: exclusively before the create, as above. A create `gh` said failed is made again next tick. A create that timed out, or a claim whose tick died, is never made again: the comments read adopts it by its hidden tag if it - landed. A failed edit is retried next tick, and the tick carries on; + landed, and only one written by the posting identity (`gh api user`, once + per shift) — that read runs for adoption even when no login is set. A + failed edit is retried next tick, and the tick carries on; - **one read a tick of that issue's comments** (`gh api repos///issues//comments`, one page, under the posting token), for the steering commands; -- **the command set**, enacted from that read: `/pause` (no new workers or - close-outs until `/resume`; workers already out keep running and are - reaped), `/resume`, `/drop ` (a pick not yet spawned is never - picked; a running worker is not killed by the watcher: it is shown - "dropped, still running", never re-dispatched and its PR never merged - unattended, and stopping it stays the human's act, by hand) and `/stop` - (writes the `STOP` kill-switch file, with exactly its effect). A command +- **the command set**, enacted from that read: `/pause` (spawns, + re-dispatches and new close-outs are held until `/resume`; reaps and + mentions continue), `/resume`, `/drop ` (a task of this shift only, + else "no such task in this shift"; a pick not yet spawned is never picked; + a running worker is not killed by the watcher: it is shown "dropped, still + running", never re-dispatched and its PR never merged unattended, and + stopping it stays the human's act, by hand; a close-out already running is + told to refuse by a `.dropped` marker it checks just before merging, + and a merge that lands anyway is recorded as merged outside the close-out, + never counted and with no stage-2 row) and `/stop` (writes the `STOP` + kill-switch file, with exactly its effect: that tick commits nothing to + Mind, and its one status edit is the acknowledgement). A command counts only when it is the first line of a comment by the login in `PYAUTO_SHIFT_MENTION` or `config/policy.yaml` `shift_watcher: mention_login:`, made after the brief's `dispatched:`. The status comment diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 92d3b374..9944242b 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -395,11 +395,15 @@ edited, at most once a tick, when the state changes or every 10 minutes comments read adopts it by its hidden tag. A failed edit is retried next tick. After the reap, one `gh api …/comments` read takes the human's commands, each the first line of a comment by `mention_login`, made after `dispatched:`: -`/pause` (no new spawns, proposals or close-outs; workers out run on and are -reaped), `/resume`, `/drop ` (`counters.json` `dropped`; never picked, -never re-dispatched, its PR refused for close-out; a live worker is shown -`dropped, still running` and stopping it is the human's, `claude stop `) -and `/stop` (writes `STOP`). Each comment acts once, by id, and is acknowledged +`/pause` (spawns, re-dispatches, shadow proposals and new close-outs are held +until `/resume`; reaps and mentions continue), `/resume`, `/drop ` (a +task of this shift only, else "no such task in this shift"; `counters.json` +`dropped` plus a `leases/.dropped` marker; never picked, never +re-dispatched, its PR refused for close-out; a close-out already running checks +the marker just before merging and refuses, and a merge that lands anyway is +recorded as merged outside the close-out, with no stage-2 row; a live worker is +shown `dropped, still running` and stopping it is the human's, `claude stop +`) and `/stop` (writes `STOP`; that tick commits nothing to Mind). 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/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 20706af2..1431c138 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -913,7 +913,8 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, out = _tick_body(slot, brief, mind, now, spawner, grace_s, records, agents, tokens, health, pr_state, poster=poster, shift=shift, token_reserve=token_reserve, whoami=whoami, github=github) - status = _live_status(slot, mind, shift, now, agents, health.cached, github) + status = _live_status(slot, mind, shift, now, agents, health.cached, github, + stopped=out.get("action") == "stopped") if status: out["status"] = status return out @@ -925,9 +926,27 @@ def _tick_body(slot, brief, mind, now, spawner, grace_s, records, agents, counters = read_counters(slot) counters["usage_unavailable"] = [] # this tick's reads decide reaped = _reap(slot, counters, now, grace_s, agents, tokens) + import _batch # noqa: E402 — deferred: _batch imports this module's sibling + planned = {} + + def plan() -> dict: + """The plan inside the brief, made once a tick when first needed.""" + if "d" not in planned: + recs = records if records is not None else _batch.survey(mind) + # Unattended by construction: an absent Lane is excluded and an + # empty queue.md stops the backlog dip (M2.3, AUTONOMY.md "M2 + # rulings — 2026-11-12"). Recorded each tick so the digest can say so. + planned["d"] = _batch.plan(recs, session_lane="local-dev", brief=brief, + queue=_batch.read_queue(mind)) + return planned["d"] + + 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 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. - commands = _steer(slot, counters, shift or {}, now, github) + commands = _steer(slot, counters, shift or {}, now, github, whoami, known) _write_counters(slot, counters) if (slot / STOP_FILE).exists(): # A /stop this tick: from here on it is the STOP file's tick. @@ -956,14 +975,7 @@ def _tick_body(slot, brief, mind, now, spawner, grace_s, records, agents, max_workers = _brief.cap_of(brief, "max-workers") max_sessions = _brief.cap_of(brief, "max-sessions") - import _batch # noqa: E402 — deferred: _batch imports this module's sibling - if records is None: - records = _batch.survey(mind) - # Unattended by construction: an absent Lane is excluded and an empty - # queue.md stops the backlog dip (M2.3, AUTONOMY.md "M2 rulings — - # 2026-11-12"). Recorded each tick so the digest can say so. - d = _batch.plan(records, session_lane="local-dev", brief=brief, - queue=_batch.read_queue(mind)) + d = plan() counters["backlog_gates"] = {"lane_absent": sorted(d["lane_absent"]), "queue_stop": d["queue_stop"]} paused = bool(counters.get("paused")) @@ -1282,6 +1294,7 @@ def _mentions(slot: Path, counters: dict, shift: dict, poster, now: _dt.datetime # Once per shift: who the comments post as. The human's own login # gets no notification for its own comment (#611 review). counters["poster_login"] = (whoami or gh_login)() or "" + if login: counters["mention_login"] = login for task, state, reason, w, key, name in todo: marker = d / f"{name}.json" @@ -1320,6 +1333,12 @@ def _mentions(slot: Path, counters: dict, shift: dict, poster, now: _dt.datetime COMMANDS = ("pause", "resume", "drop", "stop") _COMMAND_RE = re.compile(r"^/(pause|resume|drop|stop)\b[ \t]*(\S+)?[ \t]*$") _TASK_ARG_RE = re.compile(r"^[A-Za-z0-9_./-]+$") +#: `/.dropped`: a dropped task's close-out session checks it +#: just before it merges, and refuses (closeout_template.md). +DROPPED_SUFFIX = ".dropped" +#: The `/pause` acknowledgement — the one wording AUTONOMY.md and the docs use. +PAUSE_ACK = ("paused: spawns, re-dispatches and new close-outs are held until /resume; " + "reaps and mentions continue") _ISSUE_API_RE = re.compile(r"^https://github\.com/([^/\s]+)/([^/\s]+)/issues/(\d+)$") _COMMENT_API_RE = re.compile( r"^https://github\.com/([^/\s]+)/([^/\s]+)/(?:issues|pull)/\d+#issuecomment-(\d+)$") @@ -1402,13 +1421,15 @@ def _parse_command(body: str) -> tuple[str, str] | None: def _apply_command(slot: Path, counters: dict, cmd: str, arg: str, who: str, - at: str) -> str: - """Enact one command; returns its acknowledgement.""" + at: str, known=None) -> str: + """Enact one command; returns its acknowledgement. `known(task)` says + whether a task belongs to this shift (a pick, a lease, a brief or plan + member).""" if cmd == "pause": if counters.get("paused"): return "already paused" counters["paused"] = {"by": who, "at": at} - return "paused: no new workers or close-outs until /resume; workers out keep running" + return PAUSE_ACK if cmd == "resume": if not counters.get("paused"): return "not paused: nothing to resume" @@ -1422,19 +1443,34 @@ def _apply_command(slot: Path, counters: dict, cmd: str, arg: str, who: str, if not arg or not _TASK_ARG_RE.match(arg): return "ignored: /drop needs a task name" task = Path(arg).stem + held = leases(slot) + if not (task in held or task in counters["picks"] or task in counters["outcomes"] + or (known is not None and known(task))): + return f"ignored: no such task in this shift (`{task}`)" counters["dropped"][task] = {"by": who, "at": at} - lease = leases(slot).get(task) + (slot / "leases").mkdir(parents=True, exist_ok=True) + (slot / "leases" / f"{task}{DROPPED_SUFFIX}").write_text(f"/drop by {who} at {at}\n", + encoding="utf-8") + running = [pr for pr, co in counters["closeouts"].items() + if co.get("task") == task and co.get("state") == "running"] + tail = "".join(f"; a close-out already running may still merge PR {pr} (it is told " + "to refuse by a `.dropped` marker it checks before merging; a merge " + "that lands anyway is recorded as merged outside the close-out)" + for pr in running) + lease = held.get(task) if lease is not None: key = _worker_key(lease, task) return (f"dropped `{task}`: its worker {key} is still running; it is never " "re-dispatched and its PR never merged unattended. Stopping it is " - f"yours, by hand on the laptop (`claude stop {key}`)") + f"yours, by hand on the laptop (`claude stop {key}`)" + tail) if task in counters["outcomes"] or task in counters["done"]: - return f"dropped `{task}`: it had already finished; its PR is never merged unattended" - return f"dropped `{task}`: it will not be picked this shift" + return (f"dropped `{task}`: it had already finished; its PR is never merged " + "unattended" + tail) + return f"dropped `{task}`: it will not be picked this shift" + tail -def _steer(slot: Path, counters: dict, shift: dict, now: _dt.datetime, github=None) -> list[dict]: +def _steer(slot: Path, counters: dict, shift: dict, now: _dt.datetime, github=None, + whoami=None, known=None) -> list[dict]: """Read the shift issue's comments once and enact each new steering command from the human's login (`mention_login`), in order, once. @@ -1443,10 +1479,17 @@ def _steer(slot: Path, counters: dict, shift: dict, now: _dt.datetime, github=No skipped by id; no other comment it writes opens with a command), nor by a comment older than the shift's `dispatched:` (an issue reused across shifts). Each comment is acted on once, by id; its acknowledgement is a - line in the status comment, so a command costs no extra GitHub write.""" + line in the status comment, so a command costs no extra GitHub write. + + The same read adopts a status comment whose create may have landed — even + with no login set, when it is the only reason to read — and only one + written by the posting identity (`gh api user`, once per shift).""" issue = shift.get("issue", "") login = mention_login() - if not issue.startswith("http") or not login: + marker = slot / STATUS_MARKER + rec = _read_json(marker) + adopting = bool(rec) and rec.get("state") in ("claimed", "unknown") + if not issue.startswith("http") or not (login or adopting): return [] start = _brief._iso(shift.get("dispatched") or "") since = counters.get("commands_since") or (_iso(start) if start else "") @@ -1455,22 +1498,24 @@ def _steer(slot: Path, counters: dict, shift: dict, now: _dt.datetime, github=No counters["commands_unread"] = _iso(now) return [] counters.pop("commands_unread", None) - marker = slot / STATUS_MARKER - rec = _read_json(marker) + if adopting and "poster_login" not in counters: + counters["poster_login"] = (whoami or gh_login)() or "" + poster = counters.get("poster_login") or "" seen = set(counters.get("commands_seen") or []) out = [] for c in sorted(comments, key=lambda c: (c["created_at"], c["id"])): if c["created_at"] > (counters.get("commands_since") or ""): counters["commands_since"] = c["created_at"] if c["body"].lstrip().startswith(STATUS_TAG_PREFIX): - if rec and rec.get("state") in ("claimed", "unknown") \ + if rec and rec.get("state") in ("claimed", "unknown") and poster \ + and c["login"].lower() == poster.lower() \ and f" {rec.get('nonce')} -->" in c["body"].split("\n", 1)[0] and c["url"]: # A create that timed out (or a tick that died after its # claim) did land: adopt it, and edit it from now on. rec.update(state="posted", url=c["url"], due=True, adopted_at=_iso(now)) marker.write_text(json.dumps(rec, sort_keys=True)) continue - if c["id"] in seen or (rec and c["url"] and c["url"] == rec.get("url")): + if not login or c["id"] in seen or (rec and c["url"] and c["url"] == rec.get("url")): continue if c["login"].lower() != login.lower(): continue @@ -1485,7 +1530,7 @@ def _steer(slot: Path, counters: dict, shift: dict, now: _dt.datetime, github=No continue cmd, arg = parsed seen.add(c["id"]) - ack = _apply_command(slot, counters, cmd, arg, c["login"], c["created_at"]) + ack = _apply_command(slot, counters, cmd, arg, c["login"], c["created_at"], known) counters["commands"].append({"id": c["id"], "command": "/" + cmd + (f" {arg}" if arg else ""), "by": c["login"], "at": c["created_at"], "url": c["url"], "ack": ack}) @@ -1562,10 +1607,12 @@ def _post_status(slot: Path, issue: str, text: str, key: str, now: _dt.datetime, def _live_status(slot: Path, mind: Path, shift: dict, now: _dt.datetime, agents, - health, github=None) -> dict | None: + health, github=None, *, stopped: bool = False) -> dict | None: """The end of every open tick: the status comment (create once, then edit) and the dashboard's `- live:` line. Built from the same snapshot as - `batch watch`, from what this tick already read — no read of its own.""" + `batch watch`, from what this tick already read — no read of its own. + On the `/stop` tick only the status write runs, as the acknowledgement: + nothing is queued or committed to Mind, exactly as under `STOP`.""" brief_path = shift.get("brief_path") if brief_path is None: return None @@ -1577,6 +1624,8 @@ def _live_status(slot: Path, mind: Path, shift: dict, now: _dt.datetime, agents, snap["commands_on"] = bool(mention_login()) out = _post_status(slot, issue, _watch.render_status(snap), _watch.status_key(snap), now, github) + if stopped: + return out or None snap["status_url"] = status_url(slot) line, key = _watch.live_line(snap) rel = _record_rel(Path(brief_path), mind) @@ -1894,7 +1943,15 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti co["why"] = "close-out said merged; GitHub still OPEN — re-checked each tick" _write_counters(slot, counters) continue # e.g. `--auto` pending: not counted, the cap slot stays held - if merged and verdict is not None and not said_merged: + if merged and co["task"] in counters["dropped"]: + # Dropped by the human (#622): a merge that landed anyway is never + # an unattended merge — no count, no stage-2 row. + co.update(state="refused", + why="merged outside the close-out after /drop " + f"(mergedBy={(gh or {}).get('mergedBy') or '?'})") + events.setdefault("merged_outside", []).append(pr) + events["refused"].append(pr) + elif merged and verdict is not None and not said_merged: # The close-out refused, yet the PR is merged: someone else merged # it. Never an unattended merge — no count, no stage-2 row. co.update(state="refused", diff --git a/agents/conductors/batch/closeout_template.md b/agents/conductors/batch/closeout_template.md index 6aff0007..71ebe52e 100644 --- a/agents/conductors/batch/closeout_template.md +++ b/agents/conductors/batch/closeout_template.md @@ -28,13 +28,17 @@ outcome — the human merges by `/prm` at check-in. refuse unless the head has **at least one completed check and every check green** (`gh pr checks {pr_url} --json name,bucket`: none, or only `skipping`, refuses — PyAutoHeart#343). -4. If everything passed, use the prm skill on {pr_url}: the full close-out, +4. 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`. +5. If everything passed, use the prm skill on {pr_url}: the full close-out, judged exactly as a human-typed `/prm`. Never commit to PyAutoMind yourself — a hook refuses it; queue each Mind change with `{shift_ledger} append|write|move|remove|drop-section ...` (ops land in {ledger_dir}/) and the orchestrator commits them. Do **not** append the Shadow-window row: the watcher writes the stage-2 row from your verdict. -5. End at your deliverable. Never arm anything that outlives your turn. +6. End at your deliverable. Never arm anything that outlives your turn. Last, write {lease_dir}/{task}.closeout as one JSON object: diff --git a/skills/batch/reference.md b/skills/batch/reference.md index 4bbd118e..5558206c 100644 --- a/skills/batch/reference.md +++ b/skills/batch/reference.md @@ -129,5 +129,7 @@ does not volunteer it. `/pause`, `/resume`, `/drop `, `/stop`, from their own login (the watcher ignores every other account and its own comments). Each command is acknowledged once, in the status comment's `Commands` list, on the next tick. + `/pause` holds spawns, re-dispatches and new close-outs; reaps and mentions + continue. A dropped worker that is already running is not killed: stopping it is the human's, `claude stop ` on the laptop. Never post a command for them. diff --git a/tests/test_orchestrator_steering.py b/tests/test_orchestrator_steering.py index 734239cb..99aaacdd 100644 --- a/tests/test_orchestrator_steering.py +++ b/tests/test_orchestrator_steering.py @@ -10,7 +10,9 @@ import datetime as _dt import json +import subprocess import sys +from urllib.parse import parse_qs, urlparse from pathlib import Path from types import SimpleNamespace @@ -34,16 +36,20 @@ def _at(minutes: float) -> _dt.datetime: class FakeGitHub: """The issue's comments, behind `gh issue comment`, `gh api PATCH` and - `gh api …/comments`. Records each call's kind; fails the next `fail[kind]`.""" + `gh api …/comments` — whose `since` it honours, by `updated_at`, as GitHub + does. Records each call's kind; fails the next `fail[kind]`; a create + with `timeout` set times out (after landing, if `timeout == "landed"`).""" def __init__(self): self.comments, self.calls = [], [] self.fail = {"create": 0, "edit": 0, "read": 0} + self.timeout = None + self.now = NOW self._id = 100 - def add(self, login: str, body: str, minutes: float) -> str: + def add(self, login: str, body: str, minutes: float | None = None) -> str: self._id += 1 - stamp = orch._iso(_at(minutes)) + stamp = orch._iso(_at(minutes) if minutes is not None else self.now) self.comments.append({"id": self._id, "user": {"login": login}, "body": body, "created_at": stamp, "updated_at": stamp, "html_url": f"{ISSUE}#issuecomment-{self._id}"}) @@ -64,13 +70,23 @@ def __call__(self, argv, **kw): return SimpleNamespace(returncode=1, stdout="", stderr="HTTP 502") if kind == "create": body = Path(argv[argv.index("--body-file") + 1]).read_text() - return SimpleNamespace(returncode=0, stdout=self.add(BOT, body, 0) + "\n", stderr="") + if self.timeout: + if self.timeout == "landed": + self.add(BOT, body) + raise subprocess.TimeoutExpired(argv, 120) + return SimpleNamespace(returncode=0, stdout=self.add(BOT, body) + "\n", stderr="") if kind == "edit": cid = int(argv[4].rsplit("/", 1)[1]) body = json.loads(Path(argv[argv.index("--input") + 1]).read_text())["body"] - next(c for c in self.comments if c["id"] == cid)["body"] = body + self.edit(cid, body) return SimpleNamespace(returncode=0, stdout="", stderr="") - return SimpleNamespace(returncode=0, stdout=json.dumps(self.comments), stderr="") + since = (parse_qs(urlparse(argv[2]).query).get("since") or [""])[0] + return SimpleNamespace(returncode=0, stdout=json.dumps( + [c for c in self.comments if c["updated_at"] >= since]), stderr="") + + def edit(self, cid: int, body: str) -> None: + c = next(c for c in self.comments if c["id"] == cid) + c.update(body=body, updated_at=orch._iso(self.now)) def status(self) -> list[dict]: return [c for c in self.comments if c["body"].startswith(orch.STATUS_TAG_PREFIX)] @@ -84,13 +100,17 @@ def _shift(tmp_path, monkeypatch, names=("t1",), extra=""): return mind, brief, home, orch.slot_dir(brief, home) -def _tick(brief, mind, home, minutes, claude, gh, states=None): +def _tick(brief, mind, home, minutes, claude, gh, states=None, *, agents=None, + health="RUNNING", pr_state=None): slot = orch.slot_dir(brief, home) - agents = d._agents(states, slot) if states else orch.AgentsView([]) + if agents is None: + agents = d._agents(states, slot) if states else orch.AgentsView([]) before = len(gh.calls) + gh.now = _at(minutes) r = orch.tick(brief, mind, home=home, now=_at(minutes), grace_s=0, spawner=orch.RealSpawner(brief, "auto", run=claude), agents=agents, - tokens=lambda s: 0, health=lambda u: "RUNNING", github=gh, + tokens=lambda s: 0, health=lambda u: health, github=gh, + pr_state=pr_state, whoami=lambda: BOT, poster=lambda i, b: {"posted": False, "retry": False, "error": "digest"}) this = gh.calls[before:] # The bound (#622): one comments read and one status write a tick, at most. @@ -284,7 +304,7 @@ def test_a_command_is_enacted_and_acknowledged_once(tmp_path, monkeypatch): assert len(c["commands"]) == 1 and c["paused"]["by"] == LOGIN body = gh.status()[0]["body"] assert body.count("`/pause` by example-human") == 1 - assert "paused: no new workers or close-outs until /resume" in body + assert orch.PAUSE_ACK in body and "reaps and mentions continue" in body gh.add(LOGIN, "/pause", 26) # a second comment is a second command r = _tick(brief, mind, home, 28, claude, gh, {"t1": "working"}) assert r["commands"][0]["ack"] == "already paused" @@ -360,3 +380,116 @@ def commit(slot, mind, msg): _tick(brief, mind, home, 23, claude, gh, {"t1": "done"}) lines = [op["value"] for op in queued if op["op"] == "record-key"] assert len(lines) == 2 and lines[-1].startswith("LIVE · 1 finished") + + +# --- the #622 review -------------------------------------------------------------- + +def test_editing_an_enacted_command_never_re_triggers_it(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + gh.add(LOGIN, "/pause", 1) + _tick(brief, mind, home, 3, claude, gh, {"t1": "working"}) + pause = next(c for c in gh.comments if c["body"] == "/pause") + gh.now = _at(4) + gh.edit(pause["id"], "/stop") # bumps updated_at: read again + r = _tick(brief, mind, home, 6, claude, gh, {"t1": "working"}) + assert "commands" not in r and not (slot / orch.STOP_FILE).exists() + assert [c["command"] for c in orch.read_counters(slot)["commands"]] == ["/pause"] + + +def test_drop_of_a_task_not_in_the_shift_is_refused(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + gh.add(LOGIN, "/drop t11", 1) + r = _tick(brief, mind, home, 3, claude, gh, {"t1": "working"}) + assert r["commands"][0]["ack"] == "ignored: no such task in this shift (`t11`)" + assert orch.read_counters(slot)["dropped"] == {} + assert not (slot / "leases" / "t11.dropped").exists() + + +def test_drop_tells_a_running_closeout_to_refuse_and_a_merge_anyway_is_outside( + tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + brief.write_text(brief.read_text().replace("merge-cap: 0", "merge-cap: 2")) + claude, gh = d.FakeClaude(), FakeGitHub() + pr = "https://github.com/o/r/pull/9" + _tick(brief, mind, home, 0, claude, gh) + (slot / "leases" / "t1.done").write_text(pr + "\n") + _tick(brief, mind, home, 3, claude, gh, {"t1": "done"}, health="HEALTHY") + co = orch.read_counters(slot)["closeouts"][pr] + assert co["state"] == "running" + working = orch.AgentsView([{"id": co["agent_id"], "state": "working"}]) + gh.add(LOGIN, "/drop t1", 4) + r = _tick(brief, mind, home, 6, claude, gh, agents=working, health="HEALTHY") + ack = r["commands"][0]["ack"] + assert f"a close-out already running may still merge PR {pr}" in ack + assert (slot / "leases" / "t1.dropped").exists() # what the close-out checks + template = orch.closeout_prompt("t1", pr, "x.md", brief, slot / "leases") + assert f"{slot / 'leases'}/t1.dropped" in template and "dropped by /drop" in template + # It merged anyway (it was past its check): never an unattended merge. + (slot / "leases" / "t1.closeout").write_text(json.dumps( + {"result": "merged", "pr": pr, "gate": "g", "model": "m"})) + r = _tick(brief, mind, home, 9, claude, gh, agents=working, health="HEALTHY", + pr_state=lambda u: {"state": "MERGED", "mergedAt": "", "mergedBy": BOT}) + c = orch.read_counters(slot) + assert c["closeouts"][pr]["state"] == "refused" + assert c["closeouts"][pr]["why"].startswith("merged outside the close-out after /drop") + assert c["glance_auto_merges"] == 0 + assert not any(json.loads(f.read_text())["op"] == "table-append" + for f in _mind_writer.pending_ops(slot)) # no stage-2 row + + +def test_stop_commits_nothing_to_mind_on_its_tick(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + commits = [] + monkeypatch.setattr(orch, "_record_rel", lambda b, m: "batches/shift.md") + monkeypatch.setattr(_mind_writer, "commit_ledger", + lambda slot, mind, msg: commits.append(msg) or {"committed": None}) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, + {"op": "append", "path": "active.md", "text": "x"}) # a worker's + gh.add(LOGIN, "/stop", 1) + before = list(commits) + r = _tick(brief, mind, home, 3, claude, gh, {"t1": "working"}) + assert r["action"] == "stopped" and commits == before + assert gh.calls[-1] == "edit" and "STOP present" in gh.status()[0]["body"] + assert _mind_writer.pending_ops(slot) # left exactly as STOP leaves it + + +def test_a_timed_out_create_is_adopted_without_a_login_and_only_from_the_poster( + tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + monkeypatch.delenv(orch.MENTION_ENV) + claude, gh = d.FakeClaude(), FakeGitHub() + gh.timeout = True # timed out, did not land + _tick(brief, mind, home, 0, claude, gh) + nonce = json.loads((slot / orch.STATUS_MARKER).read_text())["nonce"] + gh.timeout = None + forged = orch.STATUS_TAG.format(slot=slot.name, nonce=nonce) + "\nnot ours" + gh.add("someone-else", forged, 1) + _tick(brief, mind, home, 3, claude, gh, {"t1": "working"}) + rec = json.loads((slot / orch.STATUS_MARKER).read_text()) + assert rec["state"] == "unknown" and gh.calls.count("create") == 1 + assert gh.calls[-1] == "read" # read for adoption, no login set + url = gh.add(BOT, orch.STATUS_TAG.format(slot=slot.name, nonce=nonce) + "\nours", 4) + r = _tick(brief, mind, home, 6, claude, gh, {"t1": "working"}) + rec = json.loads((slot / orch.STATUS_MARKER).read_text()) + assert rec["state"] == "posted" and rec["url"] == url and r["status"]["status"] == "edited" + assert gh.calls.count("create") == 1 + assert next(c for c in gh.comments if c["html_url"] == url)["body"] != "ours" + + +def test_a_create_that_timed_out_after_landing_is_adopted_not_reposted(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + gh.timeout = "landed" + _tick(brief, mind, home, 0, claude, gh) + gh.timeout = None + assert json.loads((slot / orch.STATUS_MARKER).read_text())["state"] == "unknown" + _tick(brief, mind, home, 3, claude, gh, {"t1": "working"}) + _tick(brief, mind, home, 6, claude, gh, {"t1": "working"}) + assert gh.calls.count("create") == 1 and len(gh.status()) == 1 + assert json.loads((slot / orch.STATUS_MARKER).read_text())["state"] == "posted"