herdr-orchestra 5.6.0 → 5.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
2
2
 
3
3
  All notable changes. Versions follow [semantic versioning](https://semver.org).
4
4
 
5
+ ## [5.7.0] - 2026-11-15
6
+
7
+ Found in a real run (orch 5.4.0): a coder hit its usage limit, then the terminal closed and herdr restarted. The event manager had been started from a herdr pane, so it died too. For 2.5 hours `orch status` still said "M3 coding on rs-opencode-1" for a pane that no longer existed, and nobody was told. After that, `orch team up` opened an OpenCode pane that quit at once and left a plain shell, and the task was typed into that shell. `dispatch --to rs-agy-1` said "ok" for a worker with no pane. The developer's "no more Claude" was forgotten as soon as Claude's pane came back. Swapping a coder meant killing the event manager by hand, and a dead manager left no trace of why it died.
8
+
9
+ ### Added
10
+ - **`orch bench <worker> off [reason]` / `on`.** Keeps a coder out of the run until you turn it back on. Unlike a usage-limit bench it never ends by itself: it holds across restarts, `orch sync`, `orch resume` and `orch team up`. Milestones sent to that coder with `--to` are freed for the others. `orch status` shows `state=OFF (<reason>)`.
11
+ - **`orch stop [--now]`.** Stops the event manager cleanly: it finishes the step it is on (a check, a merge) and exits, keeping every event. Then `orch sync` works, and `orch resume` starts it again. The playbook has a swap-a-coder recipe: `orch stop`, change `Workers:`, `orch sync`, `orch team up`, `orch resume`.
12
+ - **Crash notes in `autopilot.log`.** Every stop writes a last line, tagged with the repo and branch: `[shop feature/cart] STOPPED: orch stop`, `STOPPED: the event manager exited (code 3)`, or `CRASHED: ValueError: ...` with the traceback. A manager killed without a word is found by the next `orch status`, `orch resume` or manager start, which looks up why in the computer's own log: the memory guard (`systemd-oomd`) closing the terminal, the kernel killing a process for memory, a crash dump (`coredumpctl`), sleep, shutdown, or a reboot (from the boot time). It writes the reason and the matching system log line once.
13
+ - **Crash notes stay with their own project.** When the event manager starts, it records this run's own processes (itself, herdr, and every process working in the run's folders) and their cgroups. A kill in the system log is blamed on this run only when it names one of them. Otherwise it says `unknown — the system log shows a kill then, but not of this run's processes (another project or app)`.
14
+ - **`orch doctor --crash`** (in a repo): why the event manager last stopped, the last `STOPPED` / `CRASHED` / `LOST` / `QUIT` notes, and the saved agent screens.
15
+ - **Saved screens.** When a coder's agent quits and leaves a shell, or `orch team up` sees an agent quit right after starting, its last 40 lines are saved to `.orchestrate/crash/<agent>-<time>.txt` (newest 20 kept, `ORCH_CRASH_KEEP`).
16
+ - **A vanished coder is a lead event, not a log line.** `WORKER-LOST Mn` tells the lead what happened (pane closed, or only a shell left) and the exact fix (`orch resume` after a herdr restart, or `orch team up`). When most agents vanish at once, the log says `HERDR RESTART? 4 of 5 agents vanished at once`, with a desktop alert and a `HERDR-RESTART` lead event.
17
+
18
+ ### Changed
19
+ - **An agent counts as there only when herdr runs an agent in its pane.** A name on a pane with only a shell left (`"agent": null`, no status) used to count as alive, so prompts were typed into the shell. Now it counts as gone everywhere orch picks a coder.
20
+ - **`orch dispatch --to <worker>` refuses a worker with no agent** (`rs-agy-1 has no agent in herdr (NO AGENT). Run orch team up ...`) or one that is benched off. A plain dispatch warns when none of the possible coders is there.
21
+ - **`orch status` and `orch ready` tell the truth.** Each worker line shows `herdr=ok`, `NO AGENT` or `SHELL ONLY`, and `state=free`, `coding M3`, `benched 42m (rate-limit)` or `OFF`. A milestone coding on a vanished worker says `!! but rs-opencode-1 has no agent in herdr: nothing is working on it — orch resume`. `READY`'s free slots count only coders herdr can see, and `NOAGENT` names the rest.
22
+ - **`orch team up` looks again a few seconds after starting each agent** (`ORCH_TEAM_CONFIRM_S`, default 5). One that quit at once is reported as `QUIT`, exit 3, instead of `OPENED`.
23
+ - **Old notes are cleared.** A milestone's note such as `[rs-claude-1 hit a usage/rate limit]` is cleared when another coder starts on it.
24
+ - **The event manager starts in its own systemd scope** (`systemd-run --user --scope`) when it can, so the memory guard closing a terminal, or a closed herdr pane, does not take it down. Where that is not available it starts as before. `ORCH_NO_SCOPE=1` turns it off.
25
+ - **Logs stay small.** `autopilot.log` becomes `autopilot.log.1` past 2 MB (`ORCH_LOG_MAX_MB`) and only that one old copy is kept; `manager.out` the same at 1 MB.
26
+
27
+ Tested with simulated agents and a simulated herdr and system log only. Two things are not proven on a real machine yet: herdr's exact JSON for a pane whose agent quit (orch reads `"agent": null`, or no status at all, as "only a shell"), and the `systemd-run --scope` start on Ubuntu.
28
+
5
29
  ## [5.6.0] - 2026-11-15
6
30
 
7
31
  A small change (a few UI tweaks, a new field in an API response, a validation rule) went through the same process as a big feature: full research, a plan with a breakdown, roles and model reasons, worktrees and setup, a reviewer for every UI change, a long summary, and the check command run four or five times. For a 10-minute change most of the time went on the process around it.
package/README.md CHANGED
@@ -236,7 +236,8 @@ When a milestone passes its checks it's saved to its hidden ref and the coder is
236
236
  | Merge conflict | the same coder merges the feature branch and resolves it, up to 2 rounds; if the milestone was already approved, the reviewer sees the resolution before it lands |
237
237
  | Passes alone, fails once merged | the check runs on the merged result **before** the commit; a failure commits nothing and goes back to a coder as a fix round |
238
238
  | A coder hits a usage limit | benches it for 60 min; the other coder continues, with the work so far (also in shared mode) |
239
- | An agent disappears | coder: its task moves on with the work so far; reviewer: only the review waits. Either is used again as soon as it's back |
239
+ | An agent disappears | coder: its task moves on with the work so far, and the lead gets a `WORKER-LOST` event with the exact fix (`orch resume` or `orch team up`); reviewer: only the review waits. Either is used again as soon as it's back. A pane where the agent quit and only a shell is left counts as gone: nothing is typed into a shell |
240
+ | Most agents vanish at once | `HERDR RESTART?` in the log, a desktop alert and a lead event: run `orch resume` |
240
241
  | A prompt can't be delivered | the task goes back in the queue (its job kept) and that agent is retried after 2 min; 3 in a row bench it for 30 min |
241
242
  | Attempts keep getting lost (unreachable, gone, rate-limited) | after 4 (`ORCH_MAX_LOST`) the task fails with the history instead of looping |
242
243
  | Autopilot is killed mid-step | the next run confirms or re-sends an unconfirmed prompt to the same agent, and finishes or undoes a half-done merge |
@@ -271,6 +272,26 @@ It is safe to run more than once. If an agent with work in progress is still mis
271
272
 
272
273
  orch can't bring an agent's old conversation back, and it can't start itself when the computer starts.
273
274
 
275
+ ### Keep a coder out, swap a coder
276
+ - `orch bench claude-1 off "no Claude today"` keeps a coder out of the run until `orch bench claude-1 on`. It holds across restarts, `orch sync`, `orch resume` and `orch team up`; a usage-limit bench, by contrast, ends by itself.
277
+ - `orch dispatch Mn --to <worker>` refuses a worker with no agent in herdr and says to run `orch team up`. `orch status` shows each worker as `herdr=ok`, `NO AGENT` or `SHELL ONLY`, and `state=free`, `coding M3`, `benched 42m (rate-limit)` or `OFF`.
278
+ - Swap a coder: `orch stop` (the event manager finishes its current step and exits; nothing is lost), change `Workers:` in plan.md, `orch sync`, `orch team up`, then `orch resume`.
279
+ - `orch team up` looks again a few seconds after it starts each agent. One that quit at once (a bad flag, a sign-in) is reported as `QUIT`, with its last screen saved.
280
+
281
+ ### Logs and crash notes
282
+ Everything is in the repo's own `.orchestrate/` folder, so two projects never share a log:
283
+
284
+ | File | What is in it |
285
+ |---|---|
286
+ | `autopilot.log` | the event manager's diary. Over 2 MB it becomes `autopilot.log.1` (one old copy is kept) |
287
+ | `manager.out` | raw output of a manager started in the background (1 MB, one old copy) |
288
+ | `events.jsonl` | one line per milestone status change (`orch report` reads it) |
289
+ | `crash/` | the last screen of an agent that quit or vanished, newest 20 kept |
290
+
291
+ Every stop of the event manager writes a last line: `STOPPED: orch stop`, `STOPPED: the event manager exited (code 3)`, or `CRASHED: <error>` with the traceback. A manager killed without a word (the memory guard closing the terminal, a reboot) is found by the next `orch status`, `orch resume` or manager start, which looks up why in the computer's own log (`journalctl`, `coredumpctl`, boot time) and writes it, for example `[shop feature/cart] CRASHED: ... Reason: the memory guard (systemd-oomd) closed the terminal`. A kill is blamed on this run only when it names one of this run's own processes (recorded when the manager starts), so another project's crash is never written here. `orch doctor --crash` shows the last notes and saved screens. Sizes: `ORCH_LOG_MAX_MB` (default 2), `ORCH_CRASH_KEEP` (default 20).
292
+
293
+ The event manager starts in its own systemd scope when it can (`systemd-run --user --scope`), so a closed terminal or herdr pane does not take it down; elsewhere it starts as before (`ORCH_NO_SCOPE=1` turns this off).
294
+
274
295
  ### Contracts and reports
