From a6df39ef9cac5aa8969b47fee51d861a3c559b59 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 16 Nov 2026 13:55:04 +0000 Subject: [PATCH 1/3] feat(batch): shift event stream, batch watch --stream, /add /cap /kill (#644) M3.4 Build A, the shift cockpit's engine. - _events.py: record_tick appends one JSON line per new event to the slot's events.jsonl, inside the tick lock, from the tick's result and counters (no subprocess, no network). Keys dedup in the file itself, so a crash never repeats an event or reuses a seq; one cap line per shift-wide class. - _orchestrator: record events in the open tick, finish_shift and late_sweep; out["health"] for ci lines; shift-end when nothing is left for the late sweep; needs-you event comments, at most 5 + 1 a shift, no @ (H4b). - Steering verbs: /cap (never above the brief's own value, H6), /add (refused within 30 min of review-at; overrides exclude: and the parked hold, never the organ rule, H8; one Mind fetch per /add), /kill (local claude stop; the reap marks the exit killed, re-dispatched once unless dropped, H5). _brief.effective applies caps and added tasks per tick. - batch watch --stream [--from --for --json --check]: prints the stream, exits 0 at shift-end, STOP or the window's end, 3 at a segment end. - _batch.grade_text; _digest cap-override line, killed exit word, #641 and close-out refusal classes. - Tests: events, stream, steering (one per verb and ack, all failing on main), and a replay of shift B's real tick.log (2026-11-14-pm3). Co-Authored-By: Claude Opus 5.5 --- agents/conductors/batch/_batch.py | 60 ++- agents/conductors/batch/_brief.py | 39 +- agents/conductors/batch/_digest.py | 31 +- agents/conductors/batch/_events.py | 463 ++++++++++++++++++ agents/conductors/batch/_orchestrator.py | 436 ++++++++++++++++- agents/conductors/batch/_watch.py | 202 +++++++- .../shift_2026-11-14-pm3/counters.json | 116 +++++ tests/fixtures/shift_2026-11-14-pm3/tick.log | 23 + tests/test_batch_watch_stream.py | 284 +++++++++++ tests/test_orchestrator_dispatch.py | 3 +- tests/test_orchestrator_events.py | 401 +++++++++++++++ tests/test_orchestrator_mentions.py | 8 + tests/test_orchestrator_steering.py | 360 ++++++++++++++ 13 files changed, 2390 insertions(+), 36 deletions(-) create mode 100644 agents/conductors/batch/_events.py create mode 100644 tests/fixtures/shift_2026-11-14-pm3/counters.json create mode 100644 tests/fixtures/shift_2026-11-14-pm3/tick.log create mode 100644 tests/test_batch_watch_stream.py create mode 100644 tests/test_orchestrator_events.py diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 945f10f6..3cef57c5 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -131,9 +131,11 @@ def declared_repos(p: dict) -> list[str]: return sorted(out) or list(p.get("repos") or []) -def grade(path: Path, mind: Path) -> dict: - """Everything the planner needs about one prompt, from the faculty.""" - p = parse_prompt(path, mind) +def grade(path: Path, mind: Path, text: str | None = None) -> dict: + """Everything the planner needs about one prompt, from the faculty. + `text`, when given, is the prompt's content (`grade_text`): nothing else + is read by path.""" + p = parse_prompt(path, mind, text=text) level, score, factors, derived = effective_difficulty(p) tier, why, _ = effective_consequence(p, factors) ready, ready_why, _ = effective_unattended(p, level, factors, derived) @@ -232,6 +234,21 @@ def survey(mind: Path) -> list[dict]: return out +def grade_text(text: str, rel: str, mind: Path) -> dict: + """One `survey` record from a prompt's text as Mind origin/main holds it + (`/add`, PyAutoBrain#644): the canonical working tree nobody pulls + mid-shift may not have it yet. `rel` is its Mind-relative path.""" + g = grade(Path(mind) / rel, Path(mind), text=text) + g["path"] = rel + g["looks_shipped"] = rel in _shipped.flagged_paths(mind) + g["epic"] = _epic_of(text) + g["phase"] = _phase_of(text) + g["done"] = _is_done(text) + g["themes"] = _themes_of(text) + g["title"] = _title_of(text) + return g + + def _title_of(text: str) -> str: """The prompt's first `# ` heading — what a human reads the pick by.""" for line in text.splitlines(): @@ -2931,9 +2948,10 @@ def main(argv=None) -> int: "both fail closed; AUTONOMY.md M2 rulings)") ap.add_argument("--json", action="store_true", dest="as_json") # brief / plan - ap.add_argument("--check", default="", metavar="FILE", + ap.add_argument("--check", default="", metavar="FILE", nargs="?", const=True, help="brief: validate this shift brief against " - "PyAutoMind/batches/AGENTS.md") + "PyAutoMind/batches/AGENTS.md; watch --stream: only say " + "whether the stream is attachable now (no FILE)") ap.add_argument("--new", default="", metavar="SLOT", help="brief: print a skeleton shift brief for SLOT (e.g. " "2026-11-14-am) whose goals: come from goals.md; " @@ -2971,6 +2989,14 @@ def main(argv=None) -> int: help="watch: print one snapshot and exit") ap.add_argument("--interval", type=float, default=30.0, help="watch: seconds between refreshes (at least 30)") + ap.add_argument("--stream", action="store_true", + help="watch: print the shift's events, one plain line each, " + "until the shift ends (the cockpit's watch; local reads only)") + ap.add_argument("--from", type=int, default=None, dest="from_seq", metavar="SEQ", + help="watch --stream: print every event after this seq first") + ap.add_argument("--for", type=float, default=None, dest="for_min", metavar="MIN", + help="watch --stream: end this segment after MIN minutes " + "(prints `segment-end next=--from N`, exit 3)") # premise (and the premise leg of `brief --check`) ap.add_argument("--root", type=Path, default=None, help="premise: the workspace root holding the repo checkouts " @@ -3190,12 +3216,29 @@ def _main_digest(mind: Path, a) -> int: def _main_watch(a) -> int: """`batch watch --record [--once] [--interval N]` — a live view of a - running shift; writes nothing anywhere (`_watch`).""" + running shift; writes nothing anywhere (`_watch`). With `--stream`, the + shift's event stream (`_watch.stream`, PyAutoBrain#644).""" + import _watch + if isinstance(a.check, str) and a.check: + print("batch watch: --check takes no file (the record is --record)", file=sys.stderr) + return RC_USAGE + if a.stream or a.check is True: + env = _watch.env_file() + record = Path(a.record or env.get("PYAUTO_SHIFT_BRIEF") or "") + if not str(record) or not record.is_file(): + print(f"batch watch --stream: no brief record ({record or 'none'}; pass --record " + "or set PYAUTO_SHIFT_BRIEF in the orchestrator env file)", file=sys.stderr) + return RC_USAGE + home = a.home or (Path(env["PYAUTO_ORCHESTRATOR_HOME"]) + if env.get("PYAUTO_ORCHESTRATOR_HOME") else None) + import _orchestrator + return _watch.stream(record, _orchestrator.slot_dir(record, home), + from_seq=a.from_seq, for_min=a.for_min, as_json=a.as_json, + check=a.check is True) if not a.record: print("batch watch: --record is required", file=sys.stderr) return RC_USAGE import _orchestrator - import _watch record = Path(a.record) if not record.is_file(): print(f"batch watch: no such brief record {record}", file=sys.stderr) @@ -3327,6 +3370,9 @@ def _main_brief(mind: Path, a) -> int: """`batch brief --check ` — read-only; exit 0 valid, 1 refused. `batch brief --new --review-at ` — print (or `--out`) a skeleton brief whose goals come from goals.md.""" + if a.check is True: + print("batch brief --check: name the brief FILE to check", file=sys.stderr) + return RC_USAGE if a.new: if a.check: print("batch brief: --new and --check are separate runs", file=sys.stderr) diff --git a/agents/conductors/batch/_brief.py b/agents/conductors/batch/_brief.py index ff8c9793..d5f40805 100644 --- a/agents/conductors/batch/_brief.py +++ b/agents/conductors/batch/_brief.py @@ -142,6 +142,39 @@ def cap_of(brief: dict, key: str) -> int: return CAP_DEFAULTS[key] if value is None else value +#: The caps a `/cap` steering command may lower for one shift (#644). +CAP_KEYS = ("merge-cap", "max-workers", "max-sessions", "token-budget") + + +def effective(brief: dict, counters: dict | None) -> dict: + """The brief as this shift now runs it (PyAutoBrain#644): a copy with each + `/cap` override's value (`counters["caps"]`) swapped in, and each task the + human `/add`ed (`counters["added"]`) appended to `tasks:` and taken out of + `exclude:` — the human's newer word, as a brief that names a task again. + The brief file is never changed; with nothing steered it is `brief` itself.""" + caps = (counters or {}).get("caps") or {} + added = (counters or {}).get("added") or {} + if not brief or not (caps or added): + return brief + out = dict(brief) + for key, ov in caps.items(): + if key in CAP_KEYS and isinstance(ov, dict) and "value" in ov: + out[key] = {**(brief.get(key) or {"children": []}), "value": str(ov["value"])} + prompts = [a["prompt"] for a in added.values() if isinstance(a, dict) and a.get("prompt")] + if prompts: + tasks = brief.get("tasks") or {"value": "", "children": []} + have = {Path(c["text"]).name for c in tasks["children"]} + out["tasks"] = {**tasks, "children": list(tasks["children"]) + [ + {"text": p, "children": []} for p in prompts if Path(p).name not in have]} + names = {Path(p).name for p in prompts} + if brief.get("exclude"): + ex = brief["exclude"] + out["exclude"] = {**ex, "children": [c for c in ex["children"] + if Path(c["text"]).name not in names]} + out["added"] = {"value": " ".join(sorted(names)), "children": []} + return out + + def worker_mode_of(brief: dict) -> str: return brief.get("worker-mode", {}).get("value") or DEFAULT_WORKER_MODE @@ -363,13 +396,15 @@ def scope(records: list[dict], brief: dict) -> tuple[list[dict], list[tuple[str, ex_paths, ex_keyed = excluded_of(brief) ex_names = {Path(p).name for p in ex_paths} lanes = set(lanes_of(brief)) or {"any"} + # `/add`ed this shift (`effective`, #644): no `exclude:` rule holds it back. + added = set(_csv(brief.get("added", {}).get("value", ""))) kept, rejected = [], [] for r in records: name = Path(r["path"]).name themes = set(r.get("themes") or []) - if name in ex_names or r.get("epic") in ex_keyed.get("epics", []) \ - or themes & set(ex_keyed.get("tags", [])): + if name not in added and (name in ex_names or r.get("epic") in ex_keyed.get("epics", []) + or themes & set(ex_keyed.get("tags", []))): rejected.append((r["path"], "excluded by the brief")) continue if name not in named_names: diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index e04573c8..26378407 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -224,7 +224,8 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, return STILL_OUT, True if task in counters.get("pending_redispatch", []): if live: - return "crashed — awaiting re-dispatch", True + word = "killed by /kill" if task in (counters.get("killed") or {}) else "crashed" + return f"{word} — awaiting re-dispatch", True return f"{NOT_REDISPATCHED}: {redispatch_why(task, counters)}", False skipped = gate_why(task, counters) return ("not started — skipped: " + skipped if skipped else "not started"), False @@ -446,6 +447,7 @@ def label(task: str, pick: dict | None, url: str = "") -> str: ("blocked on a person", "Needs you — blocked on a person"), ("abandoned", "Abandoned — crashed twice"), (NOT_REDISPATCHED, "Crashed — not re-dispatched"), + ("killed by /kill", "Killed by /kill — waiting to be re-dispatched"), ("crashed", "Crashed — waiting to be re-dispatched"), ("ended", "Crashed"), ("obsolete", "Obsolete — nothing to do"), @@ -563,6 +565,7 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, lines.append(f"{SHADOW_COUNTERS} · review-minutes-planned: {values['review-minutes-planned']}") else: lines += [f"- {k}: {values[k]}" for k in COUNTERS] + lines += cap_lines(counters) lines += ["", WORKERS_HEADING] + (worker_lines(counters, links) or [NO_PICKS]) lines += ["", REFUSALS_HEADING] + (refusal_lines(counters) or [NO_PICKS]) lines += report_lines(slot) @@ -664,7 +667,9 @@ def names(paths): #: `spawned/parked/late/finished`. `launch-failed` stands alone: no session #: started. `ended` is a parked worker that ended without a `.done`. EXIT_WORDS = ("spawned", "finished", "crashed", "parked", "late", "ended", - "launch-failed") + "launch-failed", "killed") +#: `killed` is a worker the human stopped by `/kill` (#644): it is re-dispatched +#: as a crash is, but it is not a crash, so it is not in `CRASH_WORDS`. CRASH_WORDS = ("crashed", "launch-failed") @@ -702,6 +707,14 @@ def worker_lines(counters: dict, links: MindLinks | None = None) -> list[str]: r"\1: committed + \2 reserved per worker would pass it"), (re.compile(r"^token usage unavailable\b"), "token usage unavailable"), (re.compile(r"^spawn failed\b"), "spawn failed"), + # Close-out refusals, so the event stream's `cls` is stable (#644). The + # public-name check's wording is #641's (`bin/public_names.py` `reason`). + (re.compile(r"^public name added/renamed\b"), "public name added or renamed: a human /prm"), + (re.compile(r"^public-name check could not tell\b"), + "public-name check could not tell: a human /prm"), + (re.compile(r"^PR carries the decision-taken label\b"), "decision-taken label"), + (re.compile(r"^token spend \d+ \(committed\) reached (\S+× token-budget \d+)"), + r"token spend reached \1"), ) #: Refusals whose reason is the shift's, not the task's — summarised in one #: line for every task they held back (#632, F3 and review). @@ -780,6 +793,20 @@ def refusal_lines(counters: dict) -> list[str]: return out +def cap_lines(counters: dict) -> list[str]: + """A cap the human lowered (or raised back) by `/cap` this shift (#644), + one line each: `merge-cap 2 → 1 (/cap by at 18:02Z)`. Not a + counter column, so the pilot rows keep their shape.""" + out = [] + for key, ov in sorted((counters.get("caps") or {}).items()): + if not isinstance(ov, dict): + continue + at = str(ov.get("at") or "") + out.append(f"- cap override: {key} {ov.get('brief', '?')} → {ov.get('value', '?')} " + f"(/cap by {ov.get('by', '?')} at {at[11:16] + 'Z' if len(at) >= 16 else at})") + return out + + def workers_crashed(counters: dict) -> int: """Workers whose exit path holds a crash (or whose launch failed); a slot recorded before per-worker exits falls back to its crash tally.""" diff --git a/agents/conductors/batch/_events.py b/agents/conductors/batch/_events.py new file mode 100644 index 00000000..1dd76235 --- /dev/null +++ b/agents/conductors/batch/_events.py @@ -0,0 +1,463 @@ +"""The shift's event stream (M3.4, PyAutoBrain#644): one append-only +`events.jsonl` per slot, beside `counters.json` and `tick.log`. + +The watcher calls `record_tick` inside its tick lock, once per tick that did +work, with the tick's result. It renders each new event as one plain sentence +(`line`) and appends one JSON object per event. `batch watch --stream` +(`_watch.stream`) prints the file; the cockpit chat watches that. + +No new reads and no LLM: the deriver reads the tick's `result`, +`counters.json`, the slot's own files and `events.state.json`. It makes no +subprocess call and no network call (a test holds it to that). + +Dedup lives in the file itself: every event has a `key`, and an event whose +key is already in `events.jsonl` is never written again. The next `seq` is the +file's last plus one. A crash between the append and the state write can +therefore neither repeat an event nor reuse a `seq`; losing +`events.state.json` costs at most one repeated `ci` line (its key still +dedups it). All the lines of one tick go out in one `write()`, each line at +most `RECORD_MAX` bytes, and a reader ignores a last line with no newline. +""" + +from __future__ import annotations + +import datetime as _dt +import json +import os +import re +from pathlib import Path + +import _digest # noqa: E402 — the batch conductor puts this directory on sys.path + +EVENTS_FILE = "events.jsonl" +STATE_FILE = "events.state.json" +SCHEMA = 1 +#: The printed sentence, at most this many characters. +LINE_MAX = 300 +#: One JSON line, at most this many bytes (one local append, never torn). +RECORD_MAX = 1024 +#: CI verdicts that make a `ci` line; RUNNING never does, UNKNOWN is skipped +#: ("gh could not say" — the tick asks again). +CI_EMIT = ("HEALTHY", "FAILED", "NO-CHECKS") +#: Ticks in a row with the commands read failing before `steer-unread`. +UNREAD_TICKS = 3 +#: Every kind `record_tick` may write (DESIGN §1.4). +KINDS = ("shift-open", "spawned", "redispatched", "crashed", "pr-opened", "finished", + "question", "parked", "ci", "closeout-started", "merged", "merged-outside", + "refused", "cap", "steer", "steer-unread", "impaired", "late", "digest", + "stopped", "shift-end") +#: The kinds after which the stream has nothing more to follow. +FINAL_KINDS = ("shift-end", "stopped") + +_GH_RE = re.compile(r"^https://github\.com/[^/\s]+/([^/\s]+)/(?:pull|issues)/(\d+)") +_LATE_TAIL_RE = re.compile(r"\s*\(after review-at, [^)]*\)\s*$") +#: Close-out refusals whose reason is the shift's, not the PR's: one `cap` +#: line per class, then silence (DESIGN §1.4, `cap`). +_CLOSEOUT_CAP_RE = re.compile(r"^(merge-cap \d+ reached|token spend reached)") + + +# --- reading ----------------------------------------------------------------------- + +def read_events(slot: Path) -> list[dict]: + """Every complete event in the slot's file, in order. A last line with no + newline (a write in progress) and a line that is not JSON are skipped.""" + try: + data = (Path(slot) / EVENTS_FILE).read_bytes() + except OSError: + return [] + out = [] + for raw in data.split(b"\n")[:-1]: # the part after the last newline is not a line yet + try: + e = json.loads(raw) + except ValueError: + continue + if isinstance(e, dict) and isinstance(e.get("seq"), int): + out.append(e) + return out + + +def _read_state(slot: Path) -> dict: + try: + s = json.loads((Path(slot) / STATE_FILE).read_text(encoding="utf-8")) + except (OSError, ValueError): + s = {} + if not isinstance(s, dict): + s = {} + s.setdefault("ci", {}) + s.setdefault("unread_run", 0) + return s + + +def _write_state(slot: Path, state: dict) -> None: + tmp = Path(slot) / (STATE_FILE + ".tmp") + tmp.write_text(json.dumps(state, sort_keys=True), encoding="utf-8") + os.replace(tmp, Path(slot) / STATE_FILE) + + +def _read_counters(slot: Path) -> dict: + try: + c = json.loads((Path(slot) / "counters.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + c = {} + return c if isinstance(c, dict) else {} + + +# --- wording ----------------------------------------------------------------------- + +def ref(url: str) -> str: + """`Repo#n` for a GitHub PR or issue URL; the URL itself otherwise.""" + m = _GH_RE.match(url or "") + return f"{m.group(1)}#{m.group(2)}" if m else (url or "?") + + +def _hhmm(iso: str) -> str: + return iso[11:16] + "Z" if iso and len(iso) >= 16 else (iso or "?") + + +def _clean(text: str) -> str: + """One line, no `@` that could notify (written `@​`, as the status + comment does), at most `LINE_MAX` characters.""" + text = " ".join(str(text).split()).replace("@", "@​") + return text if len(text) <= LINE_MAX else text[:LINE_MAX - 1] + "…" + + +def _label(task: str, pick: dict | None) -> str: + title = (pick or {}).get("title") + return f"{title} ({task})" if title else task + + +# --- the deriver ------------------------------------------------------------------- + +class _Batch: + """One tick's new events, deduplicated against the file and each other.""" + + def __init__(self, slot: Path, now: _dt.datetime, existing: list[dict]): + self.slot, self.now = Path(slot), now + self.keys = {e.get("key") for e in existing} + self.seq = max((e["seq"] for e in existing), default=0) + self.events: list[dict] = [] + self.existing = existing + + def has(self, key: str) -> bool: + return key in self.keys + + def add(self, kind: str, key: str, line: str, *, needs_you: bool = False, **extra) -> None: + if key in self.keys: + return + self.keys.add(key) + self.seq += 1 + e = {"v": SCHEMA, "seq": self.seq, + "at": self.now.astimezone(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "slot": self.slot.name, "kind": kind, "key": key[:300], + "line": _clean(line), "needs_you": bool(needs_you)} + for k, v in extra.items(): + if v not in (None, "", [], {}): + e[k] = v if not isinstance(v, str) else v[:300] + self.events.append(e) + + def runs(self, task: str) -> int: + """How many workers this shift started for `task`, as the file knows.""" + return sum(1 for k in self.keys if k == f"spawned:{task}" + or (k or "").startswith(f"redispatched:{task}")) + + def count(self, prefix: str) -> int: + return sum(1 for k in self.keys if (k or "").startswith(prefix)) + + +def _outcome(event: dict, counters: dict) -> dict: + """A `done` reap's outcome: the event's own fields (#644 adds them), else + the task's outcome in `counters` (an old `tick.log` replay).""" + fields = ("prs", "merged", "questions", "obsolete", "verdicts", "issues") + if any(k in event for k in fields): + return {k: event[k] for k in fields if k in event} + return dict((counters.get("outcomes") or {}).get(event.get("task"), {}) or {}) + + +def _reaped(b: _Batch, result: dict, counters: dict) -> None: + picks = counters.get("picks") or {} + dropped = counters.get("dropped") or {} + for e in result.get("reaped") or []: + task, ev = e.get("task"), e.get("event") + if not task: + continue + run = max(b.runs(task), 1) + if ev == "dead": + by_kill = bool(e.get("killed")) + what = "stopped by /kill" if by_kill else "died" + if task in dropped: + tail = "It is not restarted: you dropped it." + elif str(e.get("redispatch", "")).startswith("allowed"): + tail = "It restarts once." + else: + tail = "Retry spent: left for your /prm." + b.add("crashed", f"crashed:{task}:{run}", f"Worker on {task} {what}. {tail}", + task=task) + elif ev == "parked": + since = str(e.get("why") or "").replace("blocked since ", "") + b.add("parked", f"parked:{task}:{run}", + f"{task} is stuck at a prompt (since {_hhmm(since)}).", task=task) + elif ev == "done": + o = _outcome(e, counters) + merged = list(o.get("merged") or []) + tier = (picks.get(task) or {}).get("tier") or "?" + for pr in o.get("prs") or []: + if pr in merged or "/pull/" not in pr: + continue + how = ("glance: close-out when CI is green" if tier == "glance" + else f"{tier}: your /prm") + b.add("pr-opened", f"pr-opened:{pr}", f"{task} opened {ref(pr)} ({how}).", + task=task, pr=pr) + for pr in merged: + b.add("merged", f"merged-in-turn:{pr}", + f"{task} merged {ref(pr)} in-turn (notify).", task=task, pr=pr) + questions = [] if "obsolete" in o else list(o.get("questions") or []) + for q in questions: + b.add("question", f"question:{task}:{q}", + f"{task} parked with a question on {ref(q)}.", task=task, url=q) + if "obsolete" in o or o.get("verdicts") or not (o.get("prs") or questions): + if "obsolete" in o: + state = "obsolete (premise check)" + elif o.get("verdicts"): + state = "verdict posted" + else: + state = "finished, no PR or issue named in its .done" + b.add("finished", f"finished:{task}:{run}", + f"{task} finished: {_digest.plain_outcome(state)}.", task=task, + url=(o.get("verdicts") or [""])[0]) + + +def _steer(b: _Batch, result: dict, counters: dict) -> None: + for c in result.get("commands") or []: + cmd = "/" + str(c.get("command") or "?") + (f" {c['arg']}" if c.get("arg") else "") + by = c.get("by") or next((x.get("by") for x in counters.get("commands") or [] + if x.get("command") == cmd and x.get("ack") == c.get("ack")), + "") or "the human" + ack = str(c.get("ack") or "") + key = f"steer:{c['id']}" if c.get("id") else f"steer:{b.now.isoformat()}:{cmd}" + b.add("steer", key, f"{cmd} from {by}: {ack}", + needs_you=ack.startswith(("ignored", "refused")), url=c.get("url")) + + +def _spawned(b: _Batch, result: dict, counters: dict) -> None: + picks = counters.get("picks") or {} + added = counters.get("added") or {} + for s in result.get("spawned") or []: + task = s.get("task") + if not task: + continue + runs = b.runs(task) + if runs: + key = f"redispatched:{task}" + (f":{runs + 1}" if runs > 1 else "") + b.add("redispatched", key, f"Restarted {task} (its one retry).", task=task) + continue + pick = picks.get(task) or {} + why = "added by /add" if task in added else (pick.get("why") or "named in the brief") + b.add("spawned", f"spawned:{task}", + f"Started {_label(task, pick)} ({pick.get('tier') or '?'}; {why}).", task=task) + + +def _refused(b: _Batch, result: dict) -> None: + wide: dict[str, list[str]] = {} + for r in result.get("refused") or []: + cls = _digest.refusal_class(r.get("why", "")) + if _digest.SHIFT_WIDE_RE.match(cls): + wide.setdefault(cls, []).append(r.get("task") or "?") + continue + task = r.get("task") or "?" + b.add("refused", f"refused:{task}:{cls}", f"{task} not started: {cls}.", + task=task, cls=cls) + for cls, tasks in wide.items(): + n = len(tasks) + b.add("cap", f"cap:{cls}", f"{cls}: {n} task{'s' if n != 1 else ''} wait.", cls=cls) + + +def _ci(b: _Batch, result: dict, state: dict) -> None: + for pr, verdict in sorted((result.get("health") or {}).items()): + if verdict == "UNKNOWN": + continue + last = state["ci"].get(pr) + state["ci"][pr] = verdict + if verdict not in CI_EMIT or verdict == last: + continue + line = {"HEALTHY": f"CI green on {ref(pr)}.", + "FAILED": f"CI red on {ref(pr)}: never merged unattended.", + "NO-CHECKS": f"No CI checks on {ref(pr)}: left for your /prm."}[verdict] + b.add("ci", f"ci:{pr}:{verdict}", line, pr=pr) + + +def _closeouts(b: _Batch, result: dict, counters: dict, info: dict) -> None: + co_all = counters.get("closeouts") or {} + dropped = counters.get("dropped") or {} + events = result.get("closeouts") or {} + outside = set(events.get("merged_outside") or []) + cap = info.get("merge_cap", "?") + for pr in events.get("merged") or []: + co = co_all.get(pr) or {} + k = b.count("merged:") + 1 + b.add("merged", f"merged:{pr}", + f"Merged {ref(pr)} unattended ({k} of merge-cap {cap}).", + task=co.get("task"), pr=pr) + for pr in sorted(outside): + co = co_all.get(pr) or {} + login = ((co.get("github") or {}).get("mergedBy")) or "?" + b.add("merged-outside", f"merged-outside:{pr}", + f"{ref(pr)} was merged outside the close-out (by {login}).", + needs_you=co.get("task") in dropped, task=co.get("task"), pr=pr) + _ci(b, result, b.state) + for pr in events.get("refused") or []: + if pr in outside: + continue + co = co_all.get(pr) or {} + cls = _digest.refusal_class(co.get("why") or "refused") + wide = _CLOSEOUT_CAP_RE.match(cls) + if wide: + b.add("cap", f"cap:{wide.group(1)}", + f"{cls.removesuffix(' this shift')}: later green PRs wait for /prm.", + cls=cls) + continue + b.add("refused", f"refused:{pr}", f"Not merging {ref(pr)}: {cls}. Left for your /prm.", + task=co.get("task"), pr=pr, cls=cls) + for pr in events.get("started") or []: + co = co_all.get(pr) or {} + b.add("closeout-started", f"closeout-started:{pr}", f"Close-out started on {ref(pr)}.", + task=co.get("task"), pr=pr) + + +def _impaired(b: _Batch, result: dict) -> None: + auth = result.get("github_auth") or {} + if auth.get("error"): + b.add("impaired", "impaired:github-auth", + f"Watcher can't post to GitHub ({str(auth['error'])[:160]}). Writes held.", + needs_you=True) + for ledger in (result.get("ledger"), (result.get("status") or {}).get("ledger")): + if not isinstance(ledger, dict): + continue + if ledger.get("error"): + why = str(ledger["error"])[:160] + b.add("impaired", f"impaired:ledger-error:{why[:80]}", + f"Mind write failed: {why}.", needs_you=True) + for word, items in (("set aside", ledger.get("set_aside")), ("held", ledger.get("held"))): + for x in items or []: + op = x.get("op") if isinstance(x, dict) else str(x) + why = (x.get("why") if isinstance(x, dict) else "") or "?" + where = x.get("file") if isinstance(x, dict) else "" + b.add("impaired", f"impaired:ledger:{word}:{where or op}:{str(why)[:60]}", + f"Mind write {word}: {op}, {why}.", needs_you=True) + + +def _late(b: _Batch, result: dict) -> None: + for line in result.get("late") or []: + text = _LATE_TAIL_RE.sub("", str(line).removeprefix("- late: ").strip()) + b.add("late", f"late:{text[:200]}", f"Late arrival: {text} after review-at.") + + +def _digest_event(b: _Batch, result: dict, counters: dict) -> None: + post = result.get("post") or {} + parked = [t for t, o in (counters.get("outcomes") or {}).items() + if isinstance(o, dict) and o.get("questions") and "obsolete" not in o + and not o.get("merged")] + parked += [t for t in counters.get("parked") or [] if t not in parked] + tail = (f" {len(parked)} task{'s' if len(parked) != 1 else ''} parked on a question." + if parked else "") + if post.get("url"): + b.add("digest", "digest", f"Shift closed. Digest: {post['url']}.{tail}", url=post["url"]) + else: + why = post.get("error") or "not posted" + b.add("digest", "digest", f"Shift closed. Digest written to the record; its post: " + f"{why}.{tail}") + + +def record_tick(slot: Path, now: _dt.datetime, result: dict, counters: dict | None = None, + *, info: dict | None = None, quiet: bool | None = None) -> list[dict]: + """Append this tick's new events to `/events.jsonl`; returns them. + + `result` is what the tick returned (and logs). `counters` defaults to the + slot's `counters.json` (a replay passes its own). `info` carries what the + record says about the shift (`review_at`, `named`, `merge_cap`, + `token_budget`), for the `shift-open` and `merged` lines. `quiet` is + whether nothing is left for the late sweep (no lease, no queued op, no + close-out out, nothing unreported, no post due): on a digest or late-sweep + tick it writes `shift-end`. Called by the watcher inside its tick lock.""" + slot = Path(slot) + info = info or {} + counters = counters if counters is not None else _read_counters(slot) + existing = read_events(slot) + b = _Batch(slot, now, existing) + b.state = _read_state(slot) + action = result.get("action") + + if action in ("ticked", "shadow") and not existing: + n = info.get("named") + parts = [f"Shift {slot.name} open until {_hhmm(info.get('review_at') or '')}"] + bits = ([f"{n} named task{'s' if n != 1 else ''}"] if n is not None else []) \ + + [f"merge-cap {info.get('merge_cap', '?')}"] \ + + ([f"{info['token_budget']} token budget"] if info.get("token_budget") else []) + b.add("shift-open", "shift-open", parts[0] + ": " + ", ".join(bits) + ".") + _reaped(b, result, counters) + _steer(b, result, counters) + _closeouts(b, result, counters, info) + _spawned(b, result, counters) + _refused(b, result) + _impaired(b, result) + _late(b, result) + if action in ("ticked", "shadow", "stopped"): + if counters.get("commands_unread"): + if not b.state["unread_run"]: + b.state["unread_since"] = counters["commands_unread"] + b.state["unread_run"] += 1 + if b.state["unread_run"] >= UNREAD_TICKS: + since = b.state.get("unread_since") or counters["commands_unread"] + b.add("steer-unread", f"steer-unread:{since}", + f"Can't read your commands on the shift issue since {_hhmm(since)}. " + "Steering is on hold.", needs_you=True) + else: + b.state["unread_run"] = 0 + b.state.pop("unread_since", None) + if action == "digest" and result.get("post") is not None \ + and (result.get("post") or {}).get("error") != "already posted this shift": + _digest_event(b, result, counters) + if action == "stopped" and "/stop" in str(result.get("reason") or ""): + b.add("stopped", "stopped", "Stopped by /stop. The watcher does nothing more. " + "Workers still out are not killed.") + if action in ("digest", "late") and quiet and b.has("digest"): + b.add("shift-end", "shift-end", f"Shift {slot.name} over. Nothing is still running.") + + if b.events: + _append(slot, b.events) + _write_state(slot, b.state) + return b.events + + +def _encode(e: dict) -> bytes: + raw = json.dumps(e, sort_keys=True, ensure_ascii=False).encode("utf-8") + while len(raw) > RECORD_MAX - 1: + for k in ("url", "pr"): + if k in e and len(e[k]) > 120: + e[k] = e[k][:120] + e["line"] = e["line"][:max(len(e["line"]) - 60, 40)] + e["key"] = e["key"][:200] + raw = json.dumps(e, sort_keys=True, ensure_ascii=False).encode("utf-8") + if len(e["line"]) <= 40: + break + return raw + b"\n" + + +def _append(slot: Path, events: list[dict]) -> None: + """One `write()` for the tick's lines. A torn last line from a crash is + closed off first, so the new lines never join it.""" + path = Path(slot) / EVENTS_FILE + data = b"".join(_encode(e) for e in events) + try: + size = path.stat().st_size + except OSError: + size = 0 + if size: + with open(path, "rb") as fh: + fh.seek(size - 1) + if fh.read(1) != b"\n": + data = b"\n" + data + fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644) + try: + os.write(fd, data) + finally: + os.close(fd) diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 7d4fcacd..1140deaf 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -27,7 +27,10 @@ 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). +`/stop` (#622) and `/add` `/cap` `/kill` (#644). Every tick that does work +appends what it did to the slot's `events.jsonl` (`_events`, #644), which +`batch watch --stream` prints; a needs-you event is also one short comment on +the shift issue, at most `EVENT_COMMENTS_MAX` a shift. """ from __future__ import annotations @@ -44,6 +47,7 @@ import _app_token # noqa: E402 — the batch conductor puts this directory on sys.path import _brief # noqa: E402 import _digest # noqa: E402 +import _events # noqa: E402 import _mind_writer # noqa: E402 STOP_FILE = "STOP" @@ -172,11 +176,16 @@ def _write_counters(slot: Path, c: dict) -> None: os.replace(tmp, slot / COUNTERS_FILE) -def _log(slot: Path, now: _dt.datetime, result: dict) -> None: - """Append the tick's result; a GitHub identity that failed this tick is - named in it (and in what the tick returns) — its writes were held.""" +def _auth_note(result: dict) -> None: + """A GitHub identity that failed this tick is named in its result (and in + what the tick returns, logs and streams) — its writes were held.""" if _AUTH is not None and _AUTH.used and _AUTH.error and "github_auth" not in result: result["github_auth"] = {"error": _AUTH.error, "writes": "held"} + + +def _log(slot: Path, now: _dt.datetime, result: dict) -> None: + """Append the tick's result to `tick.log`.""" + _auth_note(result) with open(slot / LOG_FILE, "a", encoding="utf-8") as fh: fh.write(json.dumps({"at": _iso(now), **result}, sort_keys=True) + "\n") @@ -994,8 +1003,13 @@ def mark(word, rec=rec): if real: path.write_text(json.dumps(lease, sort_keys=True)) # the unlisted count continue # gone, but inside the grace for a late `.done` - counters["crashes"] += 1 - mark("crashed") + # A worker the human stopped by `/kill` (#644) ends as `killed`, not + # `crashed`: it counts for the re-dispatch rule, not as a crash. + killed = (counters.get("killed") or {}).get(task) or {} + by_kill = bool(killed) and killed.get("key") == rec.get("key") + if not by_kill: + counters["crashes"] += 1 + mark("killed" if by_kill else "crashed") again = counters["redispatched"].get(task, 0) < REDISPATCH_LIMIT if again and task not in counters["pending_redispatch"]: counters["pending_redispatch"].append(task) @@ -1004,7 +1018,8 @@ def mark(word, rec=rec): _write_counters(slot, counters) path.unlink(missing_ok=True) events.append({"task": task, "event": "dead", - "redispatch": "allowed" if again else "spent — abandoned"}) + "redispatch": "allowed" if again else "spent — abandoned", + **({"killed": True} if by_kill else {})}) return events @@ -1089,6 +1104,7 @@ def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, agents=agents, tokens=tokens, grace_s=grace_s, github=github, pr_state=(pr_state or getattr(spawner, "pr_state", None) or _default_pr_state())) + _record_events(slot, now, result, brief_path, poster) finally: _drop_lock(slot) _log(slot, now, result) @@ -1105,6 +1121,7 @@ def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, agents=agents, tokens=tokens, poster=poster, pr_state=(pr_state or getattr(spawner, "pr_state", None) or _default_pr_state())) + _record_events(slot, now, result, brief_path, poster) finally: _drop_lock(slot) _log(slot, now, result) @@ -1125,6 +1142,7 @@ def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, grace_s, records, agents, tokens, health, pr_state, poster=poster, shift=shift, token_reserve=token_reserve, whoami=whoami, github=github) + _record_events(slot, now, result, brief_path, poster) finally: _drop_lock(slot) _log(slot, now, result) @@ -1339,6 +1357,10 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, stopped=out.get("action") == "stopped") if status: out["status"] = status + if health.seen: + # Every CI verdict this tick read, for the event stream's `ci` line + # (#644): no read of its own — the close-outs made these. + out["health"] = dict(health.seen) _note_auth_file(slot, now) return out @@ -1356,6 +1378,13 @@ 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) + # A task the human added by `/add` (#644) is graded from Mind + # origin/main when it is added: a prompt filed mid-shift is in no + # survey of the canonical checkout, which nobody pulls mid-shift. + have = {r["path"] for r in recs} + recs = recs + [a["record"] for a in (counters.get("added") or {}).values() + if isinstance(a.get("record"), dict) + and a["record"].get("path") not in have] # Parked on a question by an earlier shift (#637, item 3): not # startable until answered. A brief that names it again is the # human's word that it is; a task this shift picked stays. Read @@ -1386,8 +1415,16 @@ def known(task: str) -> bool: # 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, whoami, known) + ctx = {"brief": brief, "now": now, "mind": mind, + "review_at": _brief._iso((shift or {}).get("review_at") or "")} + commands = _steer(slot, counters, shift or {}, now, github, whoami, known, ctx=ctx) _write_counters(slot, counters) + if any(c["command"] in ("add", "cap") for c in commands): + planned.clear() # an /add or /cap changes what this tick's plan admits + # `/cap` overrides and `/add`ed tasks (#644), from here on in this tick: + # every later reader (the spawn gates, the close-out gates) sees them. + written = brief + brief = _brief.effective(brief, 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", @@ -1435,8 +1472,11 @@ def known(task: str) -> bool: "ledger": ledger} return _steered(out, commands, paused) budget = _brief._nonneg_int(brief.get("token-budget", {}).get("value", "")) - if budget: - counters["token_budget"] = budget # what a later shift's estimate compares + written_budget = _brief._nonneg_int(written.get("token-budget", {}).get("value", "")) + if written_budget: + # What a later shift's estimate compares: the brief's own figure, not + # a `/cap tokens` lowered for this shift. + counters["token_budget"] = written_budget # 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 # (dry-shift) worker spends nothing. @@ -1850,10 +1890,23 @@ def _mentions(slot: Path, counters: dict, shift: dict, poster, now: _dt.datetime #: The dashboard's copy of the status: one `- live:` line in the brief record, #: rewritten through the one Mind writer when the shift's state changes. LIVE_KEY_FILE = "live.key" -#: The steering commands, read from the human's comments on the shift issue. -COMMANDS = ("pause", "resume", "drop", "stop") -_COMMAND_RE = re.compile(r"^/(pause|resume|drop|stop)\b[ \t]*(\S+)?[ \t]*$") +#: The steering commands, read from the human's comments on the shift issue +#: (#622; `/add`, `/cap` and `/kill` from #644). +COMMANDS = ("pause", "resume", "drop", "stop", "add", "cap", "kill") +_COMMAND_RE = re.compile( + r"^/(pause|resume|drop|stop|add|cap|kill)\b[ \t]*(\S+)?(?:[ \t]+(\S+))?[ \t]*$") +#: The one verb that takes two arguments (`/cap `). +_TWO_ARGS = ("cap",) _TASK_ARG_RE = re.compile(r"^[A-Za-z0-9_./-]+$") +#: `/add` is refused this close to `review-at:` — a worker needs longer +#: (human ruling H8, 2026-11-16). +ADD_CUTOFF_S = 1800 +#: `/cap ` → the brief key it lowers (human ruling H6: never above the +#: brief's own value). +CAP_KEYS = {"merges": "merge-cap", "workers": "max-workers", "sessions": "max-sessions", + "tokens": "token-budget"} +#: `/kill`'s one local act, `claude stop ` — not a network call. +STOP_TIMEOUT_S = 30 #: `/.dropped`: a dropped task's close-out session checks it #: just before it merges, and refuses (closeout_template.md). DROPPED_SUFFIX = ".dropped" @@ -1943,17 +1996,32 @@ def status_url(slot: Path) -> str: def _parse_command(body: str) -> tuple[str, str] | None: """(command, argument) when a comment's first non-empty line is a - steering command and nothing else; None otherwise.""" + steering command and nothing else; None otherwise. `/cap`'s two + arguments come back as one, space-separated; every other verb takes one + at most, as before #644.""" first = next((ln.strip() for ln in (body or "").splitlines() if ln.strip()), "") m = _COMMAND_RE.match(first) - return (m.group(1), (m.group(2) or "").strip("`")) if m else None + if not m: + return None + one, two = (m.group(2) or "").strip("`"), (m.group(3) or "").strip("`") + if two and m.group(1) not in _TWO_ARGS: + return None + return m.group(1), (f"{one} {two}" if two else one) def _apply_command(slot: Path, counters: dict, cmd: str, arg: str, who: str, - at: str, known=None) -> str: + at: str, known=None, ctx: dict | None = 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).""" + member). `ctx` is what `/add`, `/cap` and `/kill` judge against: the + brief as written, `now`, `review_at` and the Mind checkout.""" + if cmd in ("add", "cap", "kill"): + ctx = ctx or {} + try: + return {"add": _cmd_add, "cap": _cmd_cap, "kill": _cmd_kill}[cmd]( + slot, counters, arg, who, at, ctx) + except Exception as e: # one command's failure is its ack, never the tick's + return f"refused: /{cmd} could not be judged ({str(e)[:200]})" if cmd == "pause": if counters.get("paused"): return "already paused" @@ -1999,7 +2067,7 @@ def _apply_command(slot: Path, counters: dict, cmd: str, arg: str, who: str, def _steer(slot: Path, counters: dict, shift: dict, now: _dt.datetime, github=None, - whoami=None, known=None) -> list[dict]: + whoami=None, known=None, ctx: dict | None = 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. @@ -2060,15 +2128,340 @@ 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"], known) + ack = _apply_command(slot, counters, cmd, arg, c["login"], c["created_at"], known, + ctx=ctx) 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}) + out.append({"command": cmd, "arg": arg, "ack": ack, "id": c["id"], "by": c["login"], + "at": c["created_at"], "url": c["url"]}) counters["commands_seen"] = sorted(seen) return out +# --- `/cap`, `/add`, `/kill` (#644; human rulings H5, H6, H8 of 2026-11-16) ------------- + +def _cap_ceiling(brief: dict, key: str) -> int | None: + """A cap as `brief` states it: the spawn caps with their defaults, the + merge cap 0 when absent (as the close-out reads it), and no token + ceiling when the brief sets no `token-budget:`.""" + if key in ("max-workers", "max-sessions"): + return _brief.cap_of(brief, key) + value = _brief._nonneg_int((brief.get(key) or {}).get("value", "")) + return (value or 0) if key == "merge-cap" else value + + +def _cap_number(word: str, tokens: bool) -> int | None: + if re.fullmatch(r"\d+", word or ""): + return int(word) + m = re.fullmatch(r"(\d+(?:\.\d+)?)([kKmM])", word or "") if tokens else None + if m: + return int(round(float(m.group(1)) * (1000 if m.group(2) in "kK" else 1_000_000))) + return None + + +def _cmd_cap(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict) -> str: + """`/cap merges|workers|sessions|tokens `: lower one of this shift's + caps, or raise it back, never above the brief's own value. It never + kills, never stops a close-out already running and never edits the + brief; `_brief.effective` applies it from this tick on.""" + words = (arg or "").split() + if not words or words[0] not in CAP_KEYS: + return "ignored: /cap takes merges, workers, sessions or tokens" + key = CAP_KEYS[words[0]] + n = _cap_number(words[1], key == "token-budget") if len(words) == 2 else None + if n is None: + return "ignored: /cap needs a whole number" + brief = ctx.get("brief") or {} + ceiling = _cap_ceiling(brief, key) + if ceiling is not None and n > ceiling: + return (f"refused: /cap {words[0]} {words[1]} is above this brief's {key} {ceiling}. " + "A higher cap needs a new brief.") + was = _cap_ceiling(_brief.effective(brief, counters), key) + counters.setdefault("caps", {})[key] = {"value": n, "by": who, "at": at, "was": was, + "brief": ceiling} + of = f"{ceiling}" if ceiling is not None else "none" + if key == "merge-cap": + merged = int(counters.get("glance_auto_merges") or 0) + running = sum(1 for co in counters["closeouts"].values() if co.get("state") == "running") + tail = (": no new close-out starts." if merged + running >= n + else f": up to {n - merged - running} more may start.") + return f"merge-cap now {n} of this brief's {of} ({merged} merged so far){tail}" + if key == "max-workers": + live = len(active_leases(slot)) + return f"max-workers now {n} of {of}." + ( + f" {live} still running are not stopped; no new spawn until fewer than {n}." + if live >= n else "") + if key == "max-sessions": + started = int(counters.get("sessions") or 0) + return f"max-sessions now {n} of {of} ({started} started)" + ( + ": no new spawn." if started >= n else ".") + committed = _committed_tokens(counters) + tail = "." + if committed >= CLOSEOUT_BUDGET_FACTOR * n: + tail = ": no new spawn or close-out." + elif committed >= n: + tail = f": no new spawn; close-outs stop at {int(CLOSEOUT_BUDGET_FACTOR * n)}." + return f"token-budget now {n} of {of} ({committed} committed){tail}" + + +def _origin_prompt(mind: Path, arg: str) -> tuple[str | None, str]: + """(Mind-relative path, '') of the draft `arg` names on Mind origin/main, + or (None, the ignored ack). A path is read as given; a basename must name + exactly one draft. Local git reads after the `/add` fetch.""" + if "/" in arg: + rel = arg if arg.endswith(".md") else arg + ".md" + if _brief.origin_text(mind, rel) is None: + return None, f"ignored: no prompt {rel} on Mind origin/main (filed? pushed?)" + return rel, "" + name = arg if arg.endswith(".md") else arg + ".md" + try: + res = subprocess.run(["git", "-C", str(mind), "ls-tree", "-r", "-z", "--name-only", + "origin/main", "--", "draft/"], + capture_output=True, text=True, timeout=60) + except (OSError, subprocess.SubprocessError) as e: + return None, f"ignored: Mind origin/main unreadable ({str(e)[:120]})" + if res.returncode != 0: + return None, "ignored: Mind origin/main unreadable: " + (res.stderr or "").strip()[:120] + hits = sorted(p for p in res.stdout.split("\0") if p and Path(p).name == name) + if not hits: + return None, f"ignored: no prompt {name} on Mind origin/main (filed? pushed?)" + if len(hits) > 1: + return None, f"ignored: {name} names {len(hits)} drafts: give the path" + return hits[0], "" + + +def _in_shift(task: str, slot: Path, counters: dict, brief: dict) -> str: + """Why `task` is already this shift's ('' when it is not).""" + if task in leases(slot): + return "running" + if task in counters.get("added", {}): + return "added by /add" + if task in counters["dropped"]: + return "dropped" + if task in counters["done"] or task in counters["outcomes"]: + return "finished" + if task in counters["picks"]: + return "picked" + if task in {task_id(p) for p in _brief.tasks_of(brief)}: + return "named in the brief" + return "" + + +def _cmd_add(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict) -> str: + """`/add `: make a draft a brief-named task for the rest of this + shift. The planner's own gates judge it as they judge a named task; it + overrides the brief's `exclude:` and an earlier shift's parked hold (the + human's newer word), never the organ rule (human ruling H8).""" + if not arg or not _TASK_ARG_RE.match(arg): + return "ignored: /add needs a prompt (draft/…/x.md, x.md or x)" + now, review_at = ctx.get("now") or _now(), ctx.get("review_at") + if review_at is not None and (review_at - now).total_seconds() < ADD_CUTOFF_S: + return (f"refused: /add within {ADD_CUTOFF_S // 60} min of review-at. " + "A worker needs longer.") + brief = ctx.get("brief") or {} + if _brief.is_shadow(brief): + return "refused: shadow shift: nothing is dispatched." + mind = Path(ctx["mind"]) + try: + # One fetch per `/add` (AUTONOMY.md amendment 2026-11-16, #644): a + # prompt filed mid-shift is newer than the once-per-shift fetch. + _mind_writer.fetch(mind) + except _mind_writer.MindWriteError as e: + counters.setdefault("add_fetch_errors", []).append(str(e)[:200]) + rel, why = _origin_prompt(mind, arg) + if rel is None: + return why + task = task_id(rel) + state = _in_shift(task, slot, counters, brief) + if state: + return f"ignored: {task} is already in this shift ({state})" + text = _brief.origin_text(mind, rel) or "" + added_dir = slot / "added" + added_dir.mkdir(parents=True, exist_ok=True) + (added_dir / Path(rel).name).write_text(text, encoding="utf-8") + import _batch # noqa: E402 — deferred, as in `_tick_body` + rec = _batch.grade_text(text, rel, mind) + if (organ := _batch.self_organ_why(rec)): + return f"refused: {task} {organ} (the organ rule: /add never overrides it)" + if (lane := _batch.lane_absent_why(rec)): + return f"refused: {task}: no Lane: line ({lane})" + ex_paths, ex_keyed = _brief.excluded_of(brief) + excluded = Path(rel).name in {Path(p).name for p in ex_paths} \ + or rec.get("epic") in ex_keyed.get("epics", []) \ + or bool(set(rec.get("themes") or []) & set(ex_keyed.get("tags", []))) + trial = dict(counters, added={**counters.get("added", {}), task: {"prompt": rel}}) + eff = _brief.effective(brief, trial) + d = _batch.plan([rec], session_lane="local-dev", brief=eff, queue=None) + if not any(m.get("path") == rel for m in d["members"]): + reason = next((w for p, w in d["rejected"] if p == rel), "not admitted by the planner") + return f"refused: {task}: {reason}" + kept, claimed = on_origin([rec], mind, set()) + if not kept: + return f"refused: {task}: {claimed.get(rel) or 'claimed on Mind origin/main'}" + was_parked = task in parked_elsewhere(slot) + counters.setdefault("added", {})[task] = {"prompt": rel, "by": who, "at": at, "record": rec} + notes = "".join([" (was excluded in the brief)" if excluded else "", + " (was parked)" if was_parked else ""]) + max_workers = _brief.cap_of(_brief.effective(brief, counters), "max-workers") + live = len(active_leases(slot)) + when = ("starts this tick" if live < max_workers + else "starts when a worker slot frees (next in line)") + return (f"added {task} ({rec.get('consequence') or '?'}){notes}: {when}; " + f"max-workers {max_workers}, {live} running.") + + +def claude_stop(agent_id: str, run=None) -> tuple[bool, str]: + """`claude stop `, the local CLI (30 s timeout): (stopped?, why not).""" + run = run or subprocess.run + try: + res = run(["claude", "stop", agent_id], capture_output=True, text=True, + timeout=STOP_TIMEOUT_S) + except (OSError, subprocess.SubprocessError) as e: + return False, str(e) + if res.returncode != 0: + first = next((ln for ln in ((res.stderr or "") + (res.stdout or "")).splitlines() + if ln.strip()), f"exit {res.returncode}") + return False, first.strip() + return True, "" + + +def _cmd_kill(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict) -> str: + """`/kill ` (human ruling H5): stop that task's running worker with + `claude stop`. The next reap sees it ended: it is `killed` (not a crash) + and re-dispatched once by the usual rule, unless the task was dropped. + A close-out is not killable here.""" + if not arg or not _TASK_ARG_RE.match(arg): + return "ignored: /kill needs a task name" + task = Path(arg).stem + lease = leases(slot).get(task) + if lease is None: + return f"ignored: no running worker for {task}" + key = _worker_key(lease, task) + agent = lease.get("agent_id") + if not agent: + return (f"refused: {task}'s worker {key} is no claude session (a dry-run stub). " + "Stop it by hand.") + old = (counters.get("killed") or {}).get(task) or {} + if old.get("key") == key: + return f"ignored: {task}'s worker {key} is already stopping (/kill at {old.get('at')})" + ok, why = (ctx.get("stop") or claude_stop)(agent) + if not ok: + return (f"refused: claude stop failed: {why[:160]}. Stop it by hand: " + f"claude stop {agent}") + counters.setdefault("killed", {})[task] = {"by": who, "at": at, "key": key} + if task in counters["dropped"]: + tail = f"It is not restarted: {task} was dropped." + elif lease.get("state") == "parked": + tail = "It stays parked for you; it is not restarted." + elif counters["redispatched"].get(task, 0) >= REDISPATCH_LIMIT: + tail = "It is not restarted: its one retry is spent." + else: + tail = f"It is restarted once, unless you /drop {task}." + return f"stopping {task}'s worker {key} (claude stop). {tail}" + + +# --- the event stream's watcher side (#644) -------------------------------------------- + +#: Needs-you event comments a shift may post (human ruling H4b), then one +#: last one saying the rest are in the status comment. +EVENT_COMMENTS_MAX = 5 +EVENT_OVERFLOW = "event.overflow" + + +def _event_info(brief_path: Path, slot: Path) -> dict: + """What the record says about the shift, with this shift's `/cap`s and + `/add`s applied — the `shift-open` and `merged` lines. Local reads.""" + try: + rec = _brief.parse(Path(brief_path).read_text(encoding="utf-8")) + except (OSError, _brief.BriefError): + return {} + top = rec["top"] + eff = _brief.effective(rec["brief"] or {}, _safe_counters(slot) or {}) + return {"review_at": (top.get("review-at") or {}).get("value", ""), + "issue": (top.get("issue") or {}).get("value", ""), + "named": len(_brief.tasks_of(eff)), + "merge_cap": _cap_ceiling(eff, "merge-cap"), + "token_budget": (eff.get("token-budget") or {}).get("value", "")} + + +def shift_quiet(slot: Path) -> bool: + """Nothing left for the late sweep: no lease, no queued Mind op, no + close-out out, nothing unreported, no post due — the late sweep's own + condition, negated. Local reads.""" + return not (leases(slot) or _mind_writer.pending_ops(slot) or closeouts_running(slot) + or ledger_unreported(slot) or post_due(slot / DIGEST_MARKER) + or post_due(slot / CORRECTION_MARKER) or mentions_due(slot)) + + +def _record_events(slot: Path, now: _dt.datetime, result: dict, brief_path: Path, + poster=None) -> None: + """Append the tick's events (inside the tick lock), then post a comment + for each needs-you one. Never fails the tick: a fault is named on stderr + and the tick carries on.""" + _auth_note(result) + try: + info = _event_info(brief_path, slot) + quiet = shift_quiet(slot) if result.get("action") in ("digest", "late") else None + new = _events.record_tick(slot, now, result, info=info, quiet=quiet) + except Exception as e: + print(f"orchestrator: events not recorded this tick ({e})", file=sys.stderr) + return + try: + posted = _event_comments(slot, new, info.get("issue", ""), poster, now) + except Exception as e: + print(f"orchestrator: needs-you comment failed ({e})", file=sys.stderr) + return + if posted: + result["event_comments"] = posted + + +def event_comment_body(slot_name: str, event: dict) -> str: + """A needs-you event as a short comment: no `@`, so it notifies only those + who already take part in the issue (the human, through their commands).""" + return (f"Shift `{slot_name}` needs you: {event['line']}\n\n" + f"(event {event['seq']}, `{event['kind']}`; the status comment has the rest. " + f"At most {EVENT_COMMENTS_MAX} such comments a shift.)\n").replace("@", "@\u200b") + + +def _event_comments(slot: Path, events: list[dict], issue: str, poster, + now: _dt.datetime) -> list[dict]: + """One comment per needs-you event on the shift issue (human ruling H4b), + at most `EVENT_COMMENTS_MAX` a shift and then one overflow comment, each + claimed by its marker before the post (`mentions/event.`); a post + `gh` said failed is retried with the mentions. Each counts as a push.""" + todo = [e for e in events if e.get("needs_you")] + if not todo or not issue.startswith("http") or (slot / STOP_FILE).exists(): + return [] + d = slot / MENTIONS_DIR + d.mkdir(parents=True, exist_ok=True) + sent = len([m for m in d.glob("event.*.json") if m.stem != EVENT_OVERFLOW]) + counters = read_counters(slot) + out = [] + for e in todo: + if sent >= EVENT_COMMENTS_MAX: + name = EVENT_OVERFLOW + text = (f"Shift `{slot.name}`: further needs-you events are in the status " + "comment (and the event stream); no more such comments this shift.\n") + else: + name, text = f"event.{e['seq']}", event_comment_body(slot.name, e) + if (d / f"{name}.json").exists(): + break + (d / f"{name}.md").write_text(text, encoding="utf-8") + rec = post_once(d / f"{name}.json", issue, d / f"{name}.md", poster, now, + event=e["seq"], kind=e["kind"]) + if rec is None: + continue + sent += 1 + if rec.get("state") == "posted": + counters["pushes"] += 1 + out.append({"event": e["seq"], "post": rec.get("state")}) + if name == EVENT_OVERFLOW: + break + _write_counters(slot, counters) + 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.""" @@ -2375,7 +2768,8 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, # reports from here on reaches the human through the late sweep (#632). counters["ledger_reported"] = len(_mind_writer.report(slot)) _write_counters(slot, counters) - digest = _digest.build(brief, slot, counters, health=health, issue=issue, mind=mind) + digest = _digest.build(_brief.effective(brief, counters), slot, counters, health=health, + issue=issue, mind=mind) (slot / DIGEST_FILE).write_text(digest, encoding="utf-8") result = {"action": "digest", "ledger": None, "post": None, "packet": None} diff --git a/agents/conductors/batch/_watch.py b/agents/conductors/batch/_watch.py index e6a463b1..03ce93ce 100644 --- a/agents/conductors/batch/_watch.py +++ b/agents/conductors/batch/_watch.py @@ -16,6 +16,10 @@ Task wording comes from `_digest.task_state`, the digest's own, so the live view and the digest never disagree. +`--stream` (`stream`, PyAutoBrain#644) prints the shift's event stream instead +— the watcher's `events.jsonl`, one plain line per event — and exits when the +shift ends. It reads local files only: no `claude agents`, no `gh`. + 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. @@ -31,6 +35,7 @@ import _brief # noqa: E402 — the batch conductor puts this directory on sys.path import _digest # noqa: E402 +import _events # noqa: E402 import _orchestrator # noqa: E402 #: The refresh interval floor, in seconds: `gh pr checks` is not hammered. @@ -109,6 +114,9 @@ def snapshot(brief_path: Path, slot: Path, now: _dt.datetime, *, agents=None, started = slot.is_dir() counters = _orchestrator.read_counters(slot) if started else {} + # The caps and tasks this shift now runs under (`/cap`, `/add`, #644). + brief = _brief.effective(brief, counters) + added = counters.get("added") or {} held = _orchestrator.leases(slot) if started else {} picks = counters.get("picks", {}) named = [Path(p).stem for p in _brief.tasks_of(brief)] @@ -124,7 +132,7 @@ def snapshot(brief_path: Path, slot: Path, now: _dt.datetime, *, agents=None, state, tiered = _digest.task_state(task, counters, health, live=True, lease=held.get(task), agents=agents) tier = picks.get(task, {}).get("tier", "?") - why = ("named in the brief" if task in named + why = ("added by /add" if task in added else "named in the brief" if task in named else picks.get(task, {}).get("why") or "NOT RECORDED") again = counters.get("redispatched", {}).get(task, 0) # The status comment's two-line entry (#634): no Mind prompt link — @@ -133,7 +141,7 @@ def snapshot(brief_path: Path, slot: Path, now: _dt.datetime, *, agents=None, entry = _digest.entry_lines( task, picks.get(task), state, tiered, tier, _digest.work_link(task, counters, links), - why="" if task in named else why, + why=why if task in added else "" if task in named else why, extra=[f"re-dispatched {again}×"] if again else []) rows.append({"task": task, "state": state, "label": _digest.label(task, picks.get(task)), @@ -233,7 +241,8 @@ def render(snap: dict) -> str: # --- 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`.") + "`/pause`, `/resume`, `/drop `, `/stop`, `/add `, " + "`/cap merges|workers|sessions|tokens `, `/kill `.") def render_status(snap: dict) -> str: @@ -315,3 +324,190 @@ def watch(brief_path: Path, slot: Path, *, interval: float = MIN_INTERVAL_S, except KeyboardInterrupt: out.write("\n") return 0 + + +# --- `batch watch --stream`: the shift's event stream (PyAutoBrain#644) ----------- + +#: The env file the watcher's systemd unit reads; the stream reads the same +#: brief and home from it, so the two agree on the slot. +ENV_FILE = Path.home() / ".config" / "pyauto" / "orchestrator.env" +#: Seconds between two reads of `events.jsonl` (a local stat and read). +STREAM_POLL_S = 5 +#: The stream may attach this long before `dispatched:` … +ATTACH_BEFORE_S = 30 * 60 +#: … and runs until this long after `review-at:` (the late-sweep window, +#: human ruling H2). +LATE_WINDOW_S = 45 * 60 +#: Events printed on attach without `--from`. +CATCH_UP = 5 +#: Exit codes: done (shift over, STOP, window), refused, segment over. +RC_DONE, RC_REFUSED, RC_SEGMENT = 0, 2, 3 + + +def env_file(path: Path | None = None) -> dict[str, str]: + """`KEY=VALUE` lines of the orchestrator env file; {} when absent.""" + out = {} + try: + text = Path(path or ENV_FILE).read_text(encoding="utf-8") + except OSError: + return out + for line in text.splitlines(): + line = line.strip() + if line and not line.startswith("#") and "=" in line: + k, v = line.split("=", 1) + out[k.strip()] = v.strip().strip('"').strip("'") + return out + + +def _window(record: Path) -> tuple: + rec = _brief.parse(Path(record).read_text(encoding="utf-8")) + top = rec["top"] + start = _brief._iso(_value(top, "dispatched", "")) + end = _brief._iso(_value(top, "review-at", "")) + return start, end + + +def attachable(record: Path, slot: Path, now: _dt.datetime) -> tuple[bool, str]: + """(may the stream run now?, why not). Window: `dispatched:` − 30 min to + `review-at:` + 45 min; never with `STOP` present or after `shift-end`.""" + try: + start, end = _window(record) + except (OSError, _brief.BriefError) as e: + return False, f"unreadable record {record} ({e})" + if start is None or end is None: + return False, f"{Path(record).name} has no dispatched:/review-at: to watch between" + if now < start - _dt.timedelta(seconds=ATTACH_BEFORE_S): + opens = start - _dt.timedelta(seconds=ATTACH_BEFORE_S) + return False, f"shift {slot.name} not open yet: attach from {opens:%H:%M}Z" + if now > end + _dt.timedelta(seconds=LATE_WINDOW_S): + return False, f"shift {slot.name} watch window is over (review-at + 45 min)" + if (slot / _orchestrator.STOP_FILE).exists(): + return False, f"STOP present in {slot}: the watcher does nothing" + if any(e.get("kind") == "shift-end" for e in _events.read_events(slot)): + return False, f"shift {slot.name} is over (shift-end written)" + return True, "" + + +def attach_summary(record: Path, slot: Path) -> str: + """One line from `counters.json` and the leases: live workers, merges of + the cap, tokens of the budget, paused. Local files only — no `claude + agents`, no `gh` (a test holds it to that).""" + if not (slot / _orchestrator.COUNTERS_FILE).exists(): + return "no tick yet — the watcher has not run for this brief" + counters = _orchestrator.read_counters(slot) + brief = _brief.parse(Path(record).read_text(encoding="utf-8"))["brief"] or {} + brief = _brief.effective(brief, counters) + held = _orchestrator.leases(slot) + live = sum(1 for l in held.values() if l.get("state") != "parked") + values = _digest.counter_values(brief, counters) + parts = [f"{live} worker{'s' if live != 1 else ''} live of " + f"{_brief.cap_of(brief, 'max-workers')}", + f"{values['merges']} merged of merge-cap {_value(brief, 'merge-cap')}", + f"tokens {values['tokens']}"] + if counters.get("paused"): + parts.append(f"PAUSED by {counters['paused'].get('by', '?')}") + return ", ".join(parts) + + +def _render_event(e: dict, as_json: bool) -> str: + if as_json: + return json.dumps(e, sort_keys=True, ensure_ascii=False) + return f"{_events._hhmm(e.get('at') or '')} " + ("NEEDS YOU: " if e.get("needs_you") else "") \ + + str(e.get("line") or "") + + +class _Tail: + """`events.jsonl`, read from a byte offset: complete lines only, so a + line still being written is read on the next poll.""" + + def __init__(self, path: Path): + self.path, self.offset = Path(path), 0 + + def read(self) -> list[dict]: + try: + with open(self.path, "rb") as fh: + fh.seek(self.offset) + data = fh.read() + except OSError: + return [] + end = data.rfind(b"\n") + if end < 0: + return [] + self.offset += end + 1 + out = [] + for raw in data[:end].split(b"\n"): + try: + e = json.loads(raw) + except ValueError: + continue + if isinstance(e, dict) and isinstance(e.get("seq"), int): + out.append(e) + return out + + +def stream(record: Path, slot: Path, *, from_seq: int | None = None, + for_min: float | None = None, as_json: bool = False, check: bool = False, + out=None, err=None, clock=None, sleep=time.sleep, + poll_s: float = STREAM_POLL_S) -> int: + """`batch watch --stream`: the shift's events as they land, one line each. + + Refuses (exit 2, one line on stderr) outside the watch window, with `STOP` + present, or once `shift-end` is written; `check` stops there (exit 0: + attachable now). Then `attached : `, the last + `CATCH_UP` events (or every one after `from_seq`), and each new one as + `HH:MMZ ` (`NEEDS YOU: ` first when it needs the human; the raw + object with `as_json`). Exit 0 on `shift-end` (or `/stop`'s `stopped`), on + a hand-written `STOP`, or when the window closes; exit 3 after `for_min` + minutes, with `segment-end next=--from ` — the one exit after which + the cockpit attaches again.""" + out, err = out or sys.stdout, err or sys.stderr + clock = clock or (lambda: _dt.datetime.now(_dt.timezone.utc)) + record, slot = Path(record), Path(slot) + began = clock() + ok, why = attachable(record, slot, began) + if not ok: + err.write(f"batch watch --stream: {why}\n") + return RC_REFUSED + if check: + out.write(f"attachable: {slot.name} ({slot})\n") + return RC_DONE + _start, end = _window(record) + closes = end + _dt.timedelta(seconds=LATE_WINDOW_S) + tail = _Tail(slot / _events.EVENTS_FILE) + first = tail.read() + last = max((e["seq"] for e in first), default=0) + shown = [e for e in first if e["seq"] > from_seq] if from_seq is not None \ + else first[-CATCH_UP:] + if from_seq is not None: + last = max(last, from_seq) + lines = [f"attached {slot.name}: {attach_summary(record, slot)}"] + lines += [_render_event(e, as_json) for e in shown] + out.write("\n".join(lines) + "\n") + out.flush() + if any(e.get("kind") in _events.FINAL_KINDS for e in shown): + return RC_DONE + stop_seen = any(e.get("kind") == "stopped" for e in first) + while True: + new = tail.read() + if new: + last = max(last, max(e["seq"] for e in new)) + out.write("\n".join(_render_event(e, as_json) for e in new) + "\n") + out.flush() + if any(e.get("kind") in _events.FINAL_KINDS for e in new): + return RC_DONE + now = clock() + if (slot / _orchestrator.STOP_FILE).exists() and not stop_seen: + out.write(f"{now:%H:%M}Z STOP file present: the watcher does nothing. " + "Watch ended.\n") + out.flush() + return RC_DONE + if now > closes: + out.write(f"{now:%H:%M}Z Watch window over (review-at + 45 min). " + "Run /prm or read the digest.\n") + out.flush() + return RC_DONE + if for_min is not None and (now - began).total_seconds() >= for_min * 60: + out.write(f"segment-end next=--from {last}\n") + out.flush() + return RC_SEGMENT + sleep(poll_s) diff --git a/tests/fixtures/shift_2026-11-14-pm3/counters.json b/tests/fixtures/shift_2026-11-14-pm3/counters.json new file mode 100644 index 00000000..d6cd42fc --- /dev/null +++ b/tests/fixtures/shift_2026-11-14-pm3/counters.json @@ -0,0 +1,116 @@ +{ + "closeouts": { + "https://github.com/PyAutoLabs/PyAutoGalaxy/pull/716": { + "github": { + "mergedAt": "", + "mergedBy": "", + "state": "OPEN" + }, + "started": "2026-11-14T20:29:47Z", + "state": "refused", + "task": "plot_rst_missing_exports", + "why": "PR carries the decision-taken label (docstring |mu| fixes in galaxies_plots.py / fit_interferometer_plots.py added beyond the plot.rst-only plan); merge is human /prm" + }, + "https://github.com/PyAutoLabs/PyAutoLens/pull/863": { + "github": { + "mergedAt": "", + "mergedBy": "", + "state": "OPEN" + }, + "started": "2026-11-14T20:32:54Z", + "state": "refused", + "task": "plot_rst_missing_exports", + "why": "PR carries the decision-taken label, and Witness clause 2 fails on the head (subplot_fit_interferometer_tracer is not under Dataset Subplots); clause 3 depends on PyAutoGalaxy#716, which is still open" + } + }, + "commands": [ + { + "ack": "dropped `markdown_regeneration_sigma_min`: it had already finished; its PR is never merged unattended", + "at": "2026-11-14T20:21:04Z", + "by": "Jammy2211", + "command": "/drop markdown_regeneration_sigma_min", + "id": "6883652146", + "url": "https://github.com/PyAutoLabs/PyAutoMind/issues/571#issuecomment-6883652146" + } + ], + "done": [ + "model_bullet_parameter_count_drift", + "markdown_regeneration_sigma_min", + "plot_rst_missing_exports" + ], + "dropped": { + "markdown_regeneration_sigma_min": { + "at": "2026-11-14T20:21:04Z", + "by": "Jammy2211" + } + }, + "glance_auto_merges": 0, + "outcomes": { + "markdown_regeneration_sigma_min": { + "issues": [ + "https://github.com/PyAutoLabs/autolens_workspace/issues/669" + ], + "merged": [], + "prs": [], + "questions": [ + "https://github.com/PyAutoLabs/autolens_workspace/issues/669" + ] + }, + "model_bullet_parameter_count_drift": { + "issues": [ + "https://github.com/PyAutoLabs/autolens_workspace/issues/672" + ], + "merged": [], + "prs": [], + "questions": [ + "https://github.com/PyAutoLabs/autolens_workspace/issues/672" + ] + }, + "plot_rst_missing_exports": { + "issues": [], + "merged": [], + "prs": [ + "https://github.com/PyAutoLabs/PyAutoGalaxy/pull/716", + "https://github.com/PyAutoLabs/PyAutoLens/pull/863" + ] + } + }, + "parked": [], + "pending_redispatch": [], + "picks": { + "markdown_regeneration_sigma_min": { + "prompt": "draft/docs/autolens_workspace/markdown_regeneration_sigma_min.md", + "repos": [ + "autolens_workspace" + ], + "size": "small", + "tier": "notify", + "title": "Regenerate autolens_workspace markdown/ so the MGE pages show sigma_min", + "why": "scoped tier notify \u00b7 queue.md #7" + }, + "model_bullet_parameter_count_drift": { + "prompt": "draft/docs/workspaces/model_bullet_parameter_count_drift.md", + "repos": [ + "autolens_workspace" + ], + "size": "small", + "tier": "notify", + "title": "autolens_workspace: `__Model__` bullets whose profiles or parameter counts do not match the code", + "why": "named task" + }, + "plot_rst_missing_exports": { + "prompt": "draft/docs/autolens/plot_rst_missing_exports.md", + "repos": [ + "autogalaxy", + "autolens" + ], + "size": "medium", + "tier": "glance", + "title": "`docs/api/plot.rst` omits already-exported plot symbols", + "why": "named task" + } + }, + "redispatched": { + "model_bullet_parameter_count_drift": 1 + } +} \ No newline at end of file diff --git a/tests/fixtures/shift_2026-11-14-pm3/tick.log b/tests/fixtures/shift_2026-11-14-pm3/tick.log new file mode 100644 index 00000000..1d48b84e --- /dev/null +++ b/tests/fixtures/shift_2026-11-14-pm3/tick.log @@ -0,0 +1,23 @@ +{"action": "ticked", "at": "2026-11-14T20:14:14Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": ["model_bullet_parameter_count_drift", "plot_rst_missing_exports"], "reaped": [], "refused": [{"task": "markdown_regeneration_sigma_min", "why": "max-workers 2 reached"}, {"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-workers 2 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-workers 2 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-workers 2 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-workers 2 reached"}, {"task": "jax_zero_contour", "why": "max-workers 2 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-workers 2 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-workers 2 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-workers 2 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-workers 2 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-workers 2 reached"}, {"task": "assistants_regime_extension", "why": "max-workers 2 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-workers 2 reached"}], "spawned": [{"pid": 0, "task": "plot_rst_missing_exports"}, {"pid": 0, "task": "model_bullet_parameter_count_drift"}], "status": {"ledger": {"committed": "2591e30519cf0bdc16ee0a48200edec6527b9c92", "held": [], "ops": 1, "set_aside": [], "skipped": [], "tries": 1}, "status": "created"}} +{"action": "ticked", "at": "2026-11-14T20:17:21Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": "8b5b30a582357a190c167cbe7be1d6f5bc95dc9c", "held": [], "ops": 4, "set_aside": [], "skipped": [], "tries": 1}, "live": ["model_bullet_parameter_count_drift", "plot_rst_missing_exports"], "reaped": [{"event": "dead", "redispatch": "allowed", "task": "model_bullet_parameter_count_drift"}], "refused": [{"task": "markdown_regeneration_sigma_min", "why": "max-workers 2 reached"}, {"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-workers 2 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-workers 2 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-workers 2 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-workers 2 reached"}, {"task": "jax_zero_contour", "why": "max-workers 2 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-workers 2 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-workers 2 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-workers 2 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-workers 2 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-workers 2 reached"}, {"task": "assistants_regime_extension", "why": "max-workers 2 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-workers 2 reached"}], "spawned": [{"pid": 0, "task": "model_bullet_parameter_count_drift"}], "status": {"status": "edited"}} +{"action": "ticked", "at": "2026-11-14T20:20:28Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": "ef2a910ee0346612d9f0e3d54669fe6120aa3a91", "held": [], "ops": 2, "set_aside": [], "skipped": [], "tries": 1}, "live": ["markdown_regeneration_sigma_min", "plot_rst_missing_exports"], "mentions": [{"post": "posted", "retry": 1, "state": "awaiting-input", "task": "model_bullet_parameter_count_drift"}], "reaped": [{"event": "done", "task": "model_bullet_parameter_count_drift"}], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-workers 2 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-workers 2 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-workers 2 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-workers 2 reached"}, {"task": "jax_zero_contour", "why": "max-workers 2 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-workers 2 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-workers 2 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-workers 2 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-workers 2 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-workers 2 reached"}, {"task": "assistants_regime_extension", "why": "max-workers 2 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-workers 2 reached"}], "spawned": [{"pid": 0, "task": "markdown_regeneration_sigma_min"}], "status": {"ledger": {"committed": "1203ce9578ddd34119bb9b70426fdb74679af824", "held": [], "ops": 1, "set_aside": [], "skipped": [], "tries": 1}, "status": "edited"}} +{"action": "ticked", "at": "2026-11-14T20:23:34Z", "closeouts": {"merged": [], "refused": [], "started": []}, "commands": [{"ack": "dropped `markdown_regeneration_sigma_min`: it had already finished; its PR is never merged unattended", "arg": "markdown_regeneration_sigma_min", "command": "drop"}], "ledger": {"committed": "a86752930621de85e590854fed239ab5f2449d19", "held": [], "ops": 4, "set_aside": [], "skipped": [], "tries": 1}, "live": ["plot_rst_missing_exports"], "mentions": [{"post": "posted", "retry": 1, "state": "awaiting-input", "task": "markdown_regeneration_sigma_min"}], "reaped": [{"event": "done", "task": "markdown_regeneration_sigma_min"}], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"ledger": {"committed": "f4bfc5c5bcf04f5019a47061a8aa0be19c483cba", "held": [], "ops": 1, "set_aside": [], "skipped": [], "tries": 1}, "status": "edited"}} +{"action": "ticked", "at": "2026-11-14T20:26:41Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": "8d2caa83fdb15ddbe6351f252e2e395794959537", "held": [], "ops": 2, "set_aside": [], "skipped": [], "tries": 1}, "live": ["plot_rst_missing_exports"], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "ticked", "at": "2026-11-14T20:29:47Z", "closeouts": {"merged": [], "refused": [], "started": ["https://github.com/PyAutoLabs/PyAutoGalaxy/pull/716"]}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [{"event": "done", "task": "plot_rst_missing_exports"}], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"ledger": {"committed": "9efb0f46294f2160f7d2f2ff608bed32dd35cee2", "held": [], "ops": 1, "set_aside": [], "skipped": [], "tries": 1}, "status": "edited"}} +{"action": "ticked", "at": "2026-11-14T20:32:54Z", "closeouts": {"merged": [], "refused": ["https://github.com/PyAutoLabs/PyAutoGalaxy/pull/716"], "started": ["https://github.com/PyAutoLabs/PyAutoLens/pull/863"]}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "edited"}} +{"action": "ticked", "at": "2026-11-14T20:36:00Z", "closeouts": {"merged": [], "refused": ["https://github.com/PyAutoLabs/PyAutoLens/pull/863"], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "edited"}} +{"action": "ticked", "at": "2026-11-14T20:39:07Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "ticked", "at": "2026-11-14T20:42:14Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "ticked", "at": "2026-11-14T20:45:20Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "ticked", "at": "2026-11-14T20:48:27Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "edited"}} +{"action": "ticked", "at": "2026-11-14T20:51:33Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "ticked", "at": "2026-11-14T20:54:40Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "ticked", "at": "2026-11-14T20:57:47Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "ticked", "at": "2026-11-14T21:00:54Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "edited"}} +{"action": "ticked", "at": "2026-11-14T21:04:02Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "ticked", "at": "2026-11-14T21:07:08Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "ticked", "at": "2026-11-14T21:10:16Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "ticked", "at": "2026-11-14T21:13:22Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "edited"}} +{"action": "ticked", "at": "2026-11-14T21:16:29Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "ticked", "at": "2026-11-14T21:19:37Z", "closeouts": {"merged": [], "refused": [], "started": []}, "ledger": {"committed": null, "ops": 0}, "live": [], "reaped": [], "refused": [{"task": "sparse_inversion_ignores_profile_subtracted_image", "why": "max-sessions 4 reached"}, {"task": "demo_subplot_ellipse_errors", "why": "max-sessions 4 reached"}, {"task": "seed_samplers_for_byte_stable_rerenders", "why": "max-sessions 4 reached"}, {"task": "remove_eden_packaging_tooling", "why": "max-sessions 4 reached"}, {"task": "jax_zero_contour", "why": "max-sessions 4 reached"}, {"task": "slam_simultaneous_subhalo_grid_search_fits_last", "why": "max-sessions 4 reached"}, {"task": "upstream_dr1_final_catalogue_tooling", "why": "max-sessions 4 reached"}, {"task": "release_validation_check_howto_stored_fit_result", "why": "max-sessions 4 reached"}, {"task": "cluster_pixelized_analysisfactor", "why": "max-sessions 4 reached"}, {"task": "cluster_mass_parameterizations_print_and_draw_every_model", "why": "max-sessions 4 reached"}, {"task": "assistants_regime_extension", "why": "max-sessions 4 reached"}, {"task": "mge_group_dataset_with_real_group_members", "why": "max-sessions 4 reached"}], "spawned": [], "status": {"status": "unchanged"}} +{"action": "digest", "at": "2026-11-14T21:22:43Z", "ledger": {"committed": "1f899becef9ef012b4020b8ead7bdd1bd5f20422", "held": [], "ops": 4, "set_aside": [], "skipped": [], "tries": 1}, "packet": null, "post": {"posted": true, "url": "https://github.com/PyAutoLabs/PyAutoMind/issues/571#issuecomment-6884400207"}, "status": {"status": "edited"}} diff --git a/tests/test_batch_watch_stream.py b/tests/test_batch_watch_stream.py new file mode 100644 index 00000000..85b4364d --- /dev/null +++ b/tests/test_batch_watch_stream.py @@ -0,0 +1,284 @@ +"""PyAutoBrain#644 (M3.4, Build A): `batch watch --stream`, the reader of the +shift's `events.jsonl`. + +It refuses outside the watch window (`dispatched:` − 30 min to `review-at:` + +45 min), with `STOP` present or after `shift-end`; `--check` stops there. It +prints `attached : ` (local reads only), the catch-up, then +each new event, and exits 0 at `shift-end`, a hand-written `STOP` or the +window's end, or 3 after `--for` minutes with `segment-end next=--from N`. +""" + +from __future__ import annotations + +import datetime as _dt +import io +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "tests")) +import test_orchestrator_dispatch as d # noqa: E402 — puts the batch conductor on sys.path +from test_orchestrator_dispatch import orch # noqa: E402 +import _events # noqa: E402 +import _watch # noqa: E402 + +UTC = _dt.timezone.utc +DISPATCHED = _dt.datetime(2026, 11, 16, 17, 0, tzinfo=UTC) +REVIEW_AT = _dt.datetime(2026, 11, 16, 19, 0, tzinfo=UTC) + +RECORD = """\ +# Batch 2026-11-16 pm +- dispatched: {d} +- review-at: {r} +- issue: https://github.com/example-org/example-mind/issues/1 +- brief: + - goals: + - 1. a shift + - tasks: + - draft/feature/pyautobrain/t1.md + - backlog: none + - review-minutes: 45 + - lanes: any + - merge-cap: 2 + - token-budget: 400000 +""" + + +def _iso(t): + return t.strftime("%Y-%m-%dT%H:%MZ") + + +def _setup(tmp_path, dispatched=DISPATCHED, review_at=REVIEW_AT, counters=True): + record = tmp_path / "2026-11-16-pm.md" + record.write_text(RECORD.format(d=_iso(dispatched), r=_iso(review_at))) + slot = tmp_path / "home" / "2026-11-16-pm" + slot.mkdir(parents=True) + if counters: + c = orch.read_counters(slot) + pr = "https://github.com/o/r/pull/1" + c.update(sessions=1, glance_auto_merges=1, outcomes={"t0": {"prs": [pr], "merged": [pr]}}) + orch._write_counters(slot, c) + (slot / "leases").mkdir() + (slot / "leases" / "t1.json").write_text(json.dumps({"task": "t1", "agent_id": "abcd1234"})) + return record, slot + + +def _emit(slot, minutes, result, **kw): + return _events.record_tick(slot, DISPATCHED + _dt.timedelta(minutes=minutes), result, + {"picks": {}, "outcomes": {}, "closeouts": {}, "dropped": {}}, + info={"review_at": _iso(REVIEW_AT), "merge_cap": 2}, **kw) + + +class Clock: + """A clock that moves `step` minutes each time it is read.""" + + def __init__(self, start, step=1.0): + self.t, self.step = start, _dt.timedelta(minutes=step) + + def __call__(self): + now = self.t + self.t += self.step + return now + + +def _run(record, slot, clock, *, on_sleep=None, **kw): + out, err = io.StringIO(), io.StringIO() + polls = [] + + def sleep(s): + polls.append(s) + if on_sleep: + on_sleep(len(polls)) + if len(polls) > 500: + raise AssertionError("the stream never ended") + rc = _watch.stream(record, slot, out=out, err=err, clock=clock, sleep=sleep, **kw) + return rc, out.getvalue(), err.getvalue(), polls + + +# --- refusals and --check ----------------------------------------------------------- + +@pytest.mark.parametrize("now,why", [ + (DISPATCHED - _dt.timedelta(minutes=31), "not open yet: attach from 16:30Z"), + (REVIEW_AT + _dt.timedelta(minutes=46), "watch window is over"), +]) +def test_it_refuses_outside_the_window(tmp_path, now, why): + record, slot = _setup(tmp_path) + for check in (False, True): + rc, out, err, _ = _run(record, slot, Clock(now), check=check) + assert rc == 2 and out == "" and why in err + + +def test_check_says_attachable_inside_the_window_at_both_edges(tmp_path): + record, slot = _setup(tmp_path) + for now in (DISPATCHED - _dt.timedelta(minutes=29), DISPATCHED + _dt.timedelta(minutes=50), + REVIEW_AT + _dt.timedelta(minutes=44)): + rc, out, err, polls = _run(record, slot, Clock(now), check=True) + assert (rc, err, polls) == (0, "", []) and out == f"attachable: {slot.name} ({slot})\n" + + +def test_it_refuses_with_stop_present_or_after_shift_end(tmp_path): + record, slot = _setup(tmp_path) + (slot / orch.STOP_FILE).write_text("by hand\n") + rc, _, err, _ = _run(record, slot, Clock(DISPATCHED), check=True) + assert rc == 2 and "STOP present" in err + (slot / orch.STOP_FILE).unlink() + _emit(slot, 120, {"action": "digest", "post": {"posted": True, "url": "u"}}, quiet=True) + rc, _, err, _ = _run(record, slot, Clock(REVIEW_AT + _dt.timedelta(minutes=5))) + assert rc == 2 and "is over (shift-end written)" in err + + +# --- attach, catch-up, follow, every exit --------------------------------------------- + +def test_attach_summary_makes_no_network_read(tmp_path, monkeypatch): + record, slot = _setup(tmp_path) + + def boom(*a, **k): + raise AssertionError("the attach summary made a network read") + monkeypatch.setattr(orch, "AgentsView", boom) + monkeypatch.setattr(_watch._digest, "pr_health", boom) + monkeypatch.setattr(subprocess, "run", boom) + monkeypatch.setattr(subprocess, "Popen", boom) + line = _watch.attach_summary(record, slot) + assert line == "1 worker live of 2, 1 merged of merge-cap 2, tokens 0 of 400000" + rc, out, _, _ = _run(record, slot, Clock(DISPATCHED), check=False, for_min=0) + assert rc == 3 and out.startswith(f"attached {slot.name}: 1 worker live of 2") + + +def test_it_catches_up_follows_and_exits_at_shift_end(tmp_path): + record, slot = _setup(tmp_path) + for m in range(7): + _emit(slot, m, {"action": "ticked", "spawned": [{"task": f"t{m}"}]}) + + def watcher(poll): + if poll == 1: + _emit(slot, 30, {"action": "ticked", "commands": [ + {"command": "cap", "arg": "merges x", "ack": "ignored: /cap needs a whole number", + "id": "5", "by": "example-human"}]}) + if poll == 3: + _emit(slot, 120, {"action": "digest", "post": {"posted": True, "url": "https://x/1"}}, + quiet=True) + rc, out, _, polls = _run(record, slot, Clock(DISPATCHED + _dt.timedelta(minutes=10)), + on_sleep=watcher) + lines = out.splitlines() + assert rc == 0 and len(polls) == 3 + assert lines[0].startswith(f"attached {slot.name}: ") + # The catch-up: the last 5 of 8 events (shift-open + 7 spawns). + assert lines[1:6] == ["17:02Z Started t2 (?; named in the brief).", + "17:03Z Started t3 (?; named in the brief).", + "17:04Z Started t4 (?; named in the brief).", + "17:05Z Started t5 (?; named in the brief).", + "17:06Z Started t6 (?; named in the brief)."] + assert lines[6] == ("17:30Z NEEDS YOU: /cap merges x from example-human: " + "ignored: /cap needs a whole number") + assert lines[7:] == ["19:00Z Shift closed. Digest: https://x/1.", + "19:00Z Shift 2026-11-16-pm over. Nothing is still running."] + + +def test_from_prints_every_event_after_it_and_json_prints_the_raw_object(tmp_path): + record, slot = _setup(tmp_path) + for m in range(7): + _emit(slot, m, {"action": "ticked", "spawned": [{"task": f"t{m}"}]}) + rc, out, _, _ = _run(record, slot, Clock(DISPATCHED), from_seq=1, for_min=0, as_json=True) + lines = out.splitlines() + assert rc == 3 and [json.loads(x)["seq"] for x in lines[1:-1]] == list(range(2, 9)) + assert lines[-1] == "segment-end next=--from 8" + + +def test_a_segment_ends_after_for_minutes_with_its_next_from(tmp_path): + record, slot = _setup(tmp_path) + _emit(slot, 0, {"action": "ticked", "spawned": [{"task": "t1"}]}) + rc, out, _, polls = _run(record, slot, Clock(DISPATCHED, step=1.0), for_min=28) + assert rc == 3 and out.splitlines()[-1] == "segment-end next=--from 2" + assert len(polls) == 27 and set(polls) == {_watch.STREAM_POLL_S} + + +def test_a_hand_written_stop_ends_the_watch(tmp_path): + record, slot = _setup(tmp_path) + rc, out, _, _ = _run(record, slot, Clock(DISPATCHED), + on_sleep=lambda n: n == 2 and (slot / orch.STOP_FILE).write_text("x")) + assert rc == 0 + assert out.splitlines()[-1] == "17:03Z STOP file present: the watcher does nothing. Watch ended." + + +def test_a_slash_stop_ends_the_watch_on_its_stopped_event(tmp_path): + record, slot = _setup(tmp_path) + + def watcher(n): + if n == 1: + _emit(slot, 5, {"action": "stopped", "reason": "STOP written by /stop"}) + (slot / orch.STOP_FILE).write_text("/stop by example-human\n") + rc, out, _, _ = _run(record, slot, Clock(DISPATCHED), on_sleep=watcher) + assert rc == 0 and out.splitlines()[-1].startswith("17:05Z Stopped by /stop.") + + +def test_the_window_end_ends_the_watch(tmp_path): + record, slot = _setup(tmp_path) + rc, out, _, _ = _run(record, slot, Clock(REVIEW_AT + _dt.timedelta(minutes=40))) + assert rc == 0 and out.splitlines()[-1] == ( + "19:46Z Watch window over (review-at + 45 min). Run /prm or read the digest.") + + +def test_a_torn_last_line_is_printed_only_once_it_is_complete(tmp_path): + record, slot = _setup(tmp_path) + _emit(slot, 0, {"action": "ticked", "spawned": [{"task": "t1"}]}) + events = slot / _events.EVENTS_FILE + whole = json.dumps({"v": 1, "seq": 3, "at": "2026-11-16T17:09:00Z", "slot": slot.name, + "kind": "shift-end", "key": "shift-end", "line": "Shift over.", + "needs_you": False}).encode() + b"\n" + + def watcher(n): + with open(events, "ab") as fh: + fh.write(whole[:20] if n == 1 else whole[20:]) + rc, out, _, polls = _run(record, slot, Clock(DISPATCHED), on_sleep=watcher) + assert rc == 0 and len(polls) == 2 and out.splitlines()[-1] == "17:09Z Shift over." + + +def test_no_tick_yet_is_said_on_attach(tmp_path): + record, slot = _setup(tmp_path, counters=False) + rc, out, _, _ = _run(record, slot, Clock(DISPATCHED), for_min=0) + assert rc == 3 and out.splitlines()[0] == ( + f"attached {slot.name}: no tick yet — the watcher has not run for this brief") + + +# --- the CLI ---------------------------------------------------------------------------- + +def _cli(*args, env=None): + return subprocess.run([str(BRAIN / "bin" / "pyauto-brain"), "batch", "watch", + *args], capture_output=True, text=True, timeout=120, + env={**os.environ, **(env or {})}) + + +def test_the_cli_streams_checks_and_refuses(tmp_path): + now = _dt.datetime.now(UTC).replace(second=0, microsecond=0) + record, slot = _setup(tmp_path, dispatched=now - _dt.timedelta(minutes=10), + review_at=now + _dt.timedelta(minutes=60)) + home = str(slot.parent) + res = _cli("--stream", "--check", "--record", str(record), "--home", home) + assert res.returncode == 0 and res.stdout == f"attachable: {slot.name} ({slot})\n", res.stderr + _events.record_tick(slot, now, {"action": "digest", "post": {"posted": True, "url": "u"}}, + {}, quiet=True) + res = _cli("--stream", "--record", str(record), "--home", home) + assert res.returncode == 2 and "is over (shift-end written)" in res.stderr + res = _cli("--stream", "--check", "x.md", "--record", str(record), "--home", home) + assert res.returncode == 2 and "--check takes no file" in res.stderr + + +def test_the_record_and_home_default_from_the_env_file(tmp_path, monkeypatch): + record, slot = _setup(tmp_path) + env = tmp_path / "orchestrator.env" + env.write_text(f"PYAUTO_SHIFT_BRIEF={record}\nPYAUTO_ORCHESTRATOR_HOME={slot.parent}\n" + "# a comment\nPYAUTO_SHIFT_APP_KEY=/not/read\n") + monkeypatch.setattr(_watch, "ENV_FILE", env) + assert _watch.env_file()["PYAUTO_SHIFT_BRIEF"] == str(record) + import _batch + seen = {} + monkeypatch.setattr(_watch, "stream", lambda record, slot, **kw: seen.update( + record=record, slot=slot, **kw) or 0) + assert _batch.main(["watch", "--stream", "--from", "4", "--for", "28"]) == 0 + assert seen["record"] == record and seen["slot"] == slot + assert seen["from_seq"] == 4 and seen["for_min"] == 28 and seen["check"] is False diff --git a/tests/test_orchestrator_dispatch.py b/tests/test_orchestrator_dispatch.py index be2002ad..9d0adbab 100644 --- a/tests/test_orchestrator_dispatch.py +++ b/tests/test_orchestrator_dispatch.py @@ -625,7 +625,8 @@ def test_an_op_set_aside_after_the_digest_reaches_the_human(tmp_path, monkeypatc assert orch.ledger_unreported(slot) r = orch.tick(brief, canon, now=AFTER + _dt.timedelta(minutes=3), **kw) assert r["action"] == "late" and r["posts"]["correction"] == "posted", r - assert "Mind ledger op set aside" in poster.calls[1][1] + # The correction carries it (#644 adds a needs-you comment for the set-aside op too). + assert any("Mind ledger op set aside" in b for _, b in poster.calls[1:]) record = t.git(bare, "show", "main:batches/2026-11-04-am.md").stdout assert "- late: Mind ledger — warning: Mind ledger op set aside" in record assert not orch.ledger_unreported(slot) diff --git a/tests/test_orchestrator_events.py b/tests/test_orchestrator_events.py new file mode 100644 index 00000000..ac5a2d82 --- /dev/null +++ b/tests/test_orchestrator_events.py @@ -0,0 +1,401 @@ +"""PyAutoBrain#644 (M3.4, Build A): the shift's event stream, `events.jsonl`. + +The watcher appends one JSON line per new event from what each tick already +did (`_events.record_tick`, inside the tick lock): no new reads, no +subprocess, no LLM. These tests hold the schema, the dedup (one `cap` line +for 20 identical refusal ticks; no repeat after a crash between the append +and the state write), every kind, the needs-you comments (human ruling H4b) +and a replay of the real shift B tick log (2026-11-14-pm3). +""" + +from __future__ import annotations + +import datetime as _dt +import json +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +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 orch # noqa: E402 +import _events # noqa: E402 + +NOW = d.NOW +FIXTURE = BRAIN / "tests" / "fixtures" / "shift_2026-11-14-pm3" +PR = "https://github.com/example-org/example-lib/pull/901" +PR2 = "https://github.com/example-org/other-lib/pull/904" +ISSUE = "https://github.com/example-org/example-workspace/issues/670" +INFO = {"review_at": "2026-11-04T11:30Z", "named": 2, "merge_cap": 2, "token_budget": "400000"} + + +def _at(minutes: float) -> _dt.datetime: + return NOW + _dt.timedelta(minutes=minutes) + + +def _slot(tmp_path) -> Path: + slot = tmp_path / "2026-11-04-am" + slot.mkdir() + return slot + + +def _counters(**kw) -> dict: + c = {"picks": {"t1": {"tier": "glance", "why": "named task", "title": "Fix the fixture"}, + "t2": {"tier": "notify", "why": "queue.md #2"}}, + "outcomes": {}, "closeouts": {}, "dropped": {}, "commands": [], "parked": []} + c.update(kw) + return c + + +def _record(slot, minutes, result, counters=None, **kw): + return orch._events.record_tick(slot, _at(minutes), result, + counters if counters is not None else _counters(), + info=INFO, **kw) + + +# --- the schema -------------------------------------------------------------------- + +def test_every_line_has_the_v1_schema_and_seq_has_no_gaps(tmp_path): + slot = _slot(tmp_path) + _record(slot, 0, {"action": "ticked", "spawned": [{"task": "t1"}, {"task": "t2"}], + "refused": [{"task": "t3", "why": "max-workers 2 reached"}]}) + _record(slot, 3, {"action": "ticked", "reaped": [{"task": "t2", "event": "dead", + "redispatch": "allowed"}], + "spawned": [{"task": "t2"}]}) + events = _events.read_events(slot) + assert [e["seq"] for e in events] == list(range(1, len(events) + 1)) + assert [e["kind"] for e in events] == ["shift-open", "spawned", "spawned", "cap", + "crashed", "redispatched"] + for e in events: + assert set(e) >= {"v", "seq", "at", "slot", "kind", "key", "line", "needs_you"} + assert e["v"] == 1 and e["slot"] == "2026-11-04-am" and e["kind"] in _events.KINDS + assert isinstance(e["needs_you"], bool) and len(e["line"]) <= _events.LINE_MAX + raw = (slot / _events.EVENTS_FILE).read_bytes().split(b"\n") + assert raw[-1] == b"" and all(len(x) < _events.RECORD_MAX for x in raw) + assert events[0]["line"] == ("Shift 2026-11-04-am open until 11:30Z: 2 named tasks, " + "merge-cap 2, 400000 token budget.") + assert events[1]["line"] == "Started Fix the fixture (t1) (glance; named task)." + assert events[4]["key"] == "crashed:t2:1" and events[5]["key"] == "redispatched:t2" + + +def test_a_line_never_carries_an_at_sign_and_is_truncated(tmp_path): + slot = _slot(tmp_path) + ack = "ignored: " + "@someone " * 80 + _record(slot, 0, {"action": "ticked", "commands": [ + {"command": "drop", "arg": "x", "ack": ack, "id": "9", "by": "example-human"}]}) + (e,) = [e for e in _events.read_events(slot) if e["kind"] == "steer"] + assert "@s" not in e["line"] and "@​s" in e["line"] + assert len(e["line"]) == _events.LINE_MAX and e["needs_you"] + + +def test_twenty_identical_refusal_ticks_give_one_cap_line(tmp_path): + slot = _slot(tmp_path) + refused = [{"task": f"t{i}", "why": "max-sessions 4 reached"} for i in range(3)] + for m in range(20): + _record(slot, m * 3, {"action": "ticked", "refused": refused}) + caps = [e for e in _events.read_events(slot) if e["kind"] == "cap"] + assert [e["line"] for e in caps] == ["max-sessions 4 reached: 3 tasks wait."] + + +def test_a_task_refusal_is_one_line_per_task_and_class(tmp_path): + slot = _slot(tmp_path) + for m in range(5): + _record(slot, m, {"action": "ticked", "refused": [ + {"task": "t1", "why": "spawn failed: claude --bg failed: boom"}]}) + refusals = [e for e in _events.read_events(slot) if e["kind"] == "refused"] + assert [e["line"] for e in refusals] == ["t1 not started: spawn failed."] + + +def test_a_crash_between_the_append_and_the_state_write_repeats_nothing(tmp_path): + slot = _slot(tmp_path) + first = _record(slot, 0, {"action": "ticked", "spawned": [{"task": "t1"}], + "health": {PR: "HEALTHY"}, + "closeouts": {"started": [PR], "merged": [], "refused": []}}) + # The tick dies after its append, before the state write: the state is lost. + (slot / _events.STATE_FILE).unlink() + # The next tick reads the same CI verdict again: the file's keys dedup it. + again = _record(slot, 3, {"action": "ticked", "health": {PR: "HEALTHY"}}) + assert again == [] and len(_events.read_events(slot)) == len(first) + nxt = _record(slot, 6, {"action": "ticked", "spawned": [{"task": "t2"}]}) + assert [e["seq"] for e in nxt] == [len(first) + 1] # no seq reused + + +def test_a_torn_last_line_is_skipped_and_never_joined(tmp_path): + slot = _slot(tmp_path) + _record(slot, 0, {"action": "ticked", "spawned": [{"task": "t1"}]}) + with open(slot / _events.EVENTS_FILE, "ab") as fh: + fh.write(b'{"v": 1, "seq": 99, "kind": "spaw') # a write cut short + assert [e["seq"] for e in _events.read_events(slot)] == [1, 2] + _record(slot, 1, {"action": "ticked", "spawned": [{"task": "t2"}]}) + assert [e["seq"] for e in _events.read_events(slot)] == [1, 2, 3] + + +def test_record_tick_makes_no_subprocess_or_network_call(tmp_path, monkeypatch): + def boom(*a, **k): + raise AssertionError("record_tick made a subprocess or network call") + for name in ("run", "Popen", "check_output", "call"): + monkeypatch.setattr(subprocess, name, boom) + import socket + monkeypatch.setattr(socket, "socket", boom) + monkeypatch.setattr(orch, "AgentsView", boom) + monkeypatch.setattr(orch._digest, "pr_health", boom) + slot = _slot(tmp_path) + _record(slot, 0, _every_kind_results()[0][1]) + + +# --- every kind --------------------------------------------------------------------- + +def _every_kind_results(): + """(minutes, result, counters) producing every kind once.""" + c = _counters( + outcomes={"t1": {"prs": [PR], "merged": []}, + "t2": {"prs": [], "merged": [], "issues": [ISSUE], "questions": [ISSUE]}, + "t4": {"prs": [], "merged": [], "issues": [], "obsolete": "already on main"}}, + closeouts={PR: {"task": "t1", "state": "merged"}, + PR2: {"task": "t5", "state": "refused", "why": "merged outside the close-out", + "github": {"mergedBy": "someone"}}, + "https://github.com/o/r/pull/3": {"task": "t6", "state": "refused", + "why": "CI FAILED — never merged unattended"}, + "https://github.com/o/r/pull/4": {"task": "t7", "state": "refused", + "why": "merge-cap 2 reached this shift"}}, + dropped={"t5": {"by": "h", "at": "x"}}, commands_unread="2026-11-04T09:00:00Z") + return [ + (0, {"action": "ticked", "spawned": [{"task": "t1"}, {"task": "t2"}, {"task": "t3"}], + "refused": [{"task": "t7", "why": "max-workers 2 reached"}, + {"task": "t9", "why": "spawn failed: no"}], + "commands": [{"command": "cap", "arg": "merges x", "ack": "ignored: /cap needs a " + "whole number", "id": "1", "by": "example-human"}]}, c), + (3, {"action": "ticked", + "reaped": [{"task": "t1", "event": "done"}, {"task": "t2", "event": "done"}, + {"task": "t4", "event": "done"}, + {"task": "t3", "event": "dead", "redispatch": "allowed"}, + {"task": "t8", "event": "parked", "why": "blocked since 2026-11-04T09:01:00Z"}], + "spawned": [{"task": "t3"}], "health": {PR: "HEALTHY", "https://github.com/o/r/pull/3": "FAILED"}, + "closeouts": {"started": [PR], "merged": [], "refused": ["https://github.com/o/r/pull/3"]}, + "github_auth": {"error": "no installation token", "writes": "held"}, + "ledger": {"committed": None, "set_aside": [{"op": "remove", "file": "1.json", + "why": "missing"}]}}, c), + (6, {"action": "ticked", + "closeouts": {"started": [], "merged": [PR], "refused": [PR2, "https://github.com/o/r/pull/4"], + "merged_outside": [PR2]}}, c), + (9, {"action": "ticked"}, c), + (12, {"action": "stopped", "reason": "STOP written by /stop"}, c), + (180, {"action": "digest", "post": {"posted": True, "url": "https://github.com/o/m/issues/1#issuecomment-5"}}, c), + (183, {"action": "late", "late": ["- late: t8 — https://github.com/o/r/pull/7 (after review-at, 2026-11-04T12:33:00Z)"]}, c), + ] + + +def test_every_kind_is_written(tmp_path): + slot = _slot(tmp_path) + runs = _every_kind_results() + for i, (minutes, result, counters) in enumerate(runs): + _record(slot, minutes, result, counters, quiet=i == len(runs) - 1) + events = _events.read_events(slot) + assert {e["kind"] for e in events} == set(_events.KINDS) + by: dict = {} + for e in events: + by.setdefault(e["kind"], e) # the first of each kind + assert by["pr-opened"]["line"] == "t1 opened example-lib#901 (glance: close-out when CI is green)." + assert by["question"]["line"] == "t2 parked with a question on example-workspace#670." + assert by["finished"]["line"] == "t4 finished: Obsolete — nothing to do." + assert by["parked"]["line"] == "t8 is stuck at a prompt (since 09:01Z)." + assert by["merged"]["line"] == "Merged example-lib#901 unattended (1 of merge-cap 2)." + assert by["merged-outside"]["needs_you"] # its task was /dropped + assert [e["line"] for e in events if e["kind"] == "ci"] == [ + "CI green on example-lib#901.", "CI red on r#3: never merged unattended."] + assert by["cap"]["line"] == "max-workers 2 reached: 1 task wait." + assert any(e["line"] == "merge-cap 2 reached: later green PRs wait for /prm." for e in events) + assert by["refused"]["line"] == "t9 not started: spawn failed." + assert by["steer-unread"]["needs_you"] and by["impaired"]["needs_you"] + assert by["steer"]["needs_you"] # an `ignored:` ack + assert by["late"]["line"] == "Late arrival: t8 — https://github.com/o/r/pull/7 after review-at." + assert by["digest"]["url"].endswith("#issuecomment-5") + assert events[-1]["kind"] == "shift-end" + assert not {k for k in ("shift-open", "spawned", "ci", "merged") if by[k]["needs_you"]} + + +def test_shift_end_waits_until_nothing_is_left(tmp_path): + slot = _slot(tmp_path) + _record(slot, 0, {"action": "digest", "post": {"posted": True, "url": "u"}}, quiet=False) + assert [e["kind"] for e in _events.read_events(slot)] == ["digest"] + _record(slot, 5, {"action": "late", "late": []}, quiet=False) + _record(slot, 8, {"action": "late", "late": []}, quiet=True) + assert [e["kind"] for e in _events.read_events(slot)] == ["digest", "shift-end"] + + +def test_steer_unread_needs_three_ticks_in_a_row(tmp_path): + slot = _slot(tmp_path) + unread = _counters(commands_unread="2026-11-04T09:00:00Z") + for m in (0, 3): + _record(slot, m, {"action": "ticked"}, unread) + _record(slot, 6, {"action": "ticked"}, _counters()) # a read worked: the run resets + for m in (9, 12): + _record(slot, m, {"action": "ticked"}, unread) + assert not [e for e in _events.read_events(slot) if e["kind"] == "steer-unread"] + _record(slot, 15, {"action": "ticked"}, unread) + (e,) = [e for e in _events.read_events(slot) if e["kind"] == "steer-unread"] + assert e["needs_you"] and "since 09:00Z" in e["line"] + + +def test_a_kill_is_named_and_a_spent_retry_is_said(tmp_path): + slot = _slot(tmp_path) + _record(slot, 0, {"action": "ticked", "spawned": [{"task": "t1"}]}) + _record(slot, 3, {"action": "ticked", "reaped": [ + {"task": "t1", "event": "dead", "redispatch": "allowed", "killed": True}], + "spawned": [{"task": "t1"}]}) + _record(slot, 6, {"action": "ticked", "reaped": [ + {"task": "t1", "event": "dead", "redispatch": "spent — abandoned"}]}) + lines = [e["line"] for e in _events.read_events(slot) if e["kind"] == "crashed"] + assert lines == ["Worker on t1 stopped by /kill. It restarts once.", + "Worker on t1 died. Retry spent: left for your /prm."] + + +# --- the replay: shift B, 2026-11-14-pm3 --------------------------------------------- + +def test_replay_of_shift_b_gives_the_designed_events_and_a_final_digest(tmp_path): + """The real `tick.log` of shift B (read-only copy; `counters.json` trimmed + to what the lines need) replays to the events of DESIGN §1.3, in order, + then the digest and `shift-end`. Old `done` reaps carry no outcome fields: + the deriver reads the outcome from the counters.""" + counters = json.loads((FIXTURE / "counters.json").read_text()) + log = [json.loads(x) for x in (FIXTURE / "tick.log").read_text().splitlines()] + slot = tmp_path / "2026-11-14-pm3" + slot.mkdir() + for r in log: + now = _dt.datetime.fromisoformat(r["at"].replace("Z", "+00:00")) + _events.record_tick(slot, now, r, counters, quiet=True, + info={"review_at": "2026-11-14T21:20Z", "merge_cap": 2}) + events = _events.read_events(slot) + got = [(e["kind"], e.get("task") or e.get("pr") or "") for e in events] + # Names come from the fixture itself (the tenant firewall: none typed here). + first, second = sorted(counters["closeouts"]) # the two PRs, as the log opened them + (model,) = counters["redispatched"] # killed by hand, re-dispatched + (md,) = counters["dropped"] # dropped by /drop + (plot,) = [t for t, o in counters["outcomes"].items() if o["prs"]] + login = counters["commands"][0]["by"] + assert got == [ + ("shift-open", ""), ("spawned", plot), ("spawned", model), ("cap", ""), + ("crashed", model), ("redispatched", model), + ("question", model), ("spawned", md), + ("question", md), ("steer", ""), ("cap", ""), + ("pr-opened", plot), ("pr-opened", plot), ("closeout-started", plot), + ("refused", plot), ("closeout-started", plot), ("refused", plot), + ("digest", ""), ("shift-end", "")] + by_key = {e["key"]: e for e in events} + crashed = by_key[f"crashed:{model}:1"] + assert crashed["at"] == "2026-11-14T20:17:21Z" and not crashed["needs_you"] + assert crashed["line"] == f"Worker on {model} died. It restarts once." + assert by_key[f"redispatched:{model}"]["line"] == f"Restarted {model} (its one retry)." + refused = by_key[f"refused:{first}"] + assert refused["at"] == "2026-11-14T20:32:54Z" and refused["cls"] == "decision-taken label" + assert refused["line"] == (f"Not merging {_events.ref(first)}: decision-taken label. " + "Left for your /prm.") + assert by_key[f"refused:{second}"]["cls"] == "decision-taken label" + assert by_key["cap:max-workers 2 reached"]["line"] == "max-workers 2 reached: 13 tasks wait." + assert by_key["cap:max-sessions 4 reached"]["line"] == "max-sessions 4 reached: 12 tasks wait." + steer = next(e for e in events if e["kind"] == "steer") + assert steer["line"].startswith(f"/drop {md} from {login}: dropped") and not steer["needs_you"] + assert by_key["digest"]["line"] == (f"Shift closed. Digest: {log[-1]['post']['url']}. " + "2 tasks parked on a question.") + # 20 ticks refused the same tasks: one cap line per class, nothing more. + assert sum(e["kind"] == "cap" for e in events) == 2 + + +# --- the watcher writes it, inside the lock ----------------------------------------------- + +def test_a_tick_writes_its_events_and_a_quiet_tick_writes_none(tmp_path): + mind, brief, home = d._shift(tmp_path) + slot = orch.slot_dir(brief, home) + claude = d.FakeClaude() + d._tick(brief, mind, home, NOW, claude) + kinds = [e["kind"] for e in _events.read_events(slot)] + assert kinds == ["shift-open", "spawned"] + d._tick(brief, mind, home, _at(3), claude, agents=d._agents({"t1": "working"}, slot)) + assert [e["kind"] for e in _events.read_events(slot)] == kinds # nothing new happened + assert (slot / _events.STATE_FILE).is_file() + + +def test_the_stop_kill_switch_tick_writes_nothing(tmp_path): + mind, brief, home = d._shift(tmp_path) + slot = orch.slot_dir(brief, home) + slot.mkdir(parents=True) + (slot / orch.STOP_FILE).write_text("by hand\n") + assert d._tick(brief, mind, home, NOW, d.FakeClaude())["action"] == "stopped" + assert not (slot / _events.EVENTS_FILE).exists() + + +def test_a_failing_deriver_never_fails_the_tick(tmp_path, monkeypatch, capsys): + mind, brief, home = d._shift(tmp_path) + monkeypatch.setattr(orch._events, "record_tick", + lambda *a, **k: (_ for _ in ()).throw(ValueError("bad"))) + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert r["action"] == "ticked" and [s["task"] for s in r["spawned"]] == ["t1"] + assert "events not recorded this tick (bad)" in capsys.readouterr().err + + +# --- needs-you comments (human ruling H4b) -------------------------------------------------- + +class Poster: + def __init__(self): + self.calls = [] + + def __call__(self, issue, body_file): + self.calls.append((issue, Path(body_file).read_text())) + return {"posted": True, "url": f"{issue}#issuecomment-{len(self.calls)}"} + + +def test_needs_you_events_post_at_most_five_comments_and_one_overflow(tmp_path): + slot = _slot(tmp_path) + (slot / "counters.json").write_text(json.dumps({})) + poster = Poster() + issue = "https://github.com/o/m/issues/1" + events = [{"seq": i, "kind": "steer", "line": f"/cap from x: ignored: {i} @you", + "needs_you": True} for i in range(1, 8)] + events.insert(2, {"seq": 50, "kind": "spawned", "line": "Started t1.", "needs_you": False}) + out = orch._event_comments(slot, events, issue, poster, NOW) + assert len(poster.calls) == 6 and len(out) == 6 + assert all("@you" not in body for _, body in poster.calls) + assert "further needs-you events are in the status comment" in poster.calls[-1][1] + assert "needs you: /cap from x: ignored: 1" in poster.calls[0][1] + assert orch.read_counters(slot)["pushes"] == 6 + # Later ticks post nothing more: the overflow comment was the last. + more = [{"seq": 90, "kind": "impaired", "line": "x", "needs_you": True}] + assert orch._event_comments(slot, more, issue, poster, NOW) == [] and len(poster.calls) == 6 + + +def test_no_needs_you_comment_without_an_issue_or_under_stop(tmp_path): + slot = _slot(tmp_path) + poster = Poster() + e = [{"seq": 1, "kind": "impaired", "line": "x", "needs_you": True}] + assert orch._event_comments(slot, e, "", poster, NOW) == [] + (slot / orch.STOP_FILE).write_text("x") + assert orch._event_comments(slot, e, "https://github.com/o/m/issues/1", poster, NOW) == [] + assert poster.calls == [] + + +def test_a_failed_needs_you_comment_is_retried_with_the_mentions(tmp_path): + slot = _slot(tmp_path) + (slot / "counters.json").write_text(json.dumps({})) + fails = {"n": 1} + + def poster(issue, body_file): + if fails["n"]: + fails["n"] -= 1 + return {"posted": False, "retry": True, "error": "HTTP 502"} + return {"posted": True, "url": issue + "#issuecomment-2"} + e = [{"seq": 4, "kind": "impaired", "line": "x", "needs_you": True}] + orch._event_comments(slot, e, "https://github.com/o/m/issues/1", poster, NOW) + assert orch.mentions_due(slot) + c = orch.read_counters(slot) + orch._retry_mentions(slot, c, poster, NOW) + assert not orch.mentions_due(slot) and c["pushes"] == 1 + + +def test_fixture_is_the_real_shift_b_log(): + lines = (FIXTURE / "tick.log").read_text().splitlines() + assert len(lines) == 23 and json.loads(lines[-1])["action"] == "digest" + assert shutil.which("python3") diff --git a/tests/test_orchestrator_mentions.py b/tests/test_orchestrator_mentions.py index fcaad374..0e239b3d 100644 --- a/tests/test_orchestrator_mentions.py +++ b/tests/test_orchestrator_mentions.py @@ -24,6 +24,14 @@ PAST_GRACE = NOW + _dt.timedelta(minutes=1, seconds=orch.STALL_GRACE_S) +@pytest.fixture(autouse=True) +def _issue_reads_answer(monkeypatch): + """The shift issue's comments read answers "no comments" — these tests are + about mentions, not steering, and never reach GitHub. A read that failed + three ticks in a row would be its own needs-you event (#644).""" + monkeypatch.setattr(orch, "gh_issue_comments", lambda issue, since, run=None: []) + + class FakeGh: """`gh issue comment`: records argv and the body; fails the first `fail` calls.""" diff --git a/tests/test_orchestrator_steering.py b/tests/test_orchestrator_steering.py index d5dc97f7..bfe5d1e7 100644 --- a/tests/test_orchestrator_steering.py +++ b/tests/test_orchestrator_steering.py @@ -10,12 +10,15 @@ import datetime as _dt import json +import os import subprocess import sys from urllib.parse import parse_qs, urlparse from pathlib import Path from types import SimpleNamespace +import pytest + BRAIN = Path(__file__).resolve().parents[1] sys.path.insert(0, str(BRAIN / "tests")) import test_orchestrator_dispatch as d # noqa: E402 — the 3b fixtures @@ -497,3 +500,360 @@ def test_a_create_that_timed_out_after_landing_is_adopted_not_reposted(tmp_path, _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" + + +# --- `/cap`, `/add`, `/kill` (PyAutoBrain#644; human rulings H5, H6, H8) ------------------ +# +# Each test below fails on the code before #644: there the comment is not a +# command at all (`_COMMAND_RE` knew four verbs), so no ack is recorded. + +def _acks(slot) -> dict[str, str]: + return {c["command"]: c["ack"] for c in orch.read_counters(slot)["commands"]} + + +def test_the_new_verbs_parse_and_the_old_ones_take_one_argument_as_before(): + assert orch._parse_command("/cap merges 1\n(said in the cockpit)") == ("cap", "merges 1") + assert orch._parse_command("/add draft/feature/x/y.md") == ("add", "draft/feature/x/y.md") + assert orch._parse_command("/kill `t1`") == ("kill", "t1") + assert orch._parse_command("/drop a b") is None and orch._parse_command("/caps 1") is None + assert orch._parse_command("/cap merges 1 2") is None + + +def _merge_cap(n: int): + return lambda text: text.replace(" - merge-cap: 0\n", f" - merge-cap: {n}\n") + + +def _cap_shift(tmp_path, monkeypatch, names=("t1",), merge_cap=2): + mind, brief, home, slot = _shift(tmp_path, monkeypatch, names=names) + brief.write_text(_merge_cap(merge_cap)(brief.read_text())) + return mind, brief, home, slot + + +@pytest.mark.parametrize("comment,ack", [ + ("/cap", "ignored: /cap takes merges, workers, sessions or tokens"), + ("/cap budget 3", "ignored: /cap takes merges, workers, sessions or tokens"), + ("/cap merges many", "ignored: /cap needs a whole number"), + ("/cap workers 1.5k", "ignored: /cap needs a whole number"), + ("/cap merges 3", "refused: /cap merges 3 is above this brief's merge-cap 2. " + "A higher cap needs a new brief."), + ("/cap tokens 1.2M", "refused: /cap tokens 1.2M is above this brief's token-budget 100000. " + "A higher cap needs a new brief."), + ("/cap sessions 7", "refused: /cap sessions 7 is above this brief's max-sessions 6. " + "A higher cap needs a new brief."), +]) +def test_cap_ignored_and_refused_acks_change_nothing(tmp_path, monkeypatch, comment, ack): + mind, brief, home, slot = _cap_shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + gh.add(LOGIN, comment, -5) + r = _tick(brief, mind, home, 0, claude, gh) + assert r["commands"][0]["ack"] == ack + assert "caps" not in orch.read_counters(slot) and _spawned(claude) == ["shift:t1"] + + +def test_cap_merges_binds_the_close_out_gate_on_the_tick_that_reads_it(tmp_path, monkeypatch): + mind, brief, home, slot = _cap_shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + pr = "https://github.com/example-org/example-repo/pull/7" + (slot / "leases" / "t1.done").write_text(pr + "\n") + gh.add(LOGIN, "/cap merges 0", 2) + r = _tick(brief, mind, home, 3, claude, gh, {"t1": "done"}, health="HEALTHY") + assert r["commands"][0]["ack"] == ("merge-cap now 0 of this brief's 2 (0 merged so far): " + "no new close-out starts.") + c = orch.read_counters(slot) + assert c["closeouts"][pr] == {"task": "t1", "state": "refused", + "why": "merge-cap 0 reached this shift"} + assert c["caps"]["merge-cap"] | {"at": "x"} == {"value": 0, "by": LOGIN, "at": "x", + "was": 2, "brief": 2} + assert "- merges: 0 of 0 (0 unattended)" in gh.status()[0]["body"] + digest = orch._digest.build(orch._brief.effective( + orch._brief.parse(brief.read_text())["brief"], c), slot, c, health=lambda u: "HEALTHY") + assert "- cap override: merge-cap 2 → 0 (/cap by example-human at 09:02Z)" in digest + + +def test_cap_workers_holds_new_spawns_and_never_stops_a_running_worker(tmp_path, monkeypatch): + mind, brief, home, slot = _cap_shift(tmp_path, monkeypatch, names=("t1", "t2", "t3")) + claude, gh = d.FakeClaude(), FakeGitHub() + gh.add(LOGIN, "/cap workers 1", -5) + r = _tick(brief, mind, home, 0, claude, gh) + assert r["commands"][0]["ack"] == "max-workers now 1 of 2." + assert _spawned(claude) == ["shift:t1"] + assert {x["why"] for x in r["refused"]} == {"max-workers 1 reached"} + gh.add(LOGIN, "/cap workers 0", 1) + r = _tick(brief, mind, home, 2, claude, gh, {"t1": "working"}) + assert r["commands"][0]["ack"] == ("max-workers now 0 of 2. 1 still running are not " + "stopped; no new spawn until fewer than 0.") + assert r["live"] == ["t1"] # never killed + gh.add(LOGIN, "/cap workers 2", 3) # raised back to the brief's + r = _tick(brief, mind, home, 4, claude, gh, {"t1": "working"}) + assert r["commands"][0]["ack"] == "max-workers now 2 of 2." + assert _spawned(claude) == ["shift:t1", "shift:t2"] + + +def test_cap_sessions_holds_new_spawns(tmp_path, monkeypatch): + mind, brief, home, slot = _cap_shift(tmp_path, monkeypatch, names=("t1", "t2")) + claude, gh = d.FakeClaude(), FakeGitHub() + gh.add(LOGIN, "/cap sessions 1", -5) + r = _tick(brief, mind, home, 0, claude, gh) + assert r["commands"][0]["ack"] == "max-sessions now 1 of 6 (0 started)." + assert _spawned(claude) == ["shift:t1"] and r["refused"] == [ + {"task": "t2", "why": "max-sessions 1 reached"}] + + +def test_cap_tokens_takes_k_and_m_and_lowers_the_spawn_budget(tmp_path, monkeypatch): + mind, brief, home, slot = _cap_shift(tmp_path, monkeypatch, names=("t1", "t2")) + claude, gh = d.FakeClaude(), FakeGitHub() + gh.add(LOGIN, "/cap tokens 0.01k", -5) + gh.now = _at(0) + r = orch.tick(brief, mind, home=home, now=_at(0), grace_s=0, token_reserve=50, + spawner=orch.RealSpawner(brief, "auto", run=claude), + agents=orch.AgentsView([]), tokens=lambda s: 0, github=gh, + whoami=lambda: BOT, poster=lambda i, b: {"posted": False, "retry": False}) + assert r["commands"][0]["ack"] == "token-budget now 10 of 100000 (0 committed)." + assert _spawned(claude) == [] and all(x["why"].startswith("token-budget 10:") + for x in r["refused"]) + assert orch.read_counters(slot)["token_budget"] == 100000 # the brief's own, for estimates + assert "- tokens: 0 of 10" in gh.status()[0]["body"] + + +# /add: a draft filed mid-shift, on Mind origin/main only. + +ADD_PROMPT = """\ +# {name} + +Type: feature +Target: {target} +Repos: +- {target} +Difficulty: small +Autonomy: supervised +Priority: normal +Status: formalised +Consequence: glance +Witness: a unit test +Review-minutes: 3 +Unattended: ready +{lane} +Body. +""" + + +def _add_shift(tmp_path, monkeypatch, drafts=(), active="", brief_edit=None): + """A git-backed shift (`t1` named) whose Mind origin/main gains `drafts` + — (path, target, lane) — from another clone after the first tick, so only + `/add`'s own fetch can see them.""" + monkeypatch.setenv(orch.MENTION_ENV, LOGIN) + t, bare, canon, brief, home = d._git_shift(tmp_path, monkeypatch) + text = brief.read_text().replace( + "- review-at: 2026-11-04T11:30Z\n", f"- review-at: 2026-11-04T11:30Z\n- issue: {ISSUE}\n") + brief.write_text(brief_edit(text) if brief_edit else text) + + def publish(): + other = tmp_path / "other" + t.git(tmp_path, "clone", "-q", str(bare), str(other)) + t.git(other, "config", "user.name", "Test") + t.git(other, "config", "user.email", "test@example.invalid") + for rel, target, lane in drafts: + f = other / rel + f.parent.mkdir(parents=True, exist_ok=True) + f.write_text(ADD_PROMPT.format(name=Path(rel).stem, target=target, + lane=f"Lane: {lane}\n" if lane else "")) + if active: + (other / "active.md").write_text((other / "active.md").read_text() + active) + t.git(other, "add", "-A") + t.git(other, "commit", "-q", "-m", "filed mid-shift") + t.git(other, "push", "-q", "origin", "HEAD:main") + return canon, brief, home, orch.slot_dir(brief, home), publish + + +#: A library repo from the body map (never typed: the tenant firewall). +import _batch # noqa: E402 +LIB = max(r for r in _batch.LIBRARY_REPOS if not _batch.self_organ_why({"target": r})) +X = f"draft/feature/{LIB}/x.md" + + +def test_add_makes_a_draft_filed_mid_shift_a_named_task_and_starts_it(tmp_path, monkeypatch): + mind, brief, home, slot, publish = _add_shift( + tmp_path, monkeypatch, drafts=[(X, LIB, "local-dev")]) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + publish() + assert not (mind / X).exists() # never pulled into the checkout + gh.add(LOGIN, "/add x\n(said in the cockpit: \"also do x\")", 1) + r = _tick(brief, mind, home, 2, claude, gh, {"t1": "working"}) + assert r["commands"][0]["ack"] == ("added x (glance): starts this tick; " + "max-workers 2, 1 running.") + assert _spawned(claude) == ["shift:t1", "shift:x"] + c = orch.read_counters(slot) + assert c["added"]["x"]["prompt"] == X and c["picks"]["x"]["prompt"] == X + assert (slot / "added" / "x.md").read_text().startswith("# x") + assert "- **Still running** — x" in gh.status()[0]["body"] + snap = _watch.snapshot(brief, slot, _at(3), agents=orch.AgentsView([]), + health=lambda u: "RUNNING") + assert {r["task"]: r["why"] for r in snap["tasks"]}["x"] == "added by /add" + + +@pytest.mark.parametrize("case,drafts,arg,ack", [ + ("not on origin", [], "nothere", + "ignored: no prompt nothere.md on Mind origin/main (filed? pushed?)"), + ("not on origin by path", [], f"draft/feature/{LIB}/nothere.md", + f"ignored: no prompt draft/feature/{LIB}/nothere.md on Mind origin/main (filed? pushed?)"), + ("two drafts", [(X, LIB, "local-dev"), + (f"draft/bug/{LIB}/x.md", LIB, "local-dev")], "x", + "ignored: x.md names 2 drafts: give the path"), + ("already named", [], "t1", "ignored: t1 is already in this shift (running)"), + ("no lane", [(X, LIB, None)], "x", + "refused: x: no Lane: line (lane absent — unattended picks fail closed; declare a Lane)"), + ("organ", [("draft/feature/pyautomind/x.md", "PyAutoMind", "local-dev")], "x", + "refused: x targets PyAutoMind — a shift never changes its own watcher, writer or release " + "path (the organ rule: /add never overrides it)"), + ("lane outside the brief", [(X, LIB, "ral")], X, + "refused: x: lane ral not in the brief's lanes"), +]) +def test_add_ignored_and_refused_acks(tmp_path, monkeypatch, case, drafts, arg, ack): + mind, brief, home, slot, publish = _add_shift(tmp_path, monkeypatch, drafts=drafts) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + if drafts: + publish() + gh.add(LOGIN, f"/add {arg}", 1) + r = _tick(brief, mind, home, 2, claude, gh, {"t1": "working"}) + assert r["commands"][0]["ack"] == ack, case + assert _spawned(claude) == ["shift:t1"] and "added" not in orch.read_counters(slot) + + +def test_add_is_refused_on_a_claim_on_mind_origin(tmp_path, monkeypatch): + mind, brief, home, slot, publish = _add_shift( + tmp_path, monkeypatch, drafts=[(X, LIB, "local-dev")], + active="\n## x\n- prompt: active/x.md\n") + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + publish() + gh.add(LOGIN, "/add x", 1) + r = _tick(brief, mind, home, 2, claude, gh, {"t1": "working"}) + assert r["commands"][0]["ack"] == "refused: x: claimed in active.md on Mind origin/main" + + +def test_add_overrides_the_briefs_exclude_list(tmp_path, monkeypatch): + mind, brief, home, slot, publish = _add_shift( + tmp_path, monkeypatch, drafts=[(X, LIB, "local-dev")], + brief_edit=lambda s: s.replace(" - backlog: none\n", + f" - backlog: none\n - exclude:\n - {X}\n")) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + publish() + gh.add(LOGIN, "/add x", 1) + r = _tick(brief, mind, home, 2, claude, gh, {"t1": "working"}) + assert r["commands"][0]["ack"] == ("added x (glance) (was excluded in the brief): starts " + "this tick; max-workers 2, 1 running.") + assert _spawned(claude) == ["shift:t1", "shift:x"] + + +def test_add_is_refused_within_thirty_minutes_of_review_at(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + gh.add(LOGIN, "/add x", 1) + r = _tick(brief, mind, home, 121, claude, gh) # 11:01Z, review-at 11:30Z + assert r["commands"][0]["ack"] == ("refused: /add within 30 min of review-at. " + "A worker needs longer.") + + +def test_add_is_refused_in_a_shadow_shift(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch, extra=" - shadow: yes\n") + claude, gh = d.FakeClaude(), FakeGitHub() + gh.add(LOGIN, "/add x", 1) + r = _tick(brief, mind, home, 2, claude, gh) + assert r["commands"][0]["ack"] == "refused: shadow shift: nothing is dispatched." + + +# /kill: `claude stop` is a fake on PATH; no session is ever started or stopped. + +def _fake_claude_bin(tmp_path, monkeypatch, rc=0): + bindir = tmp_path / "bin" + bindir.mkdir(exist_ok=True) + log = tmp_path / "claude_calls.log" + (bindir / "claude").write_text( + "#!/bin/sh\n" + f"echo \"$@\" >> {log}\n" + + ("echo 'Error: no such session' >&2\n" if rc else "echo 'stopped'\n") + + f"exit {rc}\n") + (bindir / "claude").chmod(0o755) + monkeypatch.setenv("PATH", f"{bindir}:{os.environ['PATH']}") + return log + + +def test_kill_stops_the_worker_and_it_is_restarted_once_as_killed(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + log = _fake_claude_bin(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + gh.add(LOGIN, "/kill t1", 1) + r = _tick(brief, mind, home, 2, claude, gh, {"t1": "working"}) + assert r["commands"][0]["ack"] == ("stopping t1's worker 00000001 (claude stop). " + "It is restarted once, unless you /drop t1.") + assert log.read_text() == "stop 00000001\n" + r = _tick(brief, mind, home, 4, claude, gh, {"t1": "stopped"}) + assert r["reaped"] == [{"task": "t1", "event": "dead", "redispatch": "allowed", + "killed": True}] + assert _spawned(claude) == ["shift:t1", "shift:t1"] # re-dispatched once + c = orch.read_counters(slot) + assert c["workers"][0]["exits"] == ["spawned", "killed"] and c["crashes"] == 0 + assert c["killed"]["t1"]["by"] == LOGIN and c["redispatched"] == {"t1": 1} + assert orch._digest.workers_crashed(c) == 0 + lines = [e["line"] for e in orch._events.read_events(slot) if e["kind"] in + ("steer", "crashed", "redispatched")] + assert lines == ["/kill t1 from example-human: stopping t1's worker 00000001 (claude stop). " + "It is restarted once, unless you /drop t1.", + "Worker on t1 stopped by /kill. It restarts once.", + "Restarted t1 (its one retry)."] + + +def test_drop_then_kill_is_final(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + _fake_claude_bin(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + gh.add(LOGIN, "/drop t1", 1) + gh.add(LOGIN, "/kill t1", 1.5) + r = _tick(brief, mind, home, 2, claude, gh, {"t1": "working"}) + assert r["commands"][1]["ack"] == ("stopping t1's worker 00000001 (claude stop). " + "It is not restarted: t1 was dropped.") + _tick(brief, mind, home, 4, claude, gh, {"t1": "stopped"}) + assert _spawned(claude) == ["shift:t1"] + + +@pytest.mark.parametrize("comment,rc,ack", [ + ("/kill", 0, "ignored: /kill needs a task name"), + ("/kill t9", 0, "ignored: no running worker for t9"), + ("/kill t1", 1, "refused: claude stop failed: Error: no such session. Stop it by hand: " + "claude stop 00000001"), +]) +def test_kill_ignored_and_refused_acks_stop_nothing(tmp_path, monkeypatch, comment, rc, ack): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + _fake_claude_bin(tmp_path, monkeypatch, rc=rc) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + gh.add(LOGIN, comment, 1) + r = _tick(brief, mind, home, 2, claude, gh, {"t1": "working"}) + assert r["commands"][0]["ack"] == ack + assert "killed" not in orch.read_counters(slot) + (e,) = [e for e in orch._events.read_events(slot) if e["kind"] == "steer"] + assert e["needs_you"] # an ignored/refused ack + + +def test_kill_a_second_time_is_ignored(tmp_path, monkeypatch): + mind, brief, home, slot = _shift(tmp_path, monkeypatch) + log = _fake_claude_bin(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + gh.add(LOGIN, "/kill t1", 1) + gh.add(LOGIN, "/kill t1", 1.5) + r = _tick(brief, mind, home, 2, claude, gh, {"t1": "working"}) + assert r["commands"][1]["ack"].startswith("ignored: t1's worker 00000001 is already stopping") + assert log.read_text() == "stop 00000001\n" + + +def test_command_help_lists_every_verb(): + assert {"add", "cap", "kill"} <= set(orch.COMMANDS) + for verb in orch.COMMANDS: + assert f"`/{verb}" in _watch.COMMAND_HELP From 39260155e840b1e2f63edeaccb4cda3f048dc573 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 16 Nov 2026 13:55:04 +0000 Subject: [PATCH 2/3] doctrine: watcher network amendment for the shift cockpit engine (#644) AUTONOMY.md amendment 2026-11-16 items 1-3, approved by the human: the per-shift events.jsonl, /add's one Mind fetch per command with /cap and /kill's local claude stop, and needs-you event comments (at most 5 + 1 a shift). /drop's "a running worker is not killed by the watcher" now ends "unless the human commands /kill"; the revert condition names them all. The batch skill and its reference list the new verbs and --stream. Co-Authored-By: Claude Opus 5.5 --- AUTONOMY.md | 30 ++++++++++++++++++++++++++++++ skills/batch/batch.md | 2 +- skills/batch/reference.md | 20 ++++++++++++++++++-- 3 files changed, 49 insertions(+), 3 deletions(-) diff --git a/AUTONOMY.md b/AUTONOMY.md index 60df894a..aead0530 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -991,6 +991,36 @@ refuses the merge. A PR in any other repo makes no call at all. The revert condition covers these the same way: any other call, or a repeat for the same close-out, retires the watcher to fake mode. +**Amendment — 2026-11-16 (M3.4/M3.5; PyAutoBrain#644), approved by the human.** +The shift cockpit's engine (DESIGN `m3_4_m3_5_design`, rulings H4b, H5a, H6a, +H8a/a, H10a). The watcher's surface gains, and only: + +1. **the per-shift `events.jsonl`** in its slot directory, appended inside the + tick lock from what the tick already did — local, no network, no LLM. `batch + watch --stream` reads it; it goes to neither Mind nor GitHub; +2. **`/add`** (one Mind `git fetch` per `/add` command, on top of the + once-per-shift fetch), **`/cap`**, and **`/kill`** (a local `claude stop` of a + worker the watcher started; not network). `/cap` lowers a cap, or raises it + back, never above the brief's own value. `/add` is refused within 30 minutes + of `review-at:`; it overrides the brief's `exclude:` and an earlier shift's + parked hold, never the organ rule. A worker stopped by `/kill` is + re-dispatched once, unless the human dropped the task first; +3. **needs-you event comments**, at most 5 + 1 per shift: one short comment on + the brief's `issue:` per event that needs the human (an ignored or refused + command, commands unread three ticks running, the watcher unable to post or + to write Mind, a dropped task's PR merged anyway), with no `@`, each claimed + by its marker before the post and counted as a push; after the fifth, one + last comment saying the rest are in the status comment. + +It makes no new CI read: `ci` lines come only from the `gh pr checks` the +close-outs already make (H10a). The 2026-11-13 `/drop` rule "a running worker is +not killed by the watcher" now reads "… unless the human commands `/kill`". +The revert condition now also covers a second Mind fetch for one `/add` +command, a `claude stop` of any session but a running worker of this shift the +human named in `/kill`, a needs-you comment beyond 5 + 1 in a shift or one with +an `@`, and any network call from writing or reading `events.jsonl`: 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 diff --git a/skills/batch/batch.md b/skills/batch/batch.md index 13e6a05a..40257309 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -108,7 +108,7 @@ but spawns nothing — the pilot's baseline; every shift keeps one line in `PyAu 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`. 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. +**`/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`, `/add `, `/cap merges|workers|sessions|tokens `, `/kill `); never post one for them. `batch watch --stream --record ` prints the shift's event stream (`events.jsonl`, local reads only) until it ends — the cockpit's watch ([`reference.md`](reference.md)). ## When they come back — collect, review, close (2026-08-31) diff --git a/skills/batch/reference.md b/skills/batch/reference.md index 5558206c..609a5df0 100644 --- a/skills/batch/reference.md +++ b/skills/batch/reference.md @@ -131,5 +131,21 @@ does not volunteer it. 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. + A dropped worker that is already running is not killed by `/drop`; the + human may stop it by hand (`claude stop `) or command `/kill `. + Never post a command for them. +- **More verbs (PyAutoBrain#644):** `/cap merges|workers|sessions|tokens ` + lowers a cap for this shift, or raises it back, never above the brief's own + value (`tokens` takes `400k`, `1.2M`); `/add ` makes a draft on Mind + origin/main a named task (refused within 30 min of `review-at:`; overrides the + brief's `exclude:`, never the organ rule); `/kill ` runs `claude stop` on + that task's running worker, which is re-dispatched once unless dropped first. + An ack starting `ignored:` or `refused:` is a needs-you event: at most 5 such + comments a shift, no `@`. +- **The event stream:** `bin/pyauto-brain batch watch --stream --record + [--from N] [--for MIN] [--json]` prints the slot's `events.jsonl`, one + plain line per event (`NEEDS YOU:` first when it needs the human), and exits 0 + at `shift-end`, a `STOP` or `review-at:` + 45 min; with `--for` it ends the + segment with `segment-end next=--from N` (exit 3). `--check` only says whether + it may attach now (exit 2 outside `dispatched:` − 30 min … `review-at:` + 45 + min). `--record`/`--home` default from `~/.config/pyauto/orchestrator.env`. From 1d8a1b1dfa9edd95fddb0de0910296585351e598 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 16 Nov 2026 14:08:27 +0000 Subject: [PATCH 3/3] fix(batch): review findings on the shift cockpit engine (#644) - Close-out gates read `budget is not None`: a `/cap tokens 0` now stops close-outs, as its ack says (test). - Needs-you event comments count as `event_comments`, apart from `pushes`, so the digest's push-test finding no longer fires on a normal shift; the digest names their count (test). AUTONOMY item 3 says so. - Event keys are truncated before dedup (KEY_MAX), so a long key never repeats; a `ci` key carries the PR's line count, so a verdict that changes again is streamed again (tests). - `batch watch --stream --from N` attaches after `shift-end` when N is before it, so a re-attaching cockpit gets the digest and shift-end (test). - A comment at `/kill`: a crash before the counters write re-stops the same agent id at most. - batch AGENTS.md: seven verbs, `/kill` is the watcher's, the event stream. Co-Authored-By: Claude Opus 5.5 --- AUTONOMY.md | 5 ++-- agents/conductors/batch/AGENTS.md | 22 +++++++++++++-- agents/conductors/batch/_digest.py | 5 ++++ agents/conductors/batch/_events.py | 18 +++++++++--- agents/conductors/batch/_orchestrator.py | 21 +++++++++++--- agents/conductors/batch/_watch.py | 13 ++++++--- tests/test_batch_watch_stream.py | 16 +++++++++++ tests/test_orchestrator_events.py | 35 ++++++++++++++++++++++-- tests/test_orchestrator_steering.py | 17 ++++++++++++ 9 files changed, 134 insertions(+), 18 deletions(-) diff --git a/AUTONOMY.md b/AUTONOMY.md index aead0530..2aa340f0 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -1009,8 +1009,9 @@ H8a/a, H10a). The watcher's surface gains, and only: the brief's `issue:` per event that needs the human (an ignored or refused command, commands unread three ticks running, the watcher unable to post or to write Mind, a dropped task's PR merged anyway), with no `@`, each claimed - by its marker before the post and counted as a push; after the fifth, one - last comment saying the rest are in the status comment. + by its marker before the post and counted in the digest apart from the + per-worker pushes; after the fifth, one last comment saying the rest are in + the status comment. It makes no new CI read: `ci` lines come only from the `gh pr checks` the close-outs already make (H10a). The 2026-11-13 `/drop` rule "a running worker is diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 613dfbb9..87a84bfc 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -492,14 +492,32 @@ task of this shift only, else "no such task in this shift"; `counters.json` 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 +shown `dropped, still running` until the human stops it, by hand or by `/kill`) +and `/stop` (writes `STOP`; that tick commits nothing to Mind). PyAutoBrain#644 +adds three, making seven: `/cap merges|workers|sessions|tokens ` (lowers a +cap for this shift, or raises it back, never above the brief's own value; +`_brief.effective` applies it from that tick), `/add ` (one Mind fetch +per command; the draft on origin/main becomes a named task, refused within 30 +min of `review-at:`; it overrides `exclude:` and an earlier shift's parked hold, +never the organ rule) and `/kill ` (the watcher runs a local `claude stop` +on that task's running worker; the reap marks the exit `killed`, not crashed, +and it is re-dispatched once unless dropped first). Each comment acts once, by id, and is acknowledged 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 event stream (PyAutoBrain#644).** Every tick that does work appends what +it did to `/events.jsonl` (`_events.record_tick`, inside the tick lock, +local only), one plain line per event, deduplicated by key in the file itself; +`batch watch --stream` prints it until `shift-end`. A needs-you event (an +`ignored:`/`refused:` ack, commands unread three ticks running, the watcher +unable to post or write Mind, a dropped task's PR merged anyway) is also one +short comment on the brief's `issue:`, no `@`, marker `mentions/event.`, +at most 5 + 1 a shift, counted as `event_comments` apart from `pushes`. +Doctrine: AUTONOMY.md watcher network surface, amendment 2026-11-16 (#644). + **The watcher's GitHub identity (human rulings 2026-11-12, #611, and 2026-11-14, #630).** The watcher posts as its own minimal GitHub App, `pyautolabs-watcher`, set by the human in the timer's environment diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 26378407..395d436e 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -695,6 +695,11 @@ def worker_lines(counters: dict, links: MindLinks | None = None) -> list[str]: if pushes > 1: out.append(f"- finding: {pushes} pushes this shift — the push test budgets " "about one (AUTONOMY.md)") + events = int(counters.get("event_comments") or 0) + if events: + # Needs-you event comments (#644) have their own cap, 5 + 1 a shift, + # and are not pushes for the finding above. + out.append(f"- needs-you event comments: {events} (at most 5 + 1 a shift)") return out diff --git a/agents/conductors/batch/_events.py b/agents/conductors/batch/_events.py index 1dd76235..ef941fb6 100644 --- a/agents/conductors/batch/_events.py +++ b/agents/conductors/batch/_events.py @@ -36,6 +36,9 @@ LINE_MAX = 300 #: One JSON line, at most this many bytes (one local append, never torn). RECORD_MAX = 1024 +#: A dedup key, at most this many characters: stored and compared truncated +#: alike, so a long key can never repeat on every tick. +KEY_MAX = 200 #: CI verdicts that make a `ci` line; RUNNING never does, UNKNOWN is skipped #: ("gh could not say" — the tick asks again). CI_EMIT = ("HEALTHY", "FAILED", "NO-CHECKS") @@ -142,13 +145,14 @@ def has(self, key: str) -> bool: return key in self.keys def add(self, kind: str, key: str, line: str, *, needs_you: bool = False, **extra) -> None: + key = key[:KEY_MAX] if key in self.keys: return self.keys.add(key) self.seq += 1 e = {"v": SCHEMA, "seq": self.seq, "at": self.now.astimezone(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), - "slot": self.slot.name, "kind": kind, "key": key[:300], + "slot": self.slot.name, "kind": kind, "key": key, "line": _clean(line), "needs_you": bool(needs_you)} for k, v in extra.items(): if v not in (None, "", [], {}): @@ -272,17 +276,24 @@ def _refused(b: _Batch, result: dict) -> None: def _ci(b: _Batch, result: dict, state: dict) -> None: + """A `ci` line when a PR's verdict changes to HEALTHY, FAILED or + NO-CHECKS — again after any change, e.g. green, then a new push RUNNING, + then red or green once more. The key carries how many `ci` lines the PR + already has, so each transition is its own key; with the state file + lost, the last verdict comes from the file's own `ci` lines (at most one + repeated line).""" for pr, verdict in sorted((result.get("health") or {}).items()): if verdict == "UNKNOWN": continue - last = state["ci"].get(pr) + mine = [e for e in b.existing + b.events if e.get("kind") == "ci" and e.get("pr") == pr] + last = state["ci"].get(pr, mine[-1].get("verdict") if mine else None) state["ci"][pr] = verdict if verdict not in CI_EMIT or verdict == last: continue line = {"HEALTHY": f"CI green on {ref(pr)}.", "FAILED": f"CI red on {ref(pr)}: never merged unattended.", "NO-CHECKS": f"No CI checks on {ref(pr)}: left for your /prm."}[verdict] - b.add("ci", f"ci:{pr}:{verdict}", line, pr=pr) + b.add("ci", f"ci:{pr}:{len(mine) + 1}:{verdict}", line, pr=pr, verdict=verdict) def _closeouts(b: _Batch, result: dict, counters: dict, info: dict) -> None: @@ -435,7 +446,6 @@ def _encode(e: dict) -> bytes: if k in e and len(e[k]) > 120: e[k] = e[k][:120] e["line"] = e["line"][:max(len(e["line"]) - 60, 40)] - e["key"] = e["key"][:200] raw = json.dumps(e, sort_keys=True, ensure_ascii=False).encode("utf-8") if len(e["line"]) <= 40: break diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 1140deaf..9345b973 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -1825,6 +1825,13 @@ def _retry_mentions(slot: Path, counters: dict, poster, now: _dt.datetime) -> li for marker in sorted(d.glob("*.json")): rec = retry_post(marker, marker.with_suffix(".md"), poster, now) if rec is not None: + if marker.stem.startswith("event."): + # A needs-you event comment (#644): counted apart from pushes. + if rec.get("state") == "posted": + counters["event_comments"] = int(counters.get("event_comments") or 0) + 1 + out.append({"event": rec.get("event"), "post": rec["state"], + "retry": rec["tries"]}) + continue w = last_worker(counters, rec.get("task", "")) _note_mention(counters, w if w and w.get("key") == rec.get("worker") else None, marker.stem, rec) @@ -2345,6 +2352,8 @@ def _cmd_kill(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict old = (counters.get("killed") or {}).get(task) or {} if old.get("key") == key: return f"ignored: {task}'s worker {key} is already stopping (/kill at {old.get('at')})" + # A crash between this stop and the counters write leaves the comment + # unseen: the next tick stops the same agent id again, at most — never another session. ok, why = (ctx.get("stop") or claude_stop)(agent) if not ok: return (f"refused: claude stop failed: {why[:160]}. Stop it by hand: " @@ -2429,7 +2438,8 @@ def _event_comments(slot: Path, events: list[dict], issue: str, poster, """One comment per needs-you event on the shift issue (human ruling H4b), at most `EVENT_COMMENTS_MAX` a shift and then one overflow comment, each claimed by its marker before the post (`mentions/event.`); a post - `gh` said failed is retried with the mentions. Each counts as a push.""" + `gh` said failed is retried with the mentions. Each counts in + `event_comments`, apart from the per-worker `pushes`.""" todo = [e for e in events if e.get("needs_you")] if not todo or not issue.startswith("http") or (slot / STOP_FILE).exists(): return [] @@ -2454,7 +2464,9 @@ def _event_comments(slot: Path, events: list[dict], issue: str, poster, continue sent += 1 if rec.get("state") == "posted": - counters["pushes"] += 1 + # Counted apart from the per-worker pushes, whose digest finding + # budgets about one a shift (AUTONOMY.md push test). + counters["event_comments"] = int(counters.get("event_comments") or 0) + 1 out.append({"event": e["seq"], "post": rec.get("state")}) if name == EVENT_OVERFLOW: break @@ -3084,7 +3096,7 @@ def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt. "no close-out starts this late"} events["refused"].append(pr) continue - if budget and counters["usage_unavailable"]: + if budget is not None and counters["usage_unavailable"]: # As the spawn gate: a spend that cannot be read could be # anything, so nothing starts this tick; asked again next tick. events.setdefault("held", []).append( @@ -3092,7 +3104,8 @@ def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt. + ", ".join(counters["usage_unavailable"]) + ")"}) continue spent = _committed_tokens(counters) - if budget and spent >= CLOSEOUT_BUDGET_FACTOR * budget: + # `is not None`: a `/cap tokens 0` (#644) means zero, not "no budget". + if budget is not None and spent >= CLOSEOUT_BUDGET_FACTOR * budget: # The human's ruling 2026-11-14 (#632, F5): a close-out may pass # the budget, but none starts once spend reaches 1.5x it — # spend as the spawn gate counts it, reservations included. diff --git a/agents/conductors/batch/_watch.py b/agents/conductors/batch/_watch.py index 03ce93ce..182437e3 100644 --- a/agents/conductors/batch/_watch.py +++ b/agents/conductors/batch/_watch.py @@ -367,9 +367,12 @@ def _window(record: Path) -> tuple: return start, end -def attachable(record: Path, slot: Path, now: _dt.datetime) -> tuple[bool, str]: +def attachable(record: Path, slot: Path, now: _dt.datetime, + from_seq: int | None = None) -> tuple[bool, str]: """(may the stream run now?, why not). Window: `dispatched:` − 30 min to - `review-at:` + 45 min; never with `STOP` present or after `shift-end`.""" + `review-at:` + 45 min; never with `STOP` present, nor after `shift-end` — + unless `from_seq` is before it: a cockpit re-attaching with `--from` + still gets the lines it missed, the digest and `shift-end`, then exits.""" try: start, end = _window(record) except (OSError, _brief.BriefError) as e: @@ -383,7 +386,9 @@ def attachable(record: Path, slot: Path, now: _dt.datetime) -> tuple[bool, str]: return False, f"shift {slot.name} watch window is over (review-at + 45 min)" if (slot / _orchestrator.STOP_FILE).exists(): return False, f"STOP present in {slot}: the watcher does nothing" - if any(e.get("kind") == "shift-end" for e in _events.read_events(slot)): + end_seq = next((e["seq"] for e in _events.read_events(slot) + if e.get("kind") == "shift-end"), None) + if end_seq is not None and (from_seq is None or from_seq >= end_seq): return False, f"shift {slot.name} is over (shift-end written)" return True, "" @@ -464,7 +469,7 @@ def stream(record: Path, slot: Path, *, from_seq: int | None = None, clock = clock or (lambda: _dt.datetime.now(_dt.timezone.utc)) record, slot = Path(record), Path(slot) began = clock() - ok, why = attachable(record, slot, began) + ok, why = attachable(record, slot, began, from_seq) if not ok: err.write(f"batch watch --stream: {why}\n") return RC_REFUSED diff --git a/tests/test_batch_watch_stream.py b/tests/test_batch_watch_stream.py index 85b4364d..a0a7df3f 100644 --- a/tests/test_batch_watch_stream.py +++ b/tests/test_batch_watch_stream.py @@ -132,6 +132,22 @@ def test_it_refuses_with_stop_present_or_after_shift_end(tmp_path): assert rc == 2 and "is over (shift-end written)" in err +def test_from_before_shift_end_still_attaches_and_gets_the_last_lines(tmp_path): + """Review of #644: a cockpit re-attaching with `--from` after the shift + ended still prints what it missed, the digest and `shift-end`, then exits.""" + record, slot = _setup(tmp_path) + _emit(slot, 0, {"action": "ticked", "spawned": [{"task": "t1"}]}) + _emit(slot, 120, {"action": "digest", "post": {"posted": True, "url": "https://x/9"}}, + quiet=True) + later = Clock(REVIEW_AT + _dt.timedelta(minutes=5)) + rc, out, err, polls = _run(record, slot, later, from_seq=2) + assert (rc, err, polls) == (0, "", []) and out.splitlines()[1:] == [ + "19:00Z Shift closed. Digest: https://x/9.", + "19:00Z Shift 2026-11-16-pm over. Nothing is still running."] + rc, _, err, _ = _run(record, slot, Clock(REVIEW_AT + _dt.timedelta(minutes=5)), from_seq=4) + assert rc == 2 and "is over (shift-end written)" in err + + # --- attach, catch-up, follow, every exit --------------------------------------------- def test_attach_summary_makes_no_network_read(tmp_path, monkeypatch): diff --git a/tests/test_orchestrator_events.py b/tests/test_orchestrator_events.py index ac5a2d82..d815a456 100644 --- a/tests/test_orchestrator_events.py +++ b/tests/test_orchestrator_events.py @@ -361,7 +361,8 @@ def test_needs_you_events_post_at_most_five_comments_and_one_overflow(tmp_path): assert all("@you" not in body for _, body in poster.calls) assert "further needs-you events are in the status comment" in poster.calls[-1][1] assert "needs you: /cap from x: ignored: 1" in poster.calls[0][1] - assert orch.read_counters(slot)["pushes"] == 6 + c = orch.read_counters(slot) + assert c["event_comments"] == 6 and c["pushes"] == 0 # not pushes (review #644) # Later ticks post nothing more: the overflow comment was the last. more = [{"seq": 90, "kind": "impaired", "line": "x", "needs_you": True}] assert orch._event_comments(slot, more, issue, poster, NOW) == [] and len(poster.calls) == 6 @@ -392,7 +393,37 @@ def poster(issue, body_file): assert orch.mentions_due(slot) c = orch.read_counters(slot) orch._retry_mentions(slot, c, poster, NOW) - assert not orch.mentions_due(slot) and c["pushes"] == 1 + assert not orch.mentions_due(slot) and c["event_comments"] == 1 and c["pushes"] == 0 + + +def test_needs_you_comments_never_raise_the_push_finding(): + c = {"pushes": 1, "event_comments": 6, "workers": [], "picks": {}} + lines = orch._digest.worker_lines(c) + assert not any("pushes this shift" in x for x in lines) + assert "- needs-you event comments: 6 (at most 5 + 1 a shift)" in lines + assert any("2 pushes this shift" in x for x in orch._digest.worker_lines({**c, "pushes": 2})) + + +def test_a_ci_line_comes_again_after_a_change_and_never_repeats_otherwise(tmp_path): + slot = _slot(tmp_path) + for m, v in enumerate(("RUNNING", "HEALTHY", "HEALTHY", "RUNNING", "FAILED", "FAILED", + "UNKNOWN", "HEALTHY")): + _record(slot, m, {"action": "ticked", "health": {PR: v}}) + assert [e["line"] for e in _events.read_events(slot) if e["kind"] == "ci"] == [ + "CI green on example-lib#901.", "CI red on example-lib#901: never merged unattended.", + "CI green on example-lib#901."] + (slot / _events.STATE_FILE).unlink() # lost: the file knows the last + _record(slot, 9, {"action": "ticked", "health": {PR: "HEALTHY"}}) + assert sum(e["kind"] == "ci" for e in _events.read_events(slot)) == 3 + + +def test_a_long_key_is_compared_as_stored_and_never_repeats(tmp_path): + slot = _slot(tmp_path) + long_task = "t" * 400 + for m in range(4): + _record(slot, m, {"action": "ticked", "refused": [{"task": long_task, "why": "spawn failed"}]}) + (e,) = [e for e in _events.read_events(slot) if e["kind"] == "refused"] + assert len(e["key"]) == _events.KEY_MAX def test_fixture_is_the_real_shift_b_log(): diff --git a/tests/test_orchestrator_steering.py b/tests/test_orchestrator_steering.py index bfe5d1e7..9b04ccd5 100644 --- a/tests/test_orchestrator_steering.py +++ b/tests/test_orchestrator_steering.py @@ -853,6 +853,23 @@ def test_kill_a_second_time_is_ignored(tmp_path, monkeypatch): assert log.read_text() == "stop 00000001\n" +def test_cap_tokens_zero_stops_close_outs_as_its_ack_says(tmp_path, monkeypatch): + """Review of #644: the close-out gates read `budget is not None`, so a + `/cap tokens 0` means zero, never "no budget".""" + mind, brief, home, slot = _cap_shift(tmp_path, monkeypatch) + claude, gh = d.FakeClaude(), FakeGitHub() + _tick(brief, mind, home, 0, claude, gh) + pr = "https://github.com/example-org/example-repo/pull/8" + (slot / "leases" / "t1.done").write_text(pr + "\n") + gh.add(LOGIN, "/cap tokens 0", 2) + r = _tick(brief, mind, home, 3, claude, gh, {"t1": "done"}, health="HEALTHY") + assert r["commands"][0]["ack"] == ("token-budget now 0 of 100000 (0 committed): " + "no new spawn or close-out.") + co = orch.read_counters(slot)["closeouts"][pr] + assert co["state"] == "refused" and co["why"].startswith("token spend 0 (committed) reached") + assert r["closeouts"]["started"] == [] + + def test_command_help_lists_every_verb(): assert {"add", "cap", "kill"} <= set(orch.COMMANDS) for verb in orch.COMMANDS: