herdr-orchestra 5.6.0 → 5.7.1
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 +34 -0
- package/README.md +23 -2
- package/VERSION +1 -1
- package/bin/__pycache__/orchcpython-314.pyc +0 -0
- package/bin/orch +641 -42
- package/package.json +1 -1
- package/playbooks/run.md +10 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,40 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes. Versions follow [semantic versioning](https://semver.org).
|
|
4
4
|
|
|
5
|
+
## [5.7.1] - 2026-11-16
|
|
6
|
+
|
|
7
|
+
A check that quick runs (5.6.0) and the stalled-run fixes (5.7.0) did not change how a real feature is planned. They did not: a plan with no `Mode:` line, or `Mode: full`, is planned and run as before (worktrees, reviewer, `Why separate:`, `Role:`, tier and estimate per milestone, and the same warnings). The check found one bug in quick runs.
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
- **`orch sync` refused a quick run after `orch fix`.** The follow-up milestone that `orch fix M1 "..."` adds was counted as a second planned milestone, so `orch sync` stopped with "`Mode: quick` is one milestone, and this plan has 2". Follow-ups from `orch fix` no longer count; a second milestone you plan by hand is still refused.
|
|
11
|
+
|
|
12
|
+
### Tests
|
|
13
|
+
- New tests lock in full feature planning: a three-milestone feature with no `Mode:` line stays full (worktrees, reviewer, review per milestone, role, tier, estimate and dependencies kept), none of the quick-run rules touch it (a migration or `package.json` is fine), `Why separate` and `Estimate` warnings still appear, `Mode: full` is the same as no line, an unknown `Mode` is refused, and the planning playbook keeps steps 3 to 10.
|
|
14
|
+
|
|
15
|
+
## [5.7.0] - 2026-11-15
|
|
16
|
+
|
|
17
|
+
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.
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
- **`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>)`.
|
|
21
|
+
- **`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`.
|
|
22
|
+
- **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.
|
|
23
|
+
- **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)`.
|
|
24
|
+
- **`orch doctor --crash`** (in a repo): why the event manager last stopped, the last `STOPPED` / `CRASHED` / `LOST` / `QUIT` notes, and the saved agent screens.
|
|
25
|
+
- **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`).
|
|
26
|
+
- **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.
|
|
27
|
+
|
|
28
|
+
### Changed
|
|
29
|
+
- **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.
|
|
30
|
+
- **`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.
|
|
31
|
+
- **`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.
|
|
32
|
+
- **`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`.
|
|
33
|
+
- **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.
|
|
34
|
+
- **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.
|
|
35
|
+
- **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.
|
|
36
|
+
|
|
37
|
+
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.
|
|
38
|
+
|
|
5
39
|
## [5.6.0] - 2026-11-15
|
|
6
40
|
|
|
7
41
|
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.
|
|
1
|
+
5.7.1
|
|
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
|
|
368
|
-
"""
|
|
369
|
-
|
|
370
|
-
|
|
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
|
-
|
|
613
|
+
data = json.loads(r.stdout)
|
|
379
614
|
except ValueError:
|
|
380
|
-
|
|
381
|
-
|
|
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())
|
|
@@ -946,8 +1204,14 @@ def cmd_sync(args):
|
|
|
946
1204
|
if not quick_because:
|
|
947
1205
|
errors.append("`Mode: quick` needs `Quick because: <what you found in the code that makes this small>` "
|
|
948
1206
|
"— e.g. `Quick because: the column already exists, only the response changes`")
|
|
949
|
-
|
|
950
|
-
|
|
1207
|
+
# follow-ups added by `orch fix` after the quick milestone landed are not extra planned milestones
|
|
1208
|
+
try:
|
|
1209
|
+
fixes = {k for k, v in json.loads(STATE.read_text()).get("tasks", {}).items() if v.get("fix_of")}
|
|
1210
|
+
except (OSError, ValueError, AttributeError):
|
|
1211
|
+
fixes = set()
|
|
1212
|
+
planned = [tid for tid in enabled if tid not in fixes]
|
|
1213
|
+
if len(planned) > 1:
|
|
1214
|
+
errors.append(f"`Mode: quick` is one milestone, and this plan has {len(planned)} — put the small changes "
|
|
951
1215
|
f"in one milestone (one acceptance criterion each), or use `Mode: full`")
|
|
952
1216
|
if isolation == "worktree":
|
|
953
1217
|
warns.append("`Mode: quick` with `Isolation: worktree`: one milestone needs no separate folder — "
|
|
@@ -1034,6 +1298,7 @@ def cmd_sync(args):
|
|
|
1034
1298
|
ow = old.get("workers", {}).get(name, {})
|
|
1035
1299
|
st["workers"][name] = {"kind": kind, "task": ow.get("task"), "cooldown_until": ow.get("cooldown_until", 0),
|
|
1036
1300
|
"cooldown_reason": ow.get("cooldown_reason", ""),
|
|
1301
|
+
**({"off": ow["off"]} if ow.get("off") else {}), # kept until `orch bench <w> on`
|
|
1037
1302
|
"dir": ow.get("dir"), "setup_done": ow.get("setup_done", False),
|
|
1038
1303
|
"setup_hash": ow.get("setup_hash"), "delivery_fails": ow.get("delivery_fails", 0),
|
|
1039
1304
|
"pane": pane, "detect": detect(kind, pane, "Workers"),
|
|
@@ -1630,7 +1895,15 @@ def cmd_ready(args):
|
|
|
1630
1895
|
slots = free_slots(st)
|
|
1631
1896
|
if st["isolation"] == "shared" and slots <= 0 and active_count(st) == len(fix_jobs(st)) and fix_jobs(st):
|
|
1632
1897
|
slots = 1 # shared mode: a queued fix job IS the active milestone, and it needs a coder
|
|
1898
|
+
# only coders herdr can see count as free: a coder with no agent can't take work, whatever its task field says
|
|
1899
|
+
present = [n for n, w in st["workers"].items() if not w.get("task") and not w.get("off") and not cooling(n, w)
|
|
1900
|
+
and (not w.get("detect", True) or w.get("pane") or herdr_state(n) is not None)]
|
|
1901
|
+
gone = [n for n, w in st["workers"].items() if not w.get("task") and not w.get("off") and w.get("detect", True)
|
|
1902
|
+
and not w.get("pane") and herdr_state(n) is None]
|
|
1903
|
+
slots = min(slots, len(present))
|
|
1633
1904
|
print(f"SLOTS {max(slots, 0)}")
|
|
1905
|
+
if gone:
|
|
1906
|
+
print(f"NOAGENT {' '.join(gone)} (no agent in herdr: `orch team up`)")
|
|
1634
1907
|
for tid in fix_jobs(st): # fixes first: reviewed work merges sooner and unlocks dependents
|
|
1635
1908
|
print(f"FIX {tid} {st['tasks'][tid]['status']} {st['tasks'][tid]['title']}")
|
|
1636
1909
|
for tid in out:
|
|
@@ -1649,7 +1922,7 @@ def cooling(name, info):
|
|
|
1649
1922
|
|
|
1650
1923
|
|
|
1651
1924
|
def worker_free(st, name, w):
|
|
1652
|
-
if w.get("task") or cooling(name, w):
|
|
1925
|
+
if w.get("task") or w.get("off") or cooling(name, w):
|
|
1653
1926
|
return False
|
|
1654
1927
|
if not w.get("detect", True): # herdr can't watch it: no task + no cooldown = free
|
|
1655
1928
|
return True
|
|
@@ -2514,6 +2787,70 @@ def cmd_cooldown(args):
|
|
|
2514
2787
|
print(f"COOLDOWN {name} for {args[1]} min" + (f" ({reason})" if reason else ""))
|
|
2515
2788
|
|
|
2516
2789
|
|
|
2790
|
+
def cmd_bench(args):
|
|
2791
|
+
"""orch bench <worker> off [reason] | on -> keep a coder out of the run until the developer says otherwise.
|
|
2792
|
+
Unlike a cooldown it never ends by itself: not after a restart, `orch sync`, `orch resume` or `orch team up`."""
|
|
2793
|
+
need(args, 2, "bench <worker> off [reason] | bench <worker> on")
|
|
2794
|
+
name, mode, reason = args[0], args[1], " ".join(args[2:]).strip()
|
|
2795
|
+
if mode not in ("off", "on"):
|
|
2796
|
+
die("usage: orch bench <worker> off [reason] | orch bench <worker> on")
|
|
2797
|
+
with state_lock():
|
|
2798
|
+
st = load()
|
|
2799
|
+
if name not in st["workers"]:
|
|
2800
|
+
die(f"unknown worker {name!r} — workers: {', '.join(st['workers'])}"
|
|
2801
|
+
+ (" (the reviewer can't be benched this way: change `Reviewer:` in plan.md)"
|
|
2802
|
+
if name == st.get("reviewer") else ""))
|
|
2803
|
+
w = st["workers"][name]
|
|
2804
|
+
if mode == "on":
|
|
2805
|
+
was = w.pop("off", None)
|
|
2806
|
+
save(st)
|
|
2807
|
+
print(f"ON {name} takes work again" if was else f"ON {name} was not off")
|
|
2808
|
+
return
|
|
2809
|
+
w["off"] = {"ts": now(), "why": reason or "the developer said so"}
|
|
2810
|
+
moved = [tid for tid in st["order"] if st["tasks"][tid].get("assign") == name
|
|
2811
|
+
and st["tasks"][tid]["status"] not in ("merged", "skipped")]
|
|
2812
|
+
for tid in moved:
|
|
2813
|
+
st["tasks"][tid].pop("assign", None) # `--to <this worker>` no longer holds it back
|
|
2814
|
+
save(st)
|
|
2815
|
+
print(f"OFF {name}: gets no new work until `orch bench {name} on` ({w['off']['why']})")
|
|
2816
|
+
if moved:
|
|
2817
|
+
print(f" {', '.join(moved)} no longer wait for {name}: the next free coder takes them")
|
|
2818
|
+
if w.get("task"):
|
|
2819
|
+
print(f" it still holds {w['task']}: that one finishes here. To move it now: "
|
|
2820
|
+
f"`orch set {w['task']} paused`, then `orch dispatch {w['task']}`")
|
|
2821
|
+
if not eligible_workers(st, {"tier": None, "min_tier": None}):
|
|
2822
|
+
print("WARN every coder is off now: nothing new starts until one is back on")
|
|
2823
|
+
|
|
2824
|
+
|
|
2825
|
+
def cmd_stop(args):
|
|
2826
|
+
"""orch stop [--now] -> stop the event manager cleanly: it finishes the step it is on (a check, a merge) and
|
|
2827
|
+
exits; every event and all work are kept. Then change the run (plan.md + `orch sync`, `orch team up`) and
|
|
2828
|
+
start it again with `orch resume`. --now also stops the step it is on."""
|
|
2829
|
+
if not driver_alive():
|
|
2830
|
+
print("the event manager is not running")
|
|
2831
|
+
return
|
|
2832
|
+
info = driver_info()
|
|
2833
|
+
pid = info.get("pid")
|
|
2834
|
+
if info.get("host") not in (None, socket.gethostname()):
|
|
2835
|
+
die(f"the event manager runs on {info.get('host')}: stop it there")
|
|
2836
|
+
if not isinstance(pid, int):
|
|
2837
|
+
die("can't tell the event manager's process id from .orchestrate/driver.lock")
|
|
2838
|
+
(ORCH / "stop.request").write_text(json.dumps({"ts": now(), "now": "--now" in args}))
|
|
2839
|
+
for _ in range(2 if "--now" in args else 1):
|
|
2840
|
+
with contextlib.suppress(OSError):
|
|
2841
|
+
os.kill(pid, signal.SIGTERM)
|
|
2842
|
+
time.sleep(0.3)
|
|
2843
|
+
end = time.time() + STOP_WAIT_S
|
|
2844
|
+
while time.time() < end and driver_alive():
|
|
2845
|
+
time.sleep(0.25)
|
|
2846
|
+
if driver_alive():
|
|
2847
|
+
print(f"STOPPING the event manager (pid {pid}) is finishing its current step and stops right after it. "
|
|
2848
|
+
f"`orch status` shows when it has; `orch stop --now` stops it at once.")
|
|
2849
|
+
sys.exit(3)
|
|
2850
|
+
print(f"STOPPED the event manager (pid {pid}). Nothing is lost. Change what you need (plan.md + `orch sync`, "
|
|
2851
|
+
f"`orch team up`), then start it again with `orch resume`.")
|
|
2852
|
+
|
|
2853
|
+
|
|
2517
2854
|
STATUSES = {"pending", "coding", "verifying", "awaiting-review", "reviewing", "reviewed", "committed", "merged",
|
|
2518
2855
|
"needs-answer", "paused", "failed", "conflict", "skipped", "needs-fix", "held"}
|
|
2519
2856
|
|
|
@@ -2544,6 +2881,10 @@ def cmd_set(args):
|
|
|
2544
2881
|
|
|
2545
2882
|
def cmd_status(args):
|
|
2546
2883
|
st = load()
|
|
2884
|
+
dead = None if driver_alive() else note_dead_manager(st)
|
|
2885
|
+
here = {n: presence_word(st, n) for n in st["workers"]} # ask herdr first, then print in one go
|
|
2886
|
+
if dead:
|
|
2887
|
+
print("!! " + dead.replace("\n", "\n!! "))
|
|
2547
2888
|
if driver_alive():
|
|
2548
2889
|
print(f"driven by {driver_line(driver_info())}")
|
|
2549
2890
|
elif needs_manager(st):
|
|
@@ -2561,17 +2902,27 @@ def cmd_status(args):
|
|
|
2561
2902
|
f"{st['integration_broken']} — fix it; autopilot re-checks before it continues")
|
|
2562
2903
|
for n, w in st["workers"].items():
|
|
2563
2904
|
cd = max(0, w.get("cooldown_until", 0) - now())
|
|
2905
|
+
h = here[n]
|
|
2906
|
+
state = ("OFF (" + (w["off"].get("why") or "developer") + ")" if w.get("off") else
|
|
2907
|
+
f"coding {w['task']}" if w.get("task") else
|
|
2908
|
+
f"benched {cd // 60}m ({w.get('cooldown_reason') or 'cooldown'})" if cd else "free")
|
|
2564
2909
|
print(f" worker {n:<12} {w['kind']:<8} task={w.get('task') or '-':<5} "
|
|
2565
2910
|
+ (f"model={w['model']} ({w.get('tier') or 'unrated'}) " if w.get("model") else "")
|
|
2566
2911
|
+ f"{'cooldown ' + str(cd // 60) + 'm' if cd else ''}"
|
|
2567
|
-
f"{'' if w.get('detect', True) else ' detect:off'}"
|
|
2912
|
+
f"{'' if w.get('detect', True) else ' detect:off'}"
|
|
2913
|
+
+ f" herdr={h} state={state}"
|
|
2914
|
+
+ (" !! no agent: `orch team up` (or `orch resume` after a restart)" if h in ("NO AGENT", "SHELL ONLY")
|
|
2915
|
+
else ""))
|
|
2568
2916
|
for tid in st["order"]:
|
|
2569
2917
|
t = st["tasks"][tid]
|
|
2570
2918
|
print(f" {tid:<4} {t['status']:<15} deps={','.join(t['deps']) or '-':<10} "
|
|
2571
2919
|
f"worker={t.get('worker') or '-':<10} "
|
|
2572
2920
|
+ (f"tier={t['tier'] if rank(t.get('min_tier')) <= rank(t.get('tier')) else t['min_tier'] + '^'} "
|
|
2573
2921
|
if need_rank(t) else "") + t["title"]
|
|
2574
|
-
+ (f" [{t['reason']}]" if t.get("reason") else "")
|
|
2922
|
+
+ (f" [{t['reason']}]" if t.get("reason") else "")
|
|
2923
|
+
+ (f" !! but {t['worker']} has no agent in herdr ({here[t['worker']]}): nothing is working on it — "
|
|
2924
|
+
f"`orch resume`" if t["status"] in ("coding", "conflict") and here.get(t.get("worker"))
|
|
2925
|
+
in ("NO AGENT", "SHELL ONLY") else ""))
|
|
2575
2926
|
if lead_on(st):
|
|
2576
2927
|
ev = [e for e in st["lead_events"] if event_open(st, e)]
|
|
2577
2928
|
hold = undispatched(st)
|
|
@@ -2803,14 +3154,29 @@ def start_manager():
|
|
|
2803
3154
|
return f"the event manager is running ({driver_line(driver_info())})"
|
|
2804
3155
|
if os.environ.get("ORCH_NO_AUTOSTART") == "1":
|
|
2805
3156
|
return "the event manager is NOT running — ask the developer to run `orch autopilot` in a terminal"
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
3157
|
+
_rotate(ORCH / "manager.out", LOG_MAX_B // 2)
|
|
3158
|
+
env = {k: v for k, v in os.environ.items() if not k.startswith("ORCH_DRIVER")}
|
|
3159
|
+
cmd = [sys.executable, os.path.abspath(__file__), "autopilot"]
|
|
3160
|
+
# In its own systemd scope the manager is not part of the terminal (or herdr pane) it was started from: when the
|
|
3161
|
+
# memory guard closes that terminal, or herdr restarts, the manager keeps watching and says what it saw.
|
|
3162
|
+
unit = f"orch-{re.sub(r'[^A-Za-z0-9]', '-', ROOT.name)[:30]}-{os.getpid()}"
|
|
3163
|
+
tries = []
|
|
3164
|
+
if os.environ.get("ORCH_NO_SCOPE") != "1" and shutil.which("systemd-run"):
|
|
3165
|
+
tries.append((["systemd-run", "--user", "--scope", "--quiet", "--collect", f"--unit={unit}"] + cmd,
|
|
3166
|
+
{**env, "ORCH_SCOPE": unit}))
|
|
3167
|
+
tries.append((cmd, env))
|
|
3168
|
+
for argv, e in tries:
|
|
3169
|
+
with open(ORCH / "manager.out", "a") as out:
|
|
3170
|
+
p = subprocess.Popen(argv, cwd=ROOT, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT,
|
|
3171
|
+
start_new_session=True, env=e)
|
|
3172
|
+
for _ in range(20):
|
|
3173
|
+
time.sleep(0.25)
|
|
3174
|
+
if driver_alive():
|
|
3175
|
+
return ("started the event manager (`orch autopilot`" + (f", in its own scope {unit} so a closed "
|
|
3176
|
+
f"terminal does not stop it" if argv[0] == "systemd-run" else "")
|
|
3177
|
+
+ ", log: .orchestrate/autopilot.log)")
|
|
3178
|
+
if p.poll() is not None:
|
|
3179
|
+
break # systemd-run can't reach the user session: start it the plain way
|
|
2814
3180
|
return ("could NOT start the event manager from here (see .orchestrate/manager.out) — ask the developer to run "
|
|
2815
3181
|
"`orch autopilot` in a terminal")
|
|
2816
3182
|
|
|
@@ -2829,6 +3195,16 @@ def cmd_dispatch(args):
|
|
|
2829
3195
|
st = load()
|
|
2830
3196
|
if opts.get("--to") and opts["--to"] not in st["workers"]:
|
|
2831
3197
|
die(f"unknown worker {opts['--to']!r} — workers: {', '.join(st['workers'])}")
|
|
3198
|
+
if opts.get("--to"):
|
|
3199
|
+
to = opts["--to"]
|
|
3200
|
+
if st["workers"][to].get("off"):
|
|
3201
|
+
die(f"{to} is off ({st['workers'][to]['off'].get('why')}): `orch bench {to} on` first, or pick another "
|
|
3202
|
+
f"worker")
|
|
3203
|
+
here = presence_word(st, to)
|
|
3204
|
+
if here not in ("ok", "detect:off"):
|
|
3205
|
+
die(f"{to} has no agent in herdr ({here}" + (": only a plain shell is left in its pane" if here ==
|
|
3206
|
+
"SHELL ONLY" else "") + f"). Run `orch team up` (or `orch resume` after a restart), check that "
|
|
3207
|
+
f"`orch status` shows {to} as ok, then dispatch again")
|
|
2832
3208
|
if opts.get("--tier") and opts["--tier"] not in TIERS:
|
|
2833
3209
|
die("--tier must be small, medium or high")
|
|
2834
3210
|
for tid in args:
|
|
@@ -2849,8 +3225,14 @@ def cmd_dispatch(args):
|
|
|
2849
3225
|
_park(st, tid, "pending", "dispatched again by the lead")
|
|
2850
3226
|
who = [n for n in eligible_workers(st, t)]
|
|
2851
3227
|
waits = [d for d in t["deps"] if st["tasks"][d]["status"] != "merged"]
|
|
2852
|
-
print(f"DISPATCH {tid} -> {' or '.join(who)
|
|
3228
|
+
print(f"DISPATCH {tid} -> {' or '.join(who) or 'nobody (every coder is off)'}"
|
|
3229
|
+
+ (f" (tier {TIERS[need_rank(t) - 1]})" if need_rank(t) else "")
|
|
2853
3230
|
+ (f" — starts when {', '.join(waits)} merged" if waits else ""))
|
|
3231
|
+
if who and not opts.get("--to"):
|
|
3232
|
+
missing = [n for n in who if presence_word(st, n) not in ("ok", "detect:off")]
|
|
3233
|
+
if len(missing) == len(who):
|
|
3234
|
+
print(f"WARN none of them has an agent in herdr right now ({', '.join(missing)}): {tid} waits "
|
|
3235
|
+
f"until one does. Run `orch team up` (or `orch resume` after a restart)")
|
|
2854
3236
|
save(st)
|
|
2855
3237
|
print(start_manager())
|
|
2856
3238
|
print("You will be woken with `orch events` when something needs you. Stop here; do not poll.")
|
|
@@ -2986,6 +3368,13 @@ EVENT_HELP = {
|
|
|
2986
3368
|
"reviewer-lost": "the reviewer can't be reached, so the milestone waits for review (its work is kept). Tell the "
|
|
2987
3369
|
"developer the fix in the event text (usually: rename the reviewer's new pane). Review resumes "
|
|
2988
3370
|
"by itself once herdr finds the reviewer again.",
|
|
3371
|
+
"worker-lost": "a coder vanished while it worked (pane closed, agent quit, herdr restarted). Its milestone "
|
|
3372
|
+
"waits for the next free coder with the work so far. This is NOT routine: tell the developer at "
|
|
3373
|
+
"once, with the exact fix from the event text (`orch resume` or `orch team up`). If the developer "
|
|
3374
|
+
"does not want that coder any more: `orch bench <worker> off`.",
|
|
3375
|
+
"herdr-restart": "most agents vanished at once: herdr was probably restarted or closed. Tell the developer to "
|
|
3376
|
+
"run `orch resume` (it names the panes again and re-sends the work); then `orch team up` for "
|
|
3377
|
+
"any agent it reports LOST.",
|
|
2989
3378
|
"all_done": "every milestone landed. Finish .orchestrate/summary.md (see `orch lead run`, section ALL_DONE).",
|
|
2990
3379
|
"stopped": "the event manager stopped. Tell the developer why; they run `orch resume` (or `orch autopilot`).",
|
|
2991
3380
|
}
|
|
@@ -3122,25 +3511,138 @@ RATE_RE = re.compile(r"usage limit|rate.?limit|quota|too many requests|\b429\b|l
|
|
|
3122
3511
|
re.I)
|
|
3123
3512
|
|
|
3124
3513
|
|
|
3514
|
+
class _Stop(BaseException):
|
|
3515
|
+
"""`orch stop` (or a closed terminal) asked the event manager to stop: unwinds to cmd_autopilot."""
|
|
3516
|
+
|
|
3517
|
+
|
|
3518
|
+
_STOP = {"asked": None, "child": None}
|
|
3519
|
+
|
|
3520
|
+
|
|
3521
|
+
def _on_stop_signal(signum, _frame):
|
|
3522
|
+
"""First signal: stop at the next safe point (a running `orch poll` is ended, as it only waits). Second: now."""
|
|
3523
|
+
why = "terminal closed (SIGHUP)" if signum == getattr(signal, "SIGHUP", None) else "SIGTERM"
|
|
3524
|
+
try:
|
|
3525
|
+
req = json.loads((ORCH / "stop.request").read_text())
|
|
3526
|
+
if now() - req.get("ts", 0) < 120:
|
|
3527
|
+
why = "orch stop" + (" --now" if req.get("now") else "")
|
|
3528
|
+
except (OSError, ValueError):
|
|
3529
|
+
pass
|
|
3530
|
+
again = _STOP["asked"] is not None
|
|
3531
|
+
_STOP["asked"] = why
|
|
3532
|
+
child = _STOP["child"]
|
|
3533
|
+
if child is not None and child[0].poll() is None and (again or child[1] == "poll"):
|
|
3534
|
+
with contextlib.suppress(OSError):
|
|
3535
|
+
child[0].terminate()
|
|
3536
|
+
if again:
|
|
3537
|
+
raise _Stop()
|
|
3538
|
+
|
|
3539
|
+
|
|
3540
|
+
def _stop_point():
|
|
3541
|
+
if _STOP["asked"]:
|
|
3542
|
+
raise _Stop()
|
|
3543
|
+
|
|
3544
|
+
|
|
3125
3545
|
def cmd_autopilot(args):
|
|
3546
|
+
"""The event manager (see _autopilot). This wrapper records how it ends: every stop writes a last line to
|
|
3547
|
+
autopilot.log, a Python error writes the traceback, and a manager that was killed without a word (memory guard,
|
|
3548
|
+
a crash of the whole terminal) is found by the next one, which looks up why in the computer's own log."""
|
|
3549
|
+
take_lease()
|
|
3550
|
+
if STATE.exists():
|
|
3551
|
+
manager_begin()
|
|
3552
|
+
tag = run_tag() if STATE.exists() else f"[{ROOT.name}]"
|
|
3553
|
+
with contextlib.suppress(ValueError, OSError):
|
|
3554
|
+
signal.signal(signal.SIGTERM, _on_stop_signal)
|
|
3555
|
+
signal.signal(signal.SIGHUP, _on_stop_signal)
|
|
3556
|
+
|
|
3557
|
+
def ended(how, detail=""):
|
|
3558
|
+
nonlocal tag
|
|
3559
|
+
if STATE.exists():
|
|
3560
|
+
tag = run_tag()
|
|
3561
|
+
with contextlib.suppress(BaseException):
|
|
3562
|
+
with state_lock():
|
|
3563
|
+
s_ = load()
|
|
3564
|
+
m = s_["run"].get("manager") or {}
|
|
3565
|
+
if m.get("pid") == os.getpid():
|
|
3566
|
+
m["ended"] = {"ts": now(), "how": how, "reason": detail[:300]}
|
|
3567
|
+
s_["run"]["manager"] = m
|
|
3568
|
+
save(s_)
|
|
3569
|
+
try:
|
|
3570
|
+
_autopilot(args)
|
|
3571
|
+
ended("finished")
|
|
3572
|
+
log_line(f"{tag} STOPPED: the event manager finished")
|
|
3573
|
+
except _Stop:
|
|
3574
|
+
why = _STOP["asked"] or "stop"
|
|
3575
|
+
ended("stopped", why)
|
|
3576
|
+
log_line(f"{tag} STOPPED: {why} — nothing is lost; `orch resume` starts it again")
|
|
3577
|
+
print(f"STOPPED ({why})", flush=True)
|
|
3578
|
+
with contextlib.suppress(OSError):
|
|
3579
|
+
(ORCH / "stop.request").unlink()
|
|
3580
|
+
sys.exit(0)
|
|
3581
|
+
except SystemExit as e:
|
|
3582
|
+
code = e.code if isinstance(e.code, int) else (0 if e.code is None else 1)
|
|
3583
|
+
ended("exit", f"exit {code}")
|
|
3584
|
+
log_line(f"{tag} STOPPED: the event manager exited (code {code}); the line above says why")
|
|
3585
|
+
raise
|
|
3586
|
+
except KeyboardInterrupt:
|
|
3587
|
+
ended("stopped", "Ctrl-C")
|
|
3588
|
+
log_line(f"{tag} STOPPED: Ctrl-C")
|
|
3589
|
+
raise
|
|
3590
|
+
except BaseException as e:
|
|
3591
|
+
import traceback
|
|
3592
|
+
tb = traceback.format_exc()
|
|
3593
|
+
ended("crashed", f"{type(e).__name__}: {e}")
|
|
3594
|
+
log_line(f"{tag} CRASHED: {type(e).__name__}: {e}")
|
|
3595
|
+
for l in tb.rstrip().splitlines()[-40:]:
|
|
3596
|
+
log_line(f"{tag} {l}")
|
|
3597
|
+
if shutil.which("notify-send"):
|
|
3598
|
+
subprocess.run(["notify-send", "orch autopilot", f"{tag} CRASHED: {type(e).__name__}: {e}"],
|
|
3599
|
+
capture_output=True)
|
|
3600
|
+
raise
|
|
3601
|
+
|
|
3602
|
+
|
|
3603
|
+
def manager_begin():
|
|
3604
|
+
"""The event manager starting: report a predecessor that died without a word, then record this one (pid, host,
|
|
3605
|
+
this run's processes) so the next one can do the same for it. Safe to call twice."""
|
|
3606
|
+
with state_lock():
|
|
3607
|
+
st = load()
|
|
3608
|
+
m = st["run"].get("manager") or {}
|
|
3609
|
+
if m.get("pid") == os.getpid():
|
|
3610
|
+
return
|
|
3611
|
+
dead = note_dead_manager(st, save_it=False, starting=True)
|
|
3612
|
+
if dead:
|
|
3613
|
+
print(dead, flush=True)
|
|
3614
|
+
if shutil.which("notify-send"):
|
|
3615
|
+
subprocess.run(["notify-send", "orch autopilot", dead.splitlines()[0]], capture_output=True)
|
|
3616
|
+
st["run"]["manager"] = {"pid": os.getpid(), "host": socket.gethostname(), "started": now(),
|
|
3617
|
+
"scope": os.environ.get("ORCH_SCOPE") or None, **run_processes(st)}
|
|
3618
|
+
save(st)
|
|
3619
|
+
|
|
3620
|
+
|
|
3621
|
+
def _autopilot(args):
|
|
3126
3622
|
"""The event manager: a plain script that watches the agents, runs checks, sends fixes and reviews, merges, and
|
|
3127
3623
|
wakes the lead when something needs a decision. It is the only driver of a run: it holds the driver lease, and
|
|
3128
3624
|
other processes can't change the run meanwhile (the lead's `orch dispatch` / `orch answer` are requests it
|
|
3129
3625
|
carries out). Without a lead (`Lead mode: off`) it dispatches by itself and stops (exit 3) when a human is needed."""
|
|
3130
3626
|
me = [sys.executable, os.path.abspath(__file__)]
|
|
3131
|
-
|
|
3132
|
-
|
|
3627
|
+
if os.environ.get("ORCH_FAULT") == "autopilot-error":
|
|
3628
|
+
raise ValueError("test crash") # test hook: a Python error inside the event manager
|
|
3133
3629
|
|
|
3134
3630
|
def say(msg, important=False):
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
with log.open("a") as f:
|
|
3138
|
-
f.write(line + "\n")
|
|
3631
|
+
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
|
|
3632
|
+
log_line(msg)
|
|
3139
3633
|
if important and shutil.which("notify-send"):
|
|
3140
3634
|
subprocess.run(["notify-send", "orch autopilot", msg], capture_output=True)
|
|
3141
3635
|
|
|
3142
3636
|
def run(*a, ok=(0,)):
|
|
3143
|
-
|
|
3637
|
+
_stop_point()
|
|
3638
|
+
p = subprocess.Popen(me + [str(x) for x in a], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
3639
|
+
_STOP["child"] = (p, str(a[0]))
|
|
3640
|
+
try:
|
|
3641
|
+
so, se = p.communicate()
|
|
3642
|
+
finally:
|
|
3643
|
+
_STOP["child"] = None
|
|
3644
|
+
r = subprocess.CompletedProcess(p.args, p.returncode, so, se)
|
|
3645
|
+
_stop_point() # `orch stop` came while it ran: the step is done, stop here
|
|
3144
3646
|
out = (r.stdout + r.stderr).strip()
|
|
3145
3647
|
if r.returncode not in ok:
|
|
3146
3648
|
raise RuntimeError(f"orch {' '.join(str(x) for x in a)} -> exit {r.returncode}: {out}")
|
|
@@ -3529,11 +4031,24 @@ def cmd_autopilot(args):
|
|
|
3529
4031
|
run("cooldown", agent, GONE_COOLDOWN_MIN, "gone")
|
|
3530
4032
|
say(f"reviewer {agent} is gone — restart it; {tid} waits for review (the coder's work is kept)", True)
|
|
3531
4033
|
else:
|
|
4034
|
+
where, _ = herdr_presence(agent)
|
|
4035
|
+
shell = where == "shell"
|
|
4036
|
+
saved = save_screen(agent, f"no agent left in its pane while it worked on {tid}") if shell else None
|
|
4037
|
+
what = ("its pane is still there, but only a plain shell is left in it (the agent quit)" if shell
|
|
4038
|
+
else "herdr can't find it (its pane was closed, or herdr restarted)")
|
|
4039
|
+
fix = ("run `orch team up`: it starts the agent again in that pane" if shell else
|
|
4040
|
+
"run `orch resume` if herdr restarted (it finds the pane by folder and names it again), "
|
|
4041
|
+
"else `orch team up` to open a new pane")
|
|
3532
4042
|
park(tid, "pending", f"{agent} disappeared from herdr", important=False, lost=True)
|
|
3533
4043
|
run("cooldown", agent, GONE_COOLDOWN_MIN, "gone")
|
|
3534
|
-
|
|
4044
|
+
patch_state(lambda s2: lead_event(
|
|
4045
|
+
s2, "worker-lost", tid, f"{agent} is gone: {what}. {tid} waits for the next free coder, with "
|
|
4046
|
+
f"its work so far. Fix: {fix}."))
|
|
4047
|
+
say(f"{run_tag()} LOST {agent}: {what}. {tid} goes to the next free coder. Fix: {fix}"
|
|
4048
|
+
+ (f" (its last screen: {short(saved)})" if saved else ""), True)
|
|
3535
4049
|
|
|
3536
4050
|
run("sync")
|
|
4051
|
+
manager_begin()
|
|
3537
4052
|
_, start_out = run("start")
|
|
3538
4053
|
for line in start_out.splitlines():
|
|
3539
4054
|
if line.startswith(("RECOVERED", "WARN agent")):
|
|
@@ -3579,9 +4094,42 @@ def cmd_autopilot(args):
|
|
|
3579
4094
|
last_tick = time.time()
|
|
3580
4095
|
slept = sleep_meter()
|
|
3581
4096
|
waiting_since = None # set while nothing runs and the run waits for the lead or the developer
|
|
4097
|
+
seen = {"procs": time.time(), "check": 0.0, "present": None, "told": False}
|
|
4098
|
+
|
|
4099
|
+
def watch_herdr():
|
|
4100
|
+
"""Every VANISH_CHECK_S: which agents herdr still runs. When most of them vanish at once, herdr itself
|
|
4101
|
+
restarted (or was closed): say so loudly, once, instead of one quiet GONE per agent."""
|
|
4102
|
+
if time.time() - seen["check"] < VANISH_CHECK_S:
|
|
4103
|
+
return
|
|
4104
|
+
seen["check"] = time.time()
|
|
4105
|
+
s_ = load()
|
|
4106
|
+
names = [n for n in list(s_["workers"]) + ([s_["reviewer"]] if s_.get("reviewer") else [])
|
|
4107
|
+
+ ([s_["lead"]["name"]] if s_.get("lead") else []) if watched(s_, n) and not agent_info(s_, n).get("pane")]
|
|
4108
|
+
present = {n for n in names if herdr_state(n) is not None}
|
|
4109
|
+
before = seen["present"]
|
|
4110
|
+
seen["present"] = present
|
|
4111
|
+
if before is None:
|
|
4112
|
+
return
|
|
4113
|
+
gone = sorted(before - present)
|
|
4114
|
+
if len(gone) >= 2 and len(gone) * 2 >= len(before) and not seen["told"]:
|
|
4115
|
+
seen["told"] = True
|
|
4116
|
+
say(f"{run_tag(s_)} HERDR RESTART? {len(gone)} of {len(before)} agents vanished at once ({', '.join(gone)}). "
|
|
4117
|
+
f"If herdr was restarted or closed, run `orch resume`: it finds their panes again and re-sends the work",
|
|
4118
|
+
True)
|
|
4119
|
+
patch_state(lambda s2: lead_event(s2, "herdr-restart", None,
|
|
4120
|
+
f"{len(gone)} of {len(before)} agents vanished at once: "
|
|
4121
|
+
f"{', '.join(gone)}. Tell the developer to run `orch resume`."))
|
|
4122
|
+
elif not gone and present == before:
|
|
4123
|
+
seen["told"] = False
|
|
3582
4124
|
|
|
3583
4125
|
while True:
|
|
4126
|
+
_stop_point()
|
|
3584
4127
|
st = load()
|
|
4128
|
+
if time.time() - seen["procs"] > PROCS_EVERY_S: # agents come and go: keep this run's processes current
|
|
4129
|
+
seen["procs"] = time.time()
|
|
4130
|
+
procs = run_processes(st)
|
|
4131
|
+
patch_state(lambda s_: (s_["run"].get("manager") or {}).update(procs))
|
|
4132
|
+
watch_herdr()
|
|
3585
4133
|
# 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
|
|
3586
4134
|
el, last_tick = time.time() - last_tick, time.time()
|
|
3587
4135
|
asleep = slept()
|
|
@@ -4243,7 +4791,7 @@ def team_up(args):
|
|
|
4243
4791
|
if not todo:
|
|
4244
4792
|
print("TEAM UP: every agent in the plan is running")
|
|
4245
4793
|
return
|
|
4246
|
-
failed, last = 0, None
|
|
4794
|
+
failed, last, opened = 0, None, []
|
|
4247
4795
|
for name, w, d in todo:
|
|
4248
4796
|
kind, model = w.get("kind"), w.get("model")
|
|
4249
4797
|
v = reg.get(kind)
|
|
@@ -4291,12 +4839,26 @@ def team_up(args):
|
|
|
4291
4839
|
time.sleep(min(2.0, max(0.2, TEAM_WAIT_S / 30)))
|
|
4292
4840
|
if named:
|
|
4293
4841
|
print(f"OPENED {name}: pane {pid} in {short(d)} running `{cmd}`")
|
|
4842
|
+
opened.append((name, w, pid, cmd))
|
|
4294
4843
|
else:
|
|
4295
4844
|
print(f"WAITING {name}: pane {pid} runs `{cmd}`, but herdr has not seen the agent start yet — if it "
|
|
4296
4845
|
f"shows a first-run question (trust this folder, sign in), answer it, then: herdr agent rename {pid} {name}")
|
|
4297
4846
|
failed += 1
|
|
4298
4847
|
if dry:
|
|
4299
4848
|
return
|
|
4849
|
+
if opened: # an agent can start, get its name, and quit a second later (a bad flag, a missing login)
|
|
4850
|
+
time.sleep(TEAM_CONFIRM_S)
|
|
4851
|
+
for name, w, pid, cmd in opened:
|
|
4852
|
+
where, _ = herdr_presence(name)
|
|
4853
|
+
if where == "agent":
|
|
4854
|
+
continue
|
|
4855
|
+
failed += 1
|
|
4856
|
+
saved = save_screen(name, f"{w.get('kind')} quit right after `orch team up` started it")
|
|
4857
|
+
print(f"QUIT {name}: {w.get('kind')} exited right after it started — only a plain shell is left in "
|
|
4858
|
+
f"pane {pid}, so nothing will be sent there. Run `{cmd}` in that pane yourself to see why"
|
|
4859
|
+
+ (f" (its last screen is in {short(saved)})" if saved else "") + ", then `orch team up` again")
|
|
4860
|
+
log_line(f"{run_tag(st)} QUIT {name}: {w.get('kind')} exited right after `orch team up` started it "
|
|
4861
|
+
f"in pane {pid}")
|
|
4300
4862
|
print("TEAM UP: done — run `orch start` again; every agent should show herdr=found" if not failed else
|
|
4301
4863
|
f"TEAM UP: {failed} agent(s) not ready — see above, then `orch team up` again")
|
|
4302
4864
|
if failed:
|
|
@@ -4445,6 +5007,10 @@ def cmd_resume(args):
|
|
|
4445
5007
|
else:
|
|
4446
5008
|
print("Every agent in the plan is found. Nothing to resume.")
|
|
4447
5009
|
return
|
|
5010
|
+
if not from_manager:
|
|
5011
|
+
dead = note_dead_manager(st)
|
|
5012
|
+
if dead:
|
|
5013
|
+
print(dead)
|
|
4448
5014
|
beat = st["run"].get("beat")
|
|
4449
5015
|
busy = [(tid, st["tasks"][tid]["wait"]) for tid in st["order"] if st["tasks"][tid].get("wait")]
|
|
4450
5016
|
gap = account_downtime(st)
|
|
@@ -4512,10 +5078,11 @@ COMMANDS = {
|
|
|
4512
5078
|
"send-job": cmd_send_job, "handoff": cmd_handoff, "needs-fix": cmd_needs_fix, "review-ok": cmd_review_ok,
|
|
4513
5079
|
"requeue-review": cmd_requeue_review, "finish": cmd_finish, "resend": cmd_resend, "approve": cmd_approve,
|
|
4514
5080
|
"report": cmd_report, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer,
|
|
4515
|
-
"escalate": cmd_escalate, "fix": cmd_fix, "team": cmd_team,
|
|
5081
|
+
"escalate": cmd_escalate, "fix": cmd_fix, "team": cmd_team, "bench": cmd_bench, "stop": cmd_stop,
|
|
5082
|
+
"doctor": lambda a: cmd_doctor_crash(a),
|
|
4516
5083
|
}
|
|
4517
5084
|
# 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"}
|
|
5085
|
+
UNLOCKED = {"autopilot", "poll", "events", "dispatch", "answer", "fix", "team", "resume", "bench", "stop", "doctor"}
|
|
4519
5086
|
|
|
4520
5087
|
USAGE = """usage: orch <command> [args]
|
|
4521
5088
|
version print the installed herdr-orchestra version
|
|
@@ -4557,6 +5124,9 @@ USAGE = """usage: orch <command> [args]
|
|
|
4557
5124
|
merge <Mn> squash the milestone, run the check on the result, commit it ONLY if green (CONFLICT 4, CHECK_FAILED 6, HELD 7)
|
|
4558
5125
|
park <Mn> paused|failed|pending [--lost] [reason] free the worker, keep its work in a hidden ref (refs/orch/...)
|
|
4559
5126
|
cooldown <agent> <min> [reason] bench a worker or the reviewer (reason `gone`: ends once herdr sees it again)
|
|
5127
|
+
bench <worker> off [reason] | on keep a coder out of the run until you turn it back on (survives restarts)
|
|
5128
|
+
stop [--now] stop the event manager cleanly (it finishes its current step); `orch resume` starts it again
|
|
5129
|
+
doctor --crash (in a repo) why the event manager last stopped, and the last crash / lost notes
|
|
4560
5130
|
set <Mn> <status> [reason] [--force] manual override: pending/paused/failed/skipped (others need --force)
|
|
4561
5131
|
approve <Mn> let a milestone held for risky changes land (works while autopilot runs)
|
|
4562
5132
|
cleanup remove clean worker worktrees
|
|
@@ -5004,6 +5574,30 @@ def doctor_kind(kind, v, full=True):
|
|
|
5004
5574
|
return out
|
|
5005
5575
|
|
|
5006
5576
|
|
|
5577
|
+
def cmd_doctor_crash(args):
|
|
5578
|
+
"""orch doctor --crash -> the last crash, stop and lost notes of this run, and, when the event manager is not
|
|
5579
|
+
running, why it stopped (looked up in the computer's own log, for this run's processes only)."""
|
|
5580
|
+
with state_lock():
|
|
5581
|
+
st = load()
|
|
5582
|
+
dead = None if driver_alive() else note_dead_manager(st)
|
|
5583
|
+
m = (st.get("run") or {}).get("manager") or {}
|
|
5584
|
+
print(f"{run_tag(st)} event manager: " + (f"running ({driver_line(driver_info())})" if driver_alive() else
|
|
5585
|
+
"not running" + (f"; last one ended {_clock(m['ended']['ts'])}: {m['ended'].get('how')}"
|
|
5586
|
+
+ (f" — {m['ended']['reason']}" if m['ended'].get('reason') else "")
|
|
5587
|
+
if m.get("ended") else "")))
|
|
5588
|
+
if dead:
|
|
5589
|
+
print(dead)
|
|
5590
|
+
lines = last_crash_lines()
|
|
5591
|
+
print("Last notes in .orchestrate/autopilot.log:" if lines else "No crash, stop or lost notes in autopilot.log yet.")
|
|
5592
|
+
for l in lines:
|
|
5593
|
+
print(" " + l)
|
|
5594
|
+
shots = sorted((ORCH / "crash").glob("*.txt"), key=lambda p: p.stat().st_mtime)[-5:] if (ORCH / "crash").is_dir() else []
|
|
5595
|
+
if shots:
|
|
5596
|
+
print("Saved agent screens (.orchestrate/crash/):")
|
|
5597
|
+
for p in shots:
|
|
5598
|
+
print(f" {p.name}")
|
|
5599
|
+
|
|
5600
|
+
|
|
5007
5601
|
def cmd_doctor(args):
|
|
5008
5602
|
"""orch doctor [kind...] -> check each installed agent against the real tool (version, launch flags, skills,
|
|
5009
5603
|
herdr detection). Read-only. Exit 1 if anything is broken."""
|
|
@@ -5042,7 +5636,7 @@ if __name__ == "__main__":
|
|
|
5042
5636
|
NO_REPO_COMMANDS = {"lead": cmd_lead, "agents": cmd_agents, "doctor": cmd_doctor, "models": cmd_models,
|
|
5043
5637
|
"team": cmd_team}
|
|
5044
5638
|
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)
|
|
5639
|
+
and sys.argv[2:3] != ["up"] and sys.argv[2:3] != ["--crash"]): # (`orch team up` reads the run's state)
|
|
5046
5640
|
NO_REPO_COMMANDS[sys.argv[1]](sys.argv[2:])
|
|
5047
5641
|
sys.exit(0)
|
|
5048
5642
|
if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS:
|
|
@@ -5054,8 +5648,13 @@ if __name__ == "__main__":
|
|
|
5054
5648
|
STATE = ORCH / "state.json"
|
|
5055
5649
|
if sys.argv[1] not in LEASE_FREE:
|
|
5056
5650
|
require_driver()
|
|
5057
|
-
|
|
5058
|
-
|
|
5059
|
-
else:
|
|
5060
|
-
with state_lock():
|
|
5651
|
+
try:
|
|
5652
|
+
if sys.argv[1] in UNLOCKED:
|
|
5061
5653
|
COMMANDS[sys.argv[1]](sys.argv[2:])
|
|
5654
|
+
else:
|
|
5655
|
+
with state_lock():
|
|
5656
|
+
COMMANDS[sys.argv[1]](sys.argv[2:])
|
|
5657
|
+
except BrokenPipeError: # `orch status | head`: the reader has what it wanted
|
|
5658
|
+
with contextlib.suppress(OSError):
|
|
5659
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
5660
|
+
sys.exit(0)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "herdr-orchestra",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.7.1",
|
|
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
|