275
296
  `plan.md` stays the file you edit. From it `orch` generates a `task.json` for each milestone (numbered acceptance criteria `AC1…`, allowed files, interfaces, the commits of its dependencies). Coders answer with a `result-N.json` (status, commit message, files changed, the check they ran, each criterion met or not), and the reviewer with a `review-N.json` (a verdict per criterion plus findings). The old line formats (`COMMIT:`, `QUESTION:`, `BLOCKER:`) still work as a fallback. The shapes are in [docs/contracts.md](docs/contracts.md).
276
297
 
@@ -279,7 +300,7 @@ Every status change is written to `.orchestrate/events.jsonl`, and `orch report
279
300
  Optional plan header lines: `Lead mode: events | off` (default `events` when the plan has a `Lead:` line) · `Scope: warn | strict` · `Risk hold: on | off` · `Budget: 3h` (autopilot stops when its running time is used up) · `Estimate: 1h30m` (the lead's estimate for the feature) · `Setup inputs: <globs>` (which files mean "run setup again"; default: lockfiles and manifests). Per milestone: `Why separate` (why it is its own milestone; needed when the plan has more than one) · `Tier`, `Needs`, `Model why` (see [Models and tiers](#models-and-tiers)) · `Estimate: 40m` (dispatch to landed if nothing goes wrong) · `Parallel: allow` lets it run next to a milestone that shares its `Likely files`.
280
301
 
281
302
  ### Commands
282
- `orch status` · `orch resume` · `orch report` · `orch approve Mn` · `orch models [show|check <id>]` · `orch events [--peek]` · `orch dispatch Mn... [--to <worker>] [--tier <tier>]` · `orch answer Mn "<answer>"` · `orch fix Mn "<change>" [--to <worker>]` · `orch doctor [kind]` · `orch ready` · `orch autopilot` · `orch lead plan|run|check|whoami` · `orch agents [launch <kind> [--model <id>]|sync|check]` · `orch handoff Mn` · `orch needs-fix Mn` · `orch set M3 pending` · `orch park M2 paused "why"` · `orch cooldown claude-1 60` · `orch cleanup` · `orch finish [--no-push]` · `orch version` · `orch` (full help)
303
+ `orch status` · `orch resume` · `orch report` · `orch approve Mn` · `orch models [show|check <id>]` · `orch events [--peek]` · `orch dispatch Mn... [--to <worker>] [--tier <tier>]` · `orch answer Mn "<answer>"` · `orch fix Mn "<change>" [--to <worker>]` · `orch doctor [kind]` · `orch ready` · `orch autopilot` · `orch lead plan|run|check|whoami` · `orch agents [launch <kind> [--model <id>]|sync|check]` · `orch handoff Mn` · `orch needs-fix Mn` · `orch set M3 pending` · `orch park M2 paused "why"` · `orch cooldown claude-1 60` · `orch bench claude-1 off|on` · `orch stop [--now]` · `orch doctor --crash` · `orch cleanup` · `orch finish [--no-push]` · `orch version` · `orch` (full help)
283
304
 
284
305
  Tunables: `ORCH_CODER_BUDGET_MIN` (45) · `ORCH_REVIEW_BUDGET_MIN` (15) · `ORCH_CHECK_TIMEOUT_MIN` (30) · `ORCH_COOLDOWN_MIN` (60) · `ORCH_MAX_TASKS` (unset: no limit) · `ORCH_GONE_COOLDOWN_MIN` (10) · `ORCH_SEND_RETRY_S` (120) · `ORCH_HERDR_TIMEOUT_S` (30) · `ORCH_MAX_LOST` (4) · `ORCH_UNREACHABLE_MIN` (30) · `ORCH_CONFIRM_S` (30) · `ORCH_DOWN_MIN_S` (120: an event manager silent for longer was down, and that time is not counted) · `ORCH_RISK_MAX_LINES` (1500) · `ORCH_LEAD_WAIT_MIN` (15: ready work the lead hasn't dispatched starts by itself) · `ORCH_LEAD_CONFIRM_S` (30: a wake-up the lead did not pick up is sent again, doubling) · `ORCH_LEAD_REWAKE_S` (300) · `ORCH_LEAD_MAX_WAKES` (3) · `ORCH_LEAD_IDLE_MAX_MIN` (720: how long the event manager waits for an answer) · `ORCH_NO_AUTOSTART=1` (the lead's commands never start the event manager)
285
306
 
package/VERSION CHANGED
@@ -1 +1 @@
1
- 5.6.0
1
+ 5.7.0
Binary file
package/bin/orch CHANGED
@@ -35,6 +35,10 @@ LEAD_MAX_WAKES = int(os.environ.get("ORCH_LEAD_MAX_WAKES", "3")) # ...this m
35
35
  LEAD_WAIT_S = int(os.environ.get("ORCH_LEAD_WAIT_MIN", "15")) * 60 # ready work the lead never dispatched starts by itself
36
36
  LEAD_IDLE_MAX_S = int(os.environ.get("ORCH_LEAD_IDLE_MAX_MIN", "720")) * 60 # give up waiting for answers after this
37
37
  DOWN_MIN_S = int(os.environ.get("ORCH_DOWN_MIN_S", "120")) # the event manager silent for longer than this was down
38
+ STOP_WAIT_S = float(os.environ.get("ORCH_STOP_WAIT_S", "60")) # `orch stop` waits this long for the step it is on
39
+ TEAM_CONFIRM_S = float(os.environ.get("ORCH_TEAM_CONFIRM_S", "5")) # `team up` looks again after this: still running?
40
+ LOG_MAX_B = int(float(os.environ.get("ORCH_LOG_MAX_MB", "2")) * 1024 * 1024) # autopilot.log; one old copy is kept
41
+ CRASH_KEEP = int(os.environ.get("ORCH_CRASH_KEEP", "20")) # saved agent screens in .orchestrate/crash/
38
42
  MAX_FIX = 3
39
43
  MAX_REVIEW = 2
40
44
  MAX_CONFLICT = 2
@@ -158,7 +162,7 @@ def state_lock():
158
162
 
159
163
  # usable while autopilot drives: reads, and the lead's requests (the event manager carries them out)
160
164
  LEASE_FREE = {"status", "ready", "pick", "report", "approve", "autopilot", "events", "dispatch", "answer", "fix",
161
- "team", "resume"}
165
+ "team", "resume", "bench", "stop", "doctor"}
162
166
  _LEASE = None
163
167
 
164
168
 
@@ -253,6 +257,216 @@ def fault(point):
253
257
  os._exit(99)
254
258
 
255
259
 
260
+ # ---------------------------------------------------------------- logs and crash notes
261
+ # Everything stays in this repo's own .orchestrate/, so two projects run side by side never share a log. Crash
262
+ # notes start with `[<repo> <branch>]`, and a line from the computer's own log is only blamed on this run when it
263
+ # names one of this run's own processes (recorded when the event manager starts, and every few minutes).
264
+ JOURNALCTL = os.environ.get("ORCH_JOURNALCTL", "journalctl")
265
+ COREDUMPCTL = os.environ.get("ORCH_COREDUMPCTL", "coredumpctl")
266
+ PROCS_EVERY_S = 300
267
+ VANISH_CHECK_S = float(os.environ.get("ORCH_VANISH_CHECK_S", "30"))
268
+
269
+
270
+ def _rotate(path, limit):
271
+ """Keep a log under `limit` bytes: past it, the file becomes <name>.1 (one old copy) and a new one starts."""
272
+ try:
273
+ if path.exists() and path.stat().st_size > limit:
274
+ path.replace(path.with_name(path.name + ".1"))
275
+ except OSError:
276
+ pass
277
+
278
+
279
+ def log_line(msg):
280
+ """Append one timestamped line to .orchestrate/autopilot.log (size-capped)."""
281
+ p = ORCH / "autopilot.log"
282
+ _rotate(p, LOG_MAX_B)
283
+ try:
284
+ with p.open("a") as f:
285
+ f.write(f"[{time.strftime('%H:%M:%S')}] {msg}\n")
286
+ except OSError:
287
+ pass
288
+
289
+
290
+ def run_tag(st=None):
291
+ """`[<repo> <branch>]`: which project and run a crash note is about."""
292
+ branch = None
293
+ try:
294
+ branch = (st or load()).get("branch")
295
+ except (SystemExit, OSError, ValueError):
296
+ pass
297
+ return f"[{ROOT.name}{' ' + branch if branch else ''}]"
298
+
299
+
300
+ def save_screen(agent, why):
301
+ """Keep the last lines an agent's pane shows, while herdr can still read them, in .orchestrate/crash/
302
+ (only the newest CRASH_KEEP files are kept). Returns the file, or None when there was nothing to read."""
303
+ try:
304
+ r = subprocess.run([HERDR, "agent", "read", agent, "--source", "recent-unwrapped", "--lines", "40"],
305
+ text=True, capture_output=True, timeout=HERDR_TIMEOUT_S)
306
+ text = r.stdout.strip() if r.returncode == 0 else ""
307
+ except (OSError, subprocess.TimeoutExpired):
308
+ text = ""
309
+ if not text:
310
+ return None
311
+ d = ORCH / "crash"
312
+ d.mkdir(exist_ok=True)
313
+ f = d / f"{re.sub(r'[^A-Za-z0-9_.-]', '_', agent)}-{time.strftime('%Y%m%d-%H%M%S')}.txt"
314
+ f.write_text(f"{run_tag()} {agent}: {why}\nsaved {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
315
+ + "\n".join(text.splitlines()[-40:]) + "\n")
316
+ for old in sorted(d.glob("*.txt"), key=lambda p: p.stat().st_mtime)[:-CRASH_KEEP]:
317
+ with contextlib.suppress(OSError):
318
+ old.unlink()
319
+ return f
320
+
321
+
322
+ def _cgroup(pid):
323
+ try:
324
+ for line in Path(f"/proc/{pid}/cgroup").read_text().splitlines():
325
+ if line.startswith("0::"):
326
+ return line[3:].strip() or None
327
+ except OSError:
328
+ pass
329
+ return None
330
+
331
+
332
+ def run_processes(st):
333
+ """This run's own processes: the event manager, herdr, and every process working in the run's folders (the
334
+ agents and what they started). {pid: name} plus their cgroups. Empty where /proc does not exist."""
335
+ procs, groups = {}, set()
336
+ if not Path("/proc").is_dir():
337
+ return {"procs": {}, "cgroups": []}
338
+ folders = [str(ROOT)] + [w["dir"] for w in st.get("workers", {}).values() if w.get("dir")]
339
+ me = os.getpid()
340
+ for d in Path("/proc").iterdir():
341
+ if not d.name.isdigit():
342
+ continue
343
+ try:
344
+ comm = (d / "comm").read_text().strip()
345
+ if int(d.name) != me and comm != "herdr":
346
+ cwd = os.readlink(d / "cwd")
347
+ if not any(_inside(cwd, f) for f in folders):
348
+ continue
349
+ except OSError:
350
+ continue
351
+ procs[d.name] = comm
352
+ if len(procs) >= 300:
353
+ break
354
+ procs[str(me)] = "orch autopilot"
355
+ for pid in procs:
356
+ g = _cgroup(pid)
357
+ if g:
358
+ groups.add(g)
359
+ return {"procs": procs, "cgroups": sorted(groups)[:60]}
360
+
361
+
362
+ def boot_time():
363
+ if os.environ.get("ORCH_BOOT_TIME"):
364
+ return int(os.environ["ORCH_BOOT_TIME"])
365
+ try:
366
+ for line in Path("/proc/stat").read_text().splitlines():
367
+ if line.startswith("btime "):
368
+ return int(line.split()[1])
369
+ except (OSError, ValueError):
370
+ pass
371
+ return None
372
+
373
+
374
+ def _lines(cmd):
375
+ try:
376
+ r = subprocess.run(cmd, text=True, capture_output=True, timeout=20)
377
+ except (OSError, subprocess.TimeoutExpired):
378
+ return []
379
+ return r.stdout.splitlines()[-3000:] if r.returncode == 0 else []
380
+
381
+
382
+ OOMD_RE = re.compile(r"systemd-oomd.*?Killed (/\S+)")
383
+ KOOM_RE = re.compile(r"(?:Out of memory: Killed process|oom-kill:.*?pid=)\s*(\d+)(?:\s*\(([^)]+)\))?")
384
+ SLEEP_RE = re.compile(r"PM: suspend entry|Suspending system|The system will suspend|Entering sleep state")
385
+ DOWN_RE = re.compile(r"System is powering down|System is rebooting|The system will (?:power off|reboot)|"
386
+ r"Shutting down\.|Power key pressed")
387
+
388
+
389
+ def crash_reason(rec, last):
390
+ """Why a run's processes stopped around `last` (epoch), from the computer's own logs. Returns (reason, evidence
391
+ lines). Only kills that name one of this run's processes or cgroups count; the rest is reported as such."""
392
+ procs = (rec or {}).get("procs") or {}
393
+ groups = (rec or {}).get("cgroups") or []
394
+ since, until = int(last) - 300, int(last) + 600
395
+ bt = boot_time()
396
+ if bt and bt > last:
397
+ return (f"the computer was restarted (it booted at {_clock(bt)}, after orch was last alive at "
398
+ f"{_clock(last)})", [])
399
+ lines = _lines([JOURNALCTL, "--no-pager", "-q", "-o", "short-iso", "--since", f"@{since}", "--until", f"@{until}"])
400
+ lines += _lines([JOURNALCTL, "--no-pager", "-q", "-o", "short-iso", "-k", "--since", f"@{since}",
401
+ "--until", f"@{until}"])
402
+ other = []
403
+ for line in lines:
404
+ m = OOMD_RE.search(line)
405
+ if m:
406
+ killed = m.group(1).rstrip(".,")
407
+ if any(g == killed or g.startswith(killed.rstrip("/") + "/") for g in groups):
408
+ return ("the memory guard (systemd-oomd) closed the terminal or app this run was in, because the "
409
+ "computer was low on memory", [line.strip()[:300]])
410
+ other.append(line.strip()[:300])
411
+ continue
412
+ m = KOOM_RE.search(line)
413
+ if m:
414
+ if m.group(1) in procs:
415
+ name = procs[m.group(1)]
416
+ return (f"out of memory: the system killed {name} (pid {m.group(1)})", [line.strip()[:300]])
417
+ other.append(line.strip()[:300])
418
+ continue
419
+ if SLEEP_RE.search(line):
420
+ return "the computer went to sleep", [line.strip()[:300]]
421
+ if DOWN_RE.search(line):
422
+ return "the computer was shut down or restarted", [line.strip()[:300]]
423
+ for line in _lines([COREDUMPCTL, "list", "--no-pager", "-q", "--since", f"@{since}", "--until", f"@{until}"]):
424
+ parts = line.split()
425
+ pid = next((p for p in parts if p.isdigit() and p in procs), None)
426
+ if pid or "herdr" in line:
427
+ return (f"{procs.get(pid, 'herdr')} crashed (a core dump was written)", [line.strip()[:300]])
428
+ if other:
429
+ return (f"unknown — the system log shows {len(other)} kill(s) then, but not of this run's processes "
430
+ f"(another project or app)", other[:3])
431
+ if not lines:
432
+ return "unknown — the system log could not be read (journalctl missing, or no permission)", []
433
+ return "unknown — the system log has nothing about it at that time", []
434
+
435
+
436
+ def note_dead_manager(st, save_it=True, starting=False):
437
+ """An event manager that died without its last line (killed: memory, a closed terminal, a crash of the whole
438
+ app) is found here, once: the reason is looked up and written to autopilot.log. Returns the note, or None."""
439
+ m = (st.get("run") or {}).get("manager")
440
+ if not m or m.get("ended") or m.get("host") not in (None, socket.gethostname()):
441
+ return None
442
+ if starting: # the new manager holds the lease now: the old one is dead unless it is us
443
+ if m.get("pid") == os.getpid():
444
+ return None
445
+ elif driver_alive():
446
+ return None
447
+ last = (st.get("run") or {}).get("beat") or m.get("started") or now()
448
+ reason, evidence = crash_reason(m, last)
449
+ m["ended"] = {"ts": now(), "how": "died", "reason": reason, "last_alive": last}
450
+ note = (f"{run_tag(st)} CRASHED: the event manager (pid {m.get('pid')}) stopped without a word; last alive "
451
+ f"{_clock(last)}. Reason: {reason}")
452
+ log_line(note)
453
+ for e in evidence:
454
+ log_line(f"{run_tag(st)} system log: {e}")
455
+ if save_it:
456
+ save(st)
457
+ return note + "".join(f"\n system log: {e}" for e in evidence)
458
+
459
+
460
+ def last_crash_lines(n=12):
461
+ """The newest crash, stop and lost notes from autopilot.log (and its old copy)."""
462
+ out = []
463
+ for p in (ORCH / "autopilot.log.1", ORCH / "autopilot.log"):
464
+ if p.exists():
465
+ out += [l for l in p.read_text(errors="replace").splitlines()
466
+ if re.search(r"\] (CRASHED|STOPPED|QUIT|LOST|HERDR RESTART\?)|system log:", l)]
467
+ return out[-n:]
468
+
469
+
256
470
  # Every status change goes through move(). Statuses not listed as a key are terminal.
257
471
  _PARK = {"pending", "paused", "failed"}
258
472
  TRANSITIONS = {
@@ -285,6 +499,8 @@ def move(st, tid, to, why=None, force=False):
285
499
  t["status"] = to
286
500
  if why is not None:
287
501
  t["reason"] = why
502
+ elif to != frm and to in ("coding", "verifying", "reviewing"):
503
+ t["reason"] = "" # work goes on: an old note ("hit a usage limit") no longer describes it
288
504
  if to != frm or why:
289
505
  ev = {"ts": now(), "task": tid, "from": frm, "to": to, "why": why or "",
290
506
  "agent": t.get("worker") or t.get("last_worker"), "attempt": t.get("attempt", 0)}
@@ -364,21 +580,61 @@ def _status_field(obj):
364
580
  return found if found is not None else _find_key(obj, "status")
365
581
 
366
582
 
367
- def herdr_state(agent):
368
- """The agent's lowercased status from `herdr agent get`, or None if herdr can't find it.
369
- Only the status field is matched, so a name or path containing "working" or "blocked" is not misread;
370
- output that isn't JSON falls back to the whole text."""
583
+ def _shell_only(obj):
584
+ """True when herdr knows the name but no agent runs in its pane: the JSON says `"agent": null` (or empty),
585
+ or it has no status at all. That pane is a plain shell (the agent quit, or never started), and a prompt
586
+ sent there would be typed into the shell."""
587
+ if not isinstance(obj, (dict, list)):
588
+ return False
589
+ if _status_field(obj) is None:
590
+ return True
591
+ stack = [obj]
592
+ while stack:
593
+ o = stack.pop()
594
+ if isinstance(o, dict):
595
+ if "agent" in o and o["agent"] in (None, "", False):
596
+ return True
597
+ stack.extend(o.values())
598
+ elif isinstance(o, list):
599
+ stack.extend(o)
600
+ return False
601
+
602
+
603
+ def herdr_presence(agent):
604
+ """("agent", status) when herdr runs the agent, ("shell", None) when the name is on a pane with no agent in
605
+ it, ("gone", None) when herdr can't find the name (or can't be reached)."""
371
606
  try:
372
607
  r = subprocess.run([HERDR, "agent", "get", agent], text=True, capture_output=True, timeout=HERDR_TIMEOUT_S)
373
608
  except (OSError, subprocess.TimeoutExpired):
374
- return None
609
+ return "gone", None
375
610
  if r.returncode != 0:
376
- return None
611
+ return "gone", None
377
612
  try:
378
- status = _status_field(json.loads(r.stdout))
613
+ data = json.loads(r.stdout)
379
614
  except ValueError:
380
- status = None
381
- return (status if status is not None else r.stdout + r.stderr).lower()
615
+ return "agent", (r.stdout + r.stderr).lower() # not JSON: the whole text, as before
616
+ if _shell_only(data):
617
+ return "shell", None
618
+ return "agent", _status_field(data).lower()
619
+
620
+
621
+ def herdr_state(agent):
622
+ """The agent's lowercased status from `herdr agent get`, or None if herdr can't find it, or only a shell is
623
+ left in its pane. Only the status field is matched, so a name or path containing "working" or "blocked" is
624
+ not misread; output that isn't JSON falls back to the whole text."""
625
+ return herdr_presence(agent)[1]
626
+
627
+
628
+ def presence_word(st, name):
629
+ """What `orch status` says about an agent's pane: ok, detect:off, NO AGENT, SHELL ONLY, or a stale pane id."""
630
+ info = agent_info(st, name)
631
+ if info.get("pane"):
632
+ ok, _, _ = _herdr_json([HERDR, "pane", "get", info["pane"]])
633
+ return "ok" if ok else "STALE PANE"
634
+ if not info.get("detect", True):
635
+ return "detect:off"
636
+ where, _ = herdr_presence(name)
637
+ return {"agent": "ok", "shell": "SHELL ONLY", "gone": "NO AGENT"}[where]
382
638
 
383
639
 
384
640
  def word(state, *words):
@@ -545,10 +801,12 @@ def need_rank(t):
545
801
  def eligible_workers(st, t):
546
802
  """Workers allowed to take the task: its tier or higher (unrated workers count as any tier). When nobody on the
547
803
  team reaches the tier, the strongest workers the team has, so a run never waits for a model nobody started."""
548
- if t.get("assign") in st["workers"]:
804
+ if t.get("assign") in st["workers"] and not st["workers"][t["assign"]].get("off"):
549
805
  return [t["assign"]]
550
806
  need = need_rank(t)
551
- ranks = {n: rank(w.get("tier")) for n, w in st["workers"].items()}
807
+ ranks = {n: rank(w.get("tier")) for n, w in st["workers"].items() if not w.get("off")} # `orch bench <w> off`
808
+ if not ranks:
809
+ return []
552
810
  ok = [n for n, r in ranks.items() if not need or not r or r >= need]
553
811
  if not ok:
554
812
  top = max(ranks.values())
@@ -1034,6 +1292,7 @@ def cmd_sync(args):
1034
1292
  ow = old.get("workers", {}).get(name, {})
1035
1293
  st["workers"][name] = {"kind": kind, "task": ow.get("task"), "cooldown_until": ow.get("cooldown_until", 0),
1036
1294
  "cooldown_reason": ow.get("cooldown_reason", ""),
1295
+ **({"off": ow["off"]} if ow.get("off") else {}), # kept until `orch bench <w> on`
1037
1296
  "dir": ow.get("dir"), "setup_done": ow.get("setup_done", False),
1038
1297
  "setup_hash": ow.get("setup_hash"), "delivery_fails": ow.get("delivery_fails", 0),
1039
1298
  "pane": pane, "detect": detect(kind, pane, "Workers"),
@@ -1630,7 +1889,15 @@ def cmd_ready(args):
1630
1889
  slots = free_slots(st)
1631
1890
  if st["isolation"] == "shared" and slots <= 0 and active_count(st) == len(fix_jobs(st)) and fix_jobs(st):
1632
1891
  slots = 1 # shared mode: a queued fix job IS the active milestone, and it needs a coder
1892
+ # only coders herdr can see count as free: a coder with no agent can't take work, whatever its task field says
1893
+ present = [n for n, w in st["workers"].items() if not w.get("task") and not w.get("off") and not cooling(n, w)
1894
+ and (not w.get("detect", True) or w.get("pane") or herdr_state(n) is not None)]
1895
+ gone = [n for n, w in st["workers"].items() if not w.get("task") and not w.get("off") and w.get("detect", True)
1896
+ and not w.get("pane") and herdr_state(n) is None]
1897
+ slots = min(slots, len(present))
1633
1898
  print(f"SLOTS {max(slots, 0)}")
1899
+ if gone:
1900
+ print(f"NOAGENT {' '.join(gone)} (no agent in herdr: `orch team up`)")
1634
1901
  for tid in fix_jobs(st): # fixes first: reviewed work merges sooner and unlocks dependents
1635
1902
  print(f"FIX {tid} {st['tasks'][tid]['status']} {st['tasks'][tid]['title']}")
1636
1903
  for tid in out:
@@ -1649,7 +1916,7 @@ def cooling(name, info):
1649
1916
 
1650
1917
 
1651
1918
  def worker_free(st, name, w):
1652
- if w.get("task") or cooling(name, w):
1919
+ if w.get("task") or w.get("off") or cooling(name, w):
1653
1920
  return False
1654
1921
  if not w.get("detect", True): # herdr can't watch it: no task + no cooldown = free
1655
1922
  return True
@@ -2514,6 +2781,70 @@ def cmd_cooldown(args):
2514
2781
  print(f"COOLDOWN {name} for {args[1]} min" + (f" ({reason})" if reason else ""))
2515
2782
 
2516
2783
 
2784
+ def cmd_bench(args):
2785
+ """orch bench <worker> off [reason] | on -> keep a coder out of the run until the developer says otherwise.
2786
+ Unlike a cooldown it never ends by itself: not after a restart, `orch sync`, `orch resume` or `orch team up`."""
2787
+ need(args, 2, "bench <worker> off [reason] | bench <worker> on")
2788
+ name, mode, reason = args[0], args[1], " ".join(args[2:]).strip()
2789
+ if mode not in ("off", "on"):
2790
+ die("usage: orch bench <worker> off [reason] | orch bench <worker> on")
2791
+ with state_lock():
2792
+ st = load()
2793
+ if name not in st["workers"]:
2794
+ die(f"unknown worker {name!r} — workers: {', '.join(st['workers'])}"
2795
+ + (" (the reviewer can't be benched this way: change `Reviewer:` in plan.md)"
2796
+ if name == st.get("reviewer") else ""))
2797
+ w = st["workers"][name]
2798
+ if mode == "on":
2799
+ was = w.pop("off", None)
2800
+ save(st)
2801
+ print(f"ON {name} takes work again" if was else f"ON {name} was not off")
2802
+ return
2803
+ w["off"] = {"ts": now(), "why": reason or "the developer said so"}
2804
+ moved = [tid for tid in st["order"] if st["tasks"][tid].get("assign") == name
2805
+ and st["tasks"][tid]["status"] not in ("merged", "skipped")]
2806
+ for tid in moved:
2807
+ st["tasks"][tid].pop("assign", None) # `--to <this worker>` no longer holds it back
2808
+ save(st)
2809
+ print(f"OFF {name}: gets no new work until `orch bench {name} on` ({w['off']['why']})")
2810
+ if moved:
2811
+ print(f" {', '.join(moved)} no longer wait for {name}: the next free coder takes them")
2812
+ if w.get("task"):
2813
+ print(f" it still holds {w['task']}: that one finishes here. To move it now: "
2814
+ f"`orch set {w['task']} paused`, then `orch dispatch {w['task']}`")
2815
+ if not eligible_workers(st, {"tier": None, "min_tier": None}):
2816
+ print("WARN every coder is off now: nothing new starts until one is back on")
2817
+
2818
+
2819
+ def cmd_stop(args):
2820
+ """orch stop [--now] -> stop the event manager cleanly: it finishes the step it is on (a check, a merge) and
2821
+ exits; every event and all work are kept. Then change the run (plan.md + `orch sync`, `orch team up`) and
2822
+ start it again with `orch resume`. --now also stops the step it is on."""
2823
+ if not driver_alive():
2824
+ print("the event manager is not running")
2825
+ return
2826
+ info = driver_info()
2827
+ pid = info.get("pid")
2828
+ if info.get("host") not in (None, socket.gethostname()):
2829
+ die(f"the event manager runs on {info.get('host')}: stop it there")
2830
+ if not isinstance(pid, int):
2831
+ die("can't tell the event manager's process id from .orchestrate/driver.lock")
2832
+ (ORCH / "stop.request").write_text(json.dumps({"ts": now(), "now": "--now" in args}))
2833
+ for _ in range(2 if "--now" in args else 1):
2834
+ with contextlib.suppress(OSError):
2835
+ os.kill(pid, signal.SIGTERM)
2836
+ time.sleep(0.3)
2837
+ end = time.time() + STOP_WAIT_S
2838
+ while time.time() < end and driver_alive():
2839
+ time.sleep(0.25)
2840
+ if driver_alive():
2841
+ print(f"STOPPING the event manager (pid {pid}) is finishing its current step and stops right after it. "
2842
+ f"`orch status` shows when it has; `orch stop --now` stops it at once.")
2843
+ sys.exit(3)
2844
+ print(f"STOPPED the event manager (pid {pid}). Nothing is lost. Change what you need (plan.md + `orch sync`, "
2845
+ f"`orch team up`), then start it again with `orch resume`.")
2846
+
2847
+
2517
2848
  STATUSES = {"pending", "coding", "verifying", "awaiting-review", "reviewing", "reviewed", "committed", "merged",
2518
2849
  "needs-answer", "paused", "failed", "conflict", "skipped", "needs-fix", "held"}
2519
2850
 
@@ -2544,6 +2875,10 @@ def cmd_set(args):
2544
2875
 
2545
2876
  def cmd_status(args):
2546
2877
  st = load()
2878
+ dead = None if driver_alive() else note_dead_manager(st)
2879
+ here = {n: presence_word(st, n) for n in st["workers"]} # ask herdr first, then print in one go
2880
+ if dead:
2881
+ print("!! " + dead.replace("\n", "\n!! "))
2547
2882
  if driver_alive():
2548
2883
  print(f"driven by {driver_line(driver_info())}")
2549
2884
  elif needs_manager(st):
@@ -2561,17 +2896,27 @@ def cmd_status(args):
2561
2896
  f"{st['integration_broken']} — fix it; autopilot re-checks before it continues")
2562
2897
  for n, w in st["workers"].items():
2563
2898
  cd = max(0, w.get("cooldown_until", 0) - now())
2899
+ h = here[n]
2900
+ state = ("OFF (" + (w["off"].get("why") or "developer") + ")" if w.get("off") else
2901
+ f"coding {w['task']}" if w.get("task") else
2902
+ f"benched {cd // 60}m ({w.get('cooldown_reason') or 'cooldown'})" if cd else "free")
2564
2903
  print(f" worker {n:<12} {w['kind']:<8} task={w.get('task') or '-':<5} "
2565
2904
  + (f"model={w['model']} ({w.get('tier') or 'unrated'}) " if w.get("model") else "")
2566
2905
  + f"{'cooldown ' + str(cd // 60) + 'm' if cd else ''}"
2567
- f"{'' if w.get('detect', True) else ' detect:off'}")
2906
+ f"{'' if w.get('detect', True) else ' detect:off'}"
2907
+ + f" herdr={h} state={state}"
2908
+ + (" !! no agent: `orch team up` (or `orch resume` after a restart)" if h in ("NO AGENT", "SHELL ONLY")
2909
+ else ""))
2568
2910
  for tid in st["order"]:
2569
2911
  t = st["tasks"][tid]
2570
2912
  print(f" {tid:<4} {t['status']:<15} deps={','.join(t['deps']) or '-':<10} "
2571
2913
  f"worker={t.get('worker') or '-':<10} "
2572
2914
  + (f"tier={t['tier'] if rank(t.get('min_tier')) <= rank(t.get('tier')) else t['min_tier'] + '^'} "
2573
2915
  if need_rank(t) else "") + t["title"]
2574
- + (f" [{t['reason']}]" if t.get("reason") else ""))
2916
+ + (f" [{t['reason']}]" if t.get("reason") else "")
2917
+ + (f" !! but {t['worker']} has no agent in herdr ({here[t['worker']]}): nothing is working on it — "
2918
+ f"`orch resume`" if t["status"] in ("coding", "conflict") and here.get(t.get("worker"))
2919
+ in ("NO AGENT", "SHELL ONLY") else ""))
2575
2920
  if lead_on(st):
2576
2921
  ev = [e for e in st["lead_events"] if event_open(st, e)]
2577
2922
  hold = undispatched(st)
@@ -2803,14 +3148,29 @@ def start_manager():
2803
3148
  return f"the event manager is running ({driver_line(driver_info())})"
2804
3149
  if os.environ.get("ORCH_NO_AUTOSTART") == "1":
2805
3150
  return "the event manager is NOT running — ask the developer to run `orch autopilot` in a terminal"
2806
- with open(ORCH / "manager.out", "a") as out:
2807
- subprocess.Popen([sys.executable, os.path.abspath(__file__), "autopilot"], cwd=ROOT, stdin=subprocess.DEVNULL,
2808
- stdout=out, stderr=subprocess.STDOUT, start_new_session=True,
2809
- env={k: v for k, v in os.environ.items() if not k.startswith("ORCH_DRIVER")})
2810
- for _ in range(20):
2811
- time.sleep(0.25)
2812
- if driver_alive():
2813
- return "started the event manager (`orch autopilot`, log: .orchestrate/autopilot.log)"
3151
+ _rotate(ORCH / "manager.out", LOG_MAX_B // 2)
3152
+ env = {k: v for k, v in os.environ.items() if not k.startswith("ORCH_DRIVER")}
3153
+ cmd = [sys.executable, os.path.abspath(__file__), "autopilot"]
3154
+ # In its own systemd scope the manager is not part of the terminal (or herdr pane) it was started from: when the
3155
+ # memory guard closes that terminal, or herdr restarts, the manager keeps watching and says what it saw.
3156
+ unit = f"orch-{re.sub(r'[^A-Za-z0-9]', '-', ROOT.name)[:30]}-{os.getpid()}"
3157
+ tries = []
3158
+ if os.environ.get("ORCH_NO_SCOPE") != "1" and shutil.which("systemd-run"):
3159
+ tries.append((["systemd-run", "--user", "--scope", "--quiet", "--collect", f"--unit={unit}"] + cmd,
3160
+ {**env, "ORCH_SCOPE": unit}))
3161
+ tries.append((cmd, env))
3162
+ for argv, e in tries:
3163
+ with open(ORCH / "manager.out", "a") as out:
3164
+ p = subprocess.Popen(argv, cwd=ROOT, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT,
3165
+ start_new_session=True, env=e)
3166
+ for _ in range(20):
3167
+ time.sleep(0.25)
3168
+ if driver_alive():
3169
+ return ("started the event manager (`orch autopilot`" + (f", in its own scope {unit} so a closed "
3170
+ f"terminal does not stop it" if argv[0] == "systemd-run" else "")
3171
+ + ", log: .orchestrate/autopilot.log)")
3172
+ if p.poll() is not None:
3173
+ break # systemd-run can't reach the user session: start it the plain way
2814
3174
  return ("could NOT start the event manager from here (see .orchestrate/manager.out) — ask the developer to run "
2815
3175
  "`orch autopilot` in a terminal")
2816
3176
 
@@ -2829,6 +3189,16 @@ def cmd_dispatch(args):
2829
3189
  st = load()
2830
3190
  if opts.get("--to") and opts["--to"] not in st["workers"]:
2831
3191
  die(f"unknown worker {opts['--to']!r} — workers: {', '.join(st['workers'])}")
3192
+ if opts.get("--to"):
3193
+ to = opts["--to"]
3194
+ if st["workers"][to].get("off"):
3195
+ die(f"{to} is off ({st['workers'][to]['off'].get('why')}): `orch bench {to} on` first, or pick another "
3196
+ f"worker")
3197
+ here = presence_word(st, to)
3198
+ if here not in ("ok", "detect:off"):
3199
+ die(f"{to} has no agent in herdr ({here}" + (": only a plain shell is left in its pane" if here ==
3200
+ "SHELL ONLY" else "") + f"). Run `orch team up` (or `orch resume` after a restart), check that "
3201
+ f"`orch status` shows {to} as ok, then dispatch again")
2832
3202
  if opts.get("--tier") and opts["--tier"] not in TIERS:
2833
3203
  die("--tier must be small, medium or high")
2834
3204
  for tid in args:
@@ -2849,8 +3219,14 @@ def cmd_dispatch(args):
2849
3219
  _park(st, tid, "pending", "dispatched again by the lead")
2850
3220
  who = [n for n in eligible_workers(st, t)]
2851
3221
  waits = [d for d in t["deps"] if st["tasks"][d]["status"] != "merged"]
2852
- print(f"DISPATCH {tid} -> {' or '.join(who)}" + (f" (tier {TIERS[need_rank(t) - 1]})" if need_rank(t) else "")
3222
+ print(f"DISPATCH {tid} -> {' or '.join(who) or 'nobody (every coder is off)'}"
3223
+ + (f" (tier {TIERS[need_rank(t) - 1]})" if need_rank(t) else "")
2853
3224
  + (f" — starts when {', '.join(waits)} merged" if waits else ""))
3225
+ if who and not opts.get("--to"):
3226
+ missing = [n for n in who if presence_word(st, n) not in ("ok", "detect:off")]
3227
+ if len(missing) == len(who):
3228
+ print(f"WARN none of them has an agent in herdr right now ({', '.join(missing)}): {tid} waits "
3229
+ f"until one does. Run `orch team up` (or `orch resume` after a restart)")
2854
3230
  save(st)
2855
3231
  print(start_manager())
2856
3232
  print("You will be woken with `orch events` when something needs you. Stop here; do not poll.")
@@ -2986,6 +3362,13 @@ EVENT_HELP = {
2986
3362
  "reviewer-lost": "the reviewer can't be reached, so the milestone waits for review (its work is kept). Tell the "
2987
3363
  "developer the fix in the event text (usually: rename the reviewer's new pane). Review resumes "
2988
3364
  "by itself once herdr finds the reviewer again.",
3365
+ "worker-lost": "a coder vanished while it worked (pane closed, agent quit, herdr restarted). Its milestone "
3366
+ "waits for the next free coder with the work so far. This is NOT routine: tell the developer at "
3367
+ "once, with the exact fix from the event text (`orch resume` or `orch team up`). If the developer "
3368
+ "does not want that coder any more: `orch bench <worker> off`.",
3369
+ "herdr-restart": "most agents vanished at once: herdr was probably restarted or closed. Tell the developer to "
3370
+ "run `orch resume` (it names the panes again and re-sends the work); then `orch team up` for "
3371
+ "any agent it reports LOST.",
2989
3372
  "all_done": "every milestone landed. Finish .orchestrate/summary.md (see `orch lead run`, section ALL_DONE).",
2990
3373
  "stopped": "the event manager stopped. Tell the developer why; they run `orch resume` (or `orch autopilot`).",
2991
3374
  }
@@ -3122,25 +3505,138 @@ RATE_RE = re.compile(r"usage limit|rate.?limit|quota|too many requests|\b429\b|l
3122
3505
  re.I)
3123
3506
 
3124
3507
 
3508
+ class _Stop(BaseException):
3509
+ """`orch stop` (or a closed terminal) asked the event manager to stop: unwinds to cmd_autopilot."""
3510
+
3511
+
3512
+ _STOP = {"asked": None, "child": None}
3513
+
3514
+
3515
+ def _on_stop_signal(signum, _frame):
3516
+ """First signal: stop at the next safe point (a running `orch poll` is ended, as it only waits). Second: now."""
3517
+ why = "terminal closed (SIGHUP)" if signum == getattr(signal, "SIGHUP", None) else "SIGTERM"
3518
+ try:
3519
+ req = json.loads((ORCH / "stop.request").read_text())
3520
+ if now() - req.get("ts", 0) < 120:
3521
+ why = "orch stop" + (" --now" if req.get("now") else "")
3522
+ except (OSError, ValueError):
3523
+ pass
3524
+ again = _STOP["asked"] is not None
3525
+ _STOP["asked"] = why
3526
+ child = _STOP["child"]
3527
+ if child is not None and child[0].poll() is None and (again or child[1] == "poll"):
3528
+ with contextlib.suppress(OSError):
3529
+ child[0].terminate()
3530
+ if again:
3531
+ raise _Stop()
3532
+
3533
+
3534
+ def _stop_point():
3535
+ if _STOP["asked"]:
3536
+ raise _Stop()
3537
+
3538
+
3125
3539
  def cmd_autopilot(args):
3540
+ """The event manager (see _autopilot). This wrapper records how it ends: every stop writes a last line to
3541
+ autopilot.log, a Python error writes the traceback, and a manager that was killed without a word (memory guard,
3542
+ a crash of the whole terminal) is found by the next one, which looks up why in the computer's own log."""
3543
+ take_lease()
3544
+ if STATE.exists():
3545
+ manager_begin()
3546
+ tag = run_tag() if STATE.exists() else f"[{ROOT.name}]"
3547
+ with contextlib.suppress(ValueError, OSError):
3548
+ signal.signal(signal.SIGTERM, _on_stop_signal)
3549
+ signal.signal(signal.SIGHUP, _on_stop_signal)
3550
+
3551
+ def ended(how, detail=""):
3552
+ nonlocal tag
3553
+ if STATE.exists():
3554
+ tag = run_tag()
3555
+ with contextlib.suppress(BaseException):
3556
+ with state_lock():
3557
+ s_ = load()
3558
+ m = s_["run"].get("manager") or {}
3559
+ if m.get("pid") == os.getpid():
3560
+ m["ended"] = {"ts": now(), "how": how, "reason": detail[:300]}
3561
+ s_["run"]["manager"] = m
3562
+ save(s_)
3563
+ try:
3564
+ _autopilot(args)
3565
+ ended("finished")
3566
+ log_line(f"{tag} STOPPED: the event manager finished")
3567
+ except _Stop:
3568
+ why = _STOP["asked"] or "stop"
3569
+ ended("stopped", why)
3570
+ log_line(f"{tag} STOPPED: {why} — nothing is lost; `orch resume` starts it again")
3571
+ print(f"STOPPED ({why})", flush=True)
3572
+ with contextlib.suppress(OSError):
3573
+ (ORCH / "stop.request").unlink()
3574
+ sys.exit(0)
3575
+ except SystemExit as e:
3576
+ code = e.code if isinstance(e.code, int) else (0 if e.code is None else 1)
3577
+ ended("exit", f"exit {code}")
3578
+ log_line(f"{tag} STOPPED: the event manager exited (code {code}); the line above says why")
3579
+ raise
3580
+ except KeyboardInterrupt:
3581
+ ended("stopped", "Ctrl-C")
3582
+ log_line(f"{tag} STOPPED: Ctrl-C")
3583
+ raise
3584
+ except BaseException as e:
3585
+ import traceback
3586
+ tb = traceback.format_exc()
3587
+ ended("crashed", f"{type(e).__name__}: {e}")
3588
+ log_line(f"{tag} CRASHED: {type(e).__name__}: {e}")
3589
+ for l in tb.rstrip().splitlines()[-40:]:
3590
+ log_line(f"{tag} {l}")
3591
+ if shutil.which("notify-send"):
3592
+ subprocess.run(["notify-send", "orch autopilot", f"{tag} CRASHED: {type(e).__name__}: {e}"],
3593
+ capture_output=True)
3594
+ raise
3595
+
3596
+
3597
+ def manager_begin():
3598
+ """The event manager starting: report a predecessor that died without a word, then record this one (pid, host,
3599
+ this run's processes) so the next one can do the same for it. Safe to call twice."""
3600
+ with state_lock():
3601
+ st = load()
3602
+ m = st["run"].get("manager") or {}
3603
+ if m.get("pid") == os.getpid():
3604
+ return
3605
+ dead = note_dead_manager(st, save_it=False, starting=True)
3606
+ if dead:
3607
+ print(dead, flush=True)
3608
+ if shutil.which("notify-send"):
3609
+ subprocess.run(["notify-send", "orch autopilot", dead.splitlines()[0]], capture_output=True)
3610
+ st["run"]["manager"] = {"pid": os.getpid(), "host": socket.gethostname(), "started": now(),
3611
+ "scope": os.environ.get("ORCH_SCOPE") or None, **run_processes(st)}
3612
+ save(st)
3613
+
3614
+
3615
+ def _autopilot(args):
3126
3616
  """The event manager: a plain script that watches the agents, runs checks, sends fixes and reviews, merges, and
3127
3617
  wakes the lead when something needs a decision. It is the only driver of a run: it holds the driver lease, and
3128
3618
  other processes can't change the run meanwhile (the lead's `orch dispatch` / `orch answer` are requests it
3129
3619
  carries out). Without a lead (`Lead mode: off`) it dispatches by itself and stops (exit 3) when a human is needed."""
3130
3620
  me = [sys.executable, os.path.abspath(__file__)]
3131
- log = ORCH / "autopilot.log"
3132
- take_lease()
3621
+ if os.environ.get("ORCH_FAULT") == "autopilot-error":
3622
+ raise ValueError("test crash") # test hook: a Python error inside the event manager
3133
3623
 
3134
3624
  def say(msg, important=False):
3135
- line = f"[{time.strftime('%H:%M:%S')}] {msg}"
3136
- print(line, flush=True)
3137
- with log.open("a") as f:
3138
- f.write(line + "\n")
3625
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
3626
+ log_line(msg)
3139
3627
  if important and shutil.which("notify-send"):
3140
3628
  subprocess.run(["notify-send", "orch autopilot", msg], capture_output=True)
3141
3629
 
3142
3630
  def run(*a, ok=(0,)):
3143
- r = subprocess.run(me + [str(x) for x in a], text=True, capture_output=True)
3631
+ _stop_point()
3632
+ p = subprocess.Popen(me + [str(x) for x in a], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
3633
+ _STOP["child"] = (p, str(a[0]))
3634
+ try:
3635
+ so, se = p.communicate()
3636
+ finally:
3637
+ _STOP["child"] = None
3638
+ r = subprocess.CompletedProcess(p.args, p.returncode, so, se)
3639
+ _stop_point() # `orch stop` came while it ran: the step is done, stop here
3144
3640
  out = (r.stdout + r.stderr).strip()
3145
3641
  if r.returncode not in ok:
3146
3642
  raise RuntimeError(f"orch {' '.join(str(x) for x in a)} -> exit {r.returncode}: {out}")
@@ -3529,11 +4025,24 @@ def cmd_autopilot(args):
3529
4025
  run("cooldown", agent, GONE_COOLDOWN_MIN, "gone")
3530
4026
  say(f"reviewer {agent} is gone — restart it; {tid} waits for review (the coder's work is kept)", True)
3531
4027
  else:
4028
+ where, _ = herdr_presence(agent)
4029
+ shell = where == "shell"
4030
+ saved = save_screen(agent, f"no agent left in its pane while it worked on {tid}") if shell else None
4031
+ what = ("its pane is still there, but only a plain shell is left in it (the agent quit)" if shell
4032
+ else "herdr can't find it (its pane was closed, or herdr restarted)")
4033
+ fix = ("run `orch team up`: it starts the agent again in that pane" if shell else
4034
+ "run `orch resume` if herdr restarted (it finds the pane by folder and names it again), "
4035
+ "else `orch team up` to open a new pane")
3532
4036
  park(tid, "pending", f"{agent} disappeared from herdr", important=False, lost=True)
3533
4037
  run("cooldown", agent, GONE_COOLDOWN_MIN, "gone")
3534
- say(f"{agent} is gone — restart it in its folder; {tid} goes to the next free coder", True)
4038
+ patch_state(lambda s2: lead_event(
4039
+ s2, "worker-lost", tid, f"{agent} is gone: {what}. {tid} waits for the next free coder, with "
4040
+ f"its work so far. Fix: {fix}."))
4041
+ say(f"{run_tag()} LOST {agent}: {what}. {tid} goes to the next free coder. Fix: {fix}"
4042
+ + (f" (its last screen: {short(saved)})" if saved else ""), True)
3535
4043
 
3536
4044
  run("sync")
4045
+ manager_begin()
3537
4046
  _, start_out = run("start")
3538
4047
  for line in start_out.splitlines():
3539
4048
  if line.startswith(("RECOVERED", "WARN agent")):
@@ -3579,9 +4088,42 @@ def cmd_autopilot(args):
3579
4088
  last_tick = time.time()
3580
4089
  slept = sleep_meter()
3581
4090
  waiting_since = None # set while nothing runs and the run waits for the lead or the developer
4091
+ seen = {"procs": time.time(), "check": 0.0, "present": None, "told": False}
4092
+
4093
+ def watch_herdr():
4094
+ """Every VANISH_CHECK_S: which agents herdr still runs. When most of them vanish at once, herdr itself
4095
+ restarted (or was closed): say so loudly, once, instead of one quiet GONE per agent."""
4096
+ if time.time() - seen["check"] < VANISH_CHECK_S:
4097
+ return
4098
+ seen["check"] = time.time()
4099
+ s_ = load()
4100
+ names = [n for n in list(s_["workers"]) + ([s_["reviewer"]] if s_.get("reviewer") else [])
4101
+ + ([s_["lead"]["name"]] if s_.get("lead") else []) if watched(s_, n) and not agent_info(s_, n).get("pane")]
4102
+ present = {n for n in names if herdr_state(n) is not None}
4103
+ before = seen["present"]
4104
+ seen["present"] = present
4105
+ if before is None:
4106
+ return
4107
+ gone = sorted(before - present)
4108
+ if len(gone) >= 2 and len(gone) * 2 >= len(before) and not seen["told"]:
4109
+ seen["told"] = True
4110
+ say(f"{run_tag(s_)} HERDR RESTART? {len(gone)} of {len(before)} agents vanished at once ({', '.join(gone)}). "
4111
+ f"If herdr was restarted or closed, run `orch resume`: it finds their panes again and re-sends the work",
4112
+ True)
4113
+ patch_state(lambda s2: lead_event(s2, "herdr-restart", None,
4114
+ f"{len(gone)} of {len(before)} agents vanished at once: "
4115
+ f"{', '.join(gone)}. Tell the developer to run `orch resume`."))
4116
+ elif not gone and present == before:
4117
+ seen["told"] = False
3582
4118
 
3583
4119
  while True:
4120
+ _stop_point()
3584
4121
  st = load()
4122
+ if time.time() - seen["procs"] > PROCS_EVERY_S: # agents come and go: keep this run's processes current
4123
+ seen["procs"] = time.time()
4124
+ procs = run_processes(st)
4125
+ patch_state(lambda s_: (s_["run"].get("manager") or {}).update(procs))
4126
+ watch_herdr()
3585
4127
  # 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
3586
4128
  el, last_tick = time.time() - last_tick, time.time()
3587
4129
  asleep = slept()
@@ -4243,7 +4785,7 @@ def team_up(args):
4243
4785
  if not todo:
4244
4786
  print("TEAM UP: every agent in the plan is running")
4245
4787
  return
4246
- failed, last = 0, None
4788
+ failed, last, opened = 0, None, []
4247
4789
  for name, w, d in todo:
4248
4790
  kind, model = w.get("kind"), w.get("model")
4249
4791
  v = reg.get(kind)
@@ -4291,12 +4833,26 @@ def team_up(args):
4291
4833
  time.sleep(min(2.0, max(0.2, TEAM_WAIT_S / 30)))
4292
4834
  if named:
4293
4835
  print(f"OPENED {name}: pane {pid} in {short(d)} running `{cmd}`")
4836
+ opened.append((name, w, pid, cmd))
4294
4837
  else:
4295
4838
  print(f"WAITING {name}: pane {pid} runs `{cmd}`, but herdr has not seen the agent start yet — if it "
4296
4839
  f"shows a first-run question (trust this folder, sign in), answer it, then: herdr agent rename {pid} {name}")
4297
4840
  failed += 1
4298
4841
  if dry:
4299
4842
  return
4843
+ if opened: # an agent can start, get its name, and quit a second later (a bad flag, a missing login)
4844
+ time.sleep(TEAM_CONFIRM_S)
4845
+ for name, w, pid, cmd in opened:
4846
+ where, _ = herdr_presence(name)
4847
+ if where == "agent":
4848
+ continue
4849
+ failed += 1
4850
+ saved = save_screen(name, f"{w.get('kind')} quit right after `orch team up` started it")
4851
+ print(f"QUIT {name}: {w.get('kind')} exited right after it started — only a plain shell is left in "
4852
+ f"pane {pid}, so nothing will be sent there. Run `{cmd}` in that pane yourself to see why"
4853
+ + (f" (its last screen is in {short(saved)})" if saved else "") + ", then `orch team up` again")
4854
+ log_line(f"{run_tag(st)} QUIT {name}: {w.get('kind')} exited right after `orch team up` started it "
4855
+ f"in pane {pid}")
4300
4856
  print("TEAM UP: done — run `orch start` again; every agent should show herdr=found" if not failed else
4301
4857
  f"TEAM UP: {failed} agent(s) not ready — see above, then `orch team up` again")
4302
4858
  if failed:
@@ -4445,6 +5001,10 @@ def cmd_resume(args):
4445
5001
  else:
4446
5002
  print("Every agent in the plan is found. Nothing to resume.")
4447
5003
  return
5004
+ if not from_manager:
5005
+ dead = note_dead_manager(st)
5006
+ if dead:
5007
+ print(dead)
4448
5008
  beat = st["run"].get("beat")
4449
5009
  busy = [(tid, st["tasks"][tid]["wait"]) for tid in st["order"] if st["tasks"][tid].get("wait")]
4450
5010
  gap = account_downtime(st)
@@ -4512,10 +5072,11 @@ COMMANDS = {
4512
5072
  "send-job": cmd_send_job, "handoff": cmd_handoff, "needs-fix": cmd_needs_fix, "review-ok": cmd_review_ok,
4513
5073
  "requeue-review": cmd_requeue_review, "finish": cmd_finish, "resend": cmd_resend, "approve": cmd_approve,
4514
5074
  "report": cmd_report, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer,
4515
- "escalate": cmd_escalate, "fix": cmd_fix, "team": cmd_team,
5075
+ "escalate": cmd_escalate, "fix": cmd_fix, "team": cmd_team, "bench": cmd_bench, "stop": cmd_stop,
5076
+ "doctor": lambda a: cmd_doctor_crash(a),
4516
5077
  }
4517
5078
  # they lock per step instead of for the whole command (long-running, or they start the event manager after)
4518
- UNLOCKED = {"autopilot", "poll", "events", "dispatch", "answer", "fix", "team", "resume"}
5079
+ UNLOCKED = {"autopilot", "poll", "events", "dispatch", "answer", "fix", "team", "resume", "bench", "stop", "doctor"}
4519
5080
 
4520
5081
  USAGE = """usage: orch <command> [args]
4521
5082
  version print the installed herdr-orchestra version
@@ -4557,6 +5118,9 @@ USAGE = """usage: orch <command> [args]
4557
5118
  merge <Mn> squash the milestone, run the check on the result, commit it ONLY if green (CONFLICT 4, CHECK_FAILED 6, HELD 7)
4558
5119
  park <Mn> paused|failed|pending [--lost] [reason] free the worker, keep its work in a hidden ref (refs/orch/...)
4559
5120
  cooldown <agent> <min> [reason] bench a worker or the reviewer (reason `gone`: ends once herdr sees it again)
5121
+ bench <worker> off [reason] | on keep a coder out of the run until you turn it back on (survives restarts)
5122
+ stop [--now] stop the event manager cleanly (it finishes its current step); `orch resume` starts it again
5123
+ doctor --crash (in a repo) why the event manager last stopped, and the last crash / lost notes
4560
5124
  set <Mn> <status> [reason] [--force] manual override: pending/paused/failed/skipped (others need --force)
4561
5125
  approve <Mn> let a milestone held for risky changes land (works while autopilot runs)
4562
5126
  cleanup remove clean worker worktrees
@@ -5004,6 +5568,30 @@ def doctor_kind(kind, v, full=True):
5004
5568
  return out
5005
5569
 
5006
5570
 
5571
+ def cmd_doctor_crash(args):
5572
+ """orch doctor --crash -> the last crash, stop and lost notes of this run, and, when the event manager is not
5573
+ running, why it stopped (looked up in the computer's own log, for this run's processes only)."""
5574
+ with state_lock():
5575
+ st = load()
5576
+ dead = None if driver_alive() else note_dead_manager(st)
5577
+ m = (st.get("run") or {}).get("manager") or {}
5578
+ print(f"{run_tag(st)} event manager: " + (f"running ({driver_line(driver_info())})" if driver_alive() else
5579
+ "not running" + (f"; last one ended {_clock(m['ended']['ts'])}: {m['ended'].get('how')}"
5580
+ + (f" — {m['ended']['reason']}" if m['ended'].get('reason') else "")
5581
+ if m.get("ended") else "")))
5582
+ if dead:
5583
+ print(dead)
5584
+ lines = last_crash_lines()
5585
+ print("Last notes in .orchestrate/autopilot.log:" if lines else "No crash, stop or lost notes in autopilot.log yet.")
5586
+ for l in lines:
5587
+ print(" " + l)
5588
+ shots = sorted((ORCH / "crash").glob("*.txt"), key=lambda p: p.stat().st_mtime)[-5:] if (ORCH / "crash").is_dir() else []
5589
+ if shots:
5590
+ print("Saved agent screens (.orchestrate/crash/):")
5591
+ for p in shots:
5592
+ print(f" {p.name}")
5593
+
5594
+
5007
5595
  def cmd_doctor(args):
5008
5596
  """orch doctor [kind...] -> check each installed agent against the real tool (version, launch flags, skills,
5009
5597
  herdr detection). Read-only. Exit 1 if anything is broken."""
@@ -5042,7 +5630,7 @@ if __name__ == "__main__":
5042
5630
  NO_REPO_COMMANDS = {"lead": cmd_lead, "agents": cmd_agents, "doctor": cmd_doctor, "models": cmd_models,
5043
5631
  "team": cmd_team}
5044
5632
  if (len(sys.argv) >= 2 and sys.argv[1] in NO_REPO_COMMANDS # work outside a git repo
5045
- and sys.argv[2:3] != ["up"]): # (`orch team up` reads the run's state)
5633
+ and sys.argv[2:3] != ["up"] and sys.argv[2:3] != ["--crash"]): # (`orch team up` reads the run's state)
5046
5634
  NO_REPO_COMMANDS[sys.argv[1]](sys.argv[2:])
5047
5635
  sys.exit(0)
5048
5636
  if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS:
@@ -5054,8 +5642,13 @@ if __name__ == "__main__":
5054
5642
  STATE = ORCH / "state.json"
5055
5643
  if sys.argv[1] not in LEASE_FREE:
5056
5644
  require_driver()
5057
- if sys.argv[1] in UNLOCKED:
5058
- COMMANDS[sys.argv[1]](sys.argv[2:])
5059
- else:
5060
- with state_lock():
5645
+ try:
5646
+ if sys.argv[1] in UNLOCKED:
5061
5647
  COMMANDS[sys.argv[1]](sys.argv[2:])
5648
+ else:
5649
+ with state_lock():
5650
+ COMMANDS[sys.argv[1]](sys.argv[2:])
5651
+ except BrokenPipeError: # `orch status | head`: the reader has what it wanted
5652
+ with contextlib.suppress(OSError):
5653
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
5654
+ sys.exit(0)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-orchestra",
3
- "version": "5.6.0",
3
+ "version": "5.7.0",
4
4
  "description": "Orchestrate AI coding agents (Claude Code, Codex, OpenCode, Amp) as one team in Herdr: a lead plans, coders build in parallel, a reviewer checks, you get one PR.",
5
5
  "license": "MIT",
6
6
  "bin": {
package/playbooks/run.md CHANGED
@@ -41,6 +41,8 @@ Run `orch events`. It lists the new events, the ones still open, the milestones
41
41
  | `PAUSED Mn`: agent stopped twice / over its time budget / blocked / orch error | Look at what the agent shows (`herdr agent read <agent> --source recent-unwrapped --lines 60`) or the error in the log, and tell the developer. Don't work around it by hand. When it is sorted out: `orch dispatch Mn`. |
42
42
  | `FAILED Mn`: checks / review / criteria still failing | It already had its rounds, and a round on a stronger model if the team has one. Read the last report and the last check output or review file. Explain in two lines what keeps failing. If a fact or constraint was missing from the milestone, add it to the plan (never a how-to) and `orch dispatch Mn`; add `--tier high` when the work turned out harder than its tier. If you can't tell what is missing, ask the developer. |
43
43
  | `FAILED Mn`: lost N attempts | The agents kept being unreachable, gone or rate-limited. Tell the developer which agents to restart or wait for; then `orch dispatch Mn`. |
44
+ | `WORKER-LOST Mn` | A coder vanished while it worked (pane closed, the agent quit and left a shell, herdr restarted). **Not routine:** tell the developer at once, with the exact fix in the event text (`orch resume`, or `orch team up`). The milestone waits for the next free coder with its work so far; nothing else to do. |
45
+ | `HERDR-RESTART` | Most agents vanished at once. Tell the developer to run `orch resume`, then `orch team up` for any agent it reports `LOST`. |
44
46
  | `HELD Mn` | Risky changes (deleted files, migrations, CI config, secrets files, unlisted dependency changes, a very large diff) wait for the developer. Show the reasons from `orch status`, and tell the developer to look and run `orch approve Mn` (or `orch set Mn paused`). |
45
47
  | `NEEDS-ANSWER Mn` | Open questions in the plan: ask the developer, write the answers under "Notes from user", set "Open questions:" to `- none`, `orch sync`, then `orch dispatch Mn`. |
46
48
  | `ESCALATED Mn`, `AUTO-DISPATCHED Mn` | Information. Mention an escalation in the final summary. |
@@ -50,6 +52,14 @@ Run `orch events`. It lists the new events, the ones still open, the milestones
50
52
 
51
53
  If you changed plan.md by hand, run `orch sync` (it works once the event manager is idle; `orch answer` and `orch dispatch` work at any time).
52
54
 
55
+ **The developer says "stop sending work to <coder>"** (for example, no Claude today): run `orch bench <worker> off "<their reason>"`. It holds until `orch bench <worker> on`, across restarts, `orch sync` and `orch resume`; a usage-limit bench does not. Tell the developer what it still holds (`orch status`). Never try to keep a coder out by remembering it yourself.
56
+
57
+ **Swap a coder** (for example, AGY instead of OpenCode): `orch stop` (the event manager finishes its current step and exits; nothing is lost), change `Workers:` in plan.md, `orch sync`, `orch team up`, check that `orch status` shows the new worker as `herdr=ok`, then `orch resume`. Never kill the event manager by hand.
58
+
59
+ **Before `orch dispatch --to <worker>`**, `orch status` must show that worker as `herdr=ok`. dispatch refuses a worker with no agent (`NO AGENT`, `SHELL ONLY`); do what it says (`orch team up`) and try again. If `orch team up` reports `QUIT <worker>`, the agent quit as soon as it started: show the developer the pane and the saved screen it names.
60
+
61
+ **Why did the event manager stop?** `orch doctor --crash` prints the last `STOPPED` / `CRASHED` / `LOST` notes (with the reason found in the computer's own log) and the saved agent screens. Give the developer that reason in one line.
62
+
53
63
  **Red baseline.** The event manager needs the check command to pass before any work. If it says the baseline fails: run the check yourself (`<check cmd> 2>&1 | tail -40`), tell the developer exactly what fails, and propose a narrower `Check command` that passes today and still covers the feature. Write it into the plan header only when the developer agrees, then `orch sync` and dispatch again. Never judge "no new failures" by eye.
54
64
 
55
65
  ## 3. ALL_DONE