herdr-orchestra 5.5.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 +38 -0
- package/README.md +31 -5
- package/VERSION +1 -1
- package/bin/__pycache__/orchcpython-314.pyc +0 -0
- package/bin/orch +724 -51
- package/claude-commands/orch-plan.md +1 -1
- package/opencode-commands/orch-plan.md +1 -1
- package/package.json +1 -1
- package/playbooks/plan.md +57 -1
- package/playbooks/run.md +12 -2
- package/skills/orch-plan/SKILL.md +1 -1
package/bin/orch
CHANGED
|
@@ -13,7 +13,7 @@ Task status flow (every change goes through move(), which checks TRANSITIONS)
|
|
|
13
13
|
side states: needs-answer, paused, failed, conflict, needs-fix, held (waiting for `orch approve`), skipped
|
|
14
14
|
Also: .orchestrate/events.jsonl (one line per transition), driver.lock (held by autopilot while it drives).
|
|
15
15
|
"""
|
|
16
|
-
import contextlib, fcntl, fnmatch, hashlib, json, os, re, shlex, shutil, signal, socket, subprocess, sys, time
|
|
16
|
+
import contextlib, fcntl, fnmatch, hashlib, json, os, re, shlex, shutil, signal, socket, subprocess, sys, tempfile, time
|
|
17
17
|
from pathlib import Path
|
|
18
18
|
|
|
19
19
|
HERDR = os.environ.get("HERDR", "herdr")
|
|
@@ -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
|
|
@@ -59,6 +63,12 @@ RISK_RULES = [
|
|
|
59
63
|
(re.compile(r"(^|/)\.env(\.(?!example$|sample$|template$)[^/]+)?$|(^|/)[^/]*\.(pem|key|p12)$", re.I),
|
|
60
64
|
"secrets or environment file"),
|
|
61
65
|
]
|
|
66
|
+
# quick runs (`Mode: quick`): small, clear changes only. Files that always need the full process...
|
|
67
|
+
QUICK_NEVER = RISK_RULES + [(LOCKFILE_RE, "dependency file")]
|
|
68
|
+
# ...and names that usually mean auth or payment code: the lead should be sure before calling it quick
|
|
69
|
+
QUICK_CAREFUL_RE = re.compile(r"auth|login|logout|password|session|token|oauth|permission|rbac|acl|payment|billing|"
|
|
70
|
+
r"invoice|checkout|stripe|paypal|razorpay|subscription|schema\.(prisma|sql|rb)|models?\.py$",
|
|
71
|
+
re.I)
|
|
62
72
|
RISK_MAX_LINES = int(os.environ.get("ORCH_RISK_MAX_LINES", "1500"))
|
|
63
73
|
CHECK_TIMEOUT_S = int(os.environ.get("ORCH_CHECK_TIMEOUT_MIN", "30")) * 60
|
|
64
74
|
ACTIVE = {"coding", "verifying", "awaiting-review", "reviewing", "reviewed", "committed", "conflict", "needs-fix",
|
|
@@ -152,7 +162,7 @@ def state_lock():
|
|
|
152
162
|
|
|
153
163
|
# usable while autopilot drives: reads, and the lead's requests (the event manager carries them out)
|
|
154
164
|
LEASE_FREE = {"status", "ready", "pick", "report", "approve", "autopilot", "events", "dispatch", "answer", "fix",
|
|
155
|
-
"team", "resume"}
|
|
165
|
+
"team", "resume", "bench", "stop", "doctor"}
|
|
156
166
|
_LEASE = None
|
|
157
167
|
|
|
158
168
|
|
|
@@ -247,6 +257,216 @@ def fault(point):
|
|
|
247
257
|
os._exit(99)
|
|
248
258
|
|
|
249
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
|
+
|
|
250
470
|
# Every status change goes through move(). Statuses not listed as a key are terminal.
|
|
251
471
|
_PARK = {"pending", "paused", "failed"}
|
|
252
472
|
TRANSITIONS = {
|
|
@@ -279,6 +499,8 @@ def move(st, tid, to, why=None, force=False):
|
|
|
279
499
|
t["status"] = to
|
|
280
500
|
if why is not None:
|
|
281
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
|
|
282
504
|
if to != frm or why:
|
|
283
505
|
ev = {"ts": now(), "task": tid, "from": frm, "to": to, "why": why or "",
|
|
284
506
|
"agent": t.get("worker") or t.get("last_worker"), "attempt": t.get("attempt", 0)}
|
|
@@ -358,21 +580,61 @@ def _status_field(obj):
|
|
|
358
580
|
return found if found is not None else _find_key(obj, "status")
|
|
359
581
|
|
|
360
582
|
|
|
361
|
-
def
|
|
362
|
-
"""
|
|
363
|
-
|
|
364
|
-
|
|
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)."""
|
|
365
606
|
try:
|
|
366
607
|
r = subprocess.run([HERDR, "agent", "get", agent], text=True, capture_output=True, timeout=HERDR_TIMEOUT_S)
|
|
367
608
|
except (OSError, subprocess.TimeoutExpired):
|
|
368
|
-
return None
|
|
609
|
+
return "gone", None
|
|
369
610
|
if r.returncode != 0:
|
|
370
|
-
return None
|
|
611
|
+
return "gone", None
|
|
371
612
|
try:
|
|
372
|
-
|
|
613
|
+
data = json.loads(r.stdout)
|
|
373
614
|
except ValueError:
|
|
374
|
-
|
|
375
|
-
|
|
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]
|
|
376
638
|
|
|
377
639
|
|
|
378
640
|
def word(state, *words):
|
|
@@ -539,10 +801,12 @@ def need_rank(t):
|
|
|
539
801
|
def eligible_workers(st, t):
|
|
540
802
|
"""Workers allowed to take the task: its tier or higher (unrated workers count as any tier). When nobody on the
|
|
541
803
|
team reaches the tier, the strongest workers the team has, so a run never waits for a model nobody started."""
|
|
542
|
-
if t.get("assign") in st["workers"]:
|
|
804
|
+
if t.get("assign") in st["workers"] and not st["workers"][t["assign"]].get("off"):
|
|
543
805
|
return [t["assign"]]
|
|
544
806
|
need = need_rank(t)
|
|
545
|
-
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 []
|
|
546
810
|
ok = [n for n, r in ranks.items() if not need or not r or r >= need]
|
|
547
811
|
if not ok:
|
|
548
812
|
top = max(ranks.values())
|
|
@@ -709,7 +973,12 @@ def cmd_sync(args):
|
|
|
709
973
|
if commits not in ("per-milestone", "single"):
|
|
710
974
|
errors.append(f"Commits must be per-milestone or single, got {commits!r}")
|
|
711
975
|
title_m = re.search(r"(?m)^# Plan:\s*(.+?)\s*$", plan_text)
|
|
712
|
-
|
|
976
|
+
mode = (get("mode", "full").split() or ["full"])[0].lower()
|
|
977
|
+
if mode not in ("quick", "full"):
|
|
978
|
+
errors.append(f"Mode must be quick or full, got {mode!r}")
|
|
979
|
+
quick = mode == "quick"
|
|
980
|
+
quick_because = get("quick because")
|
|
981
|
+
isolation = get("isolation", "shared" if quick else "worktree").split()[0].lower()
|
|
713
982
|
if isolation not in ("worktree", "shared"):
|
|
714
983
|
errors.append(f"Isolation must be worktree or shared, got {isolation!r}")
|
|
715
984
|
try:
|
|
@@ -930,6 +1199,28 @@ def cmd_sync(args):
|
|
|
930
1199
|
if not field(by_id[tid], "why separate"):
|
|
931
1200
|
warns.append(f"{tid} has no `Why separate:` — say why it is its own milestone (parallel work, a "
|
|
932
1201
|
f"foundation others build on, too big for one sitting), or merge it into another")
|
|
1202
|
+
# a quick run: one small, clear milestone, the lead says why it is small, and nothing that needs the full process
|
|
1203
|
+
if quick:
|
|
1204
|
+
if not quick_because:
|
|
1205
|
+
errors.append("`Mode: quick` needs `Quick because: <what you found in the code that makes this small>` "
|
|
1206
|
+
"— e.g. `Quick because: the column already exists, only the response changes`")
|
|
1207
|
+
if len(enabled) > 1:
|
|
1208
|
+
errors.append(f"`Mode: quick` is one milestone, and this plan has {len(enabled)} — put the small changes "
|
|
1209
|
+
f"in one milestone (one acceptance criterion each), or use `Mode: full`")
|
|
1210
|
+
if isolation == "worktree":
|
|
1211
|
+
warns.append("`Mode: quick` with `Isolation: worktree`: one milestone needs no separate folder — "
|
|
1212
|
+
"`Isolation: shared` skips the worktree and its setup")
|
|
1213
|
+
for tid in enabled:
|
|
1214
|
+
never = sorted({f"{what}: {f}" for f in files[tid] for rx, what in QUICK_NEVER if rx.search(f)})
|
|
1215
|
+
if never:
|
|
1216
|
+
errors.append(f"{tid} lists {', '.join(never)} — a quick run never touches these; use `Mode: full`")
|
|
1217
|
+
careful = sorted(f for f in files[tid] if QUICK_CAREFUL_RE.search(f))
|
|
1218
|
+
if careful:
|
|
1219
|
+
warns.append(f"{tid} lists {', '.join(careful)}, which looks like auth, payment or schema code — "
|
|
1220
|
+
f"those take the full process; keep `Mode: quick` only if the change does not touch them")
|
|
1221
|
+
if has_open_questions(by_id[tid]):
|
|
1222
|
+
errors.append(f"{tid} has open questions — a quick run needs a clear change; answer them or use "
|
|
1223
|
+
f"`Mode: full`")
|
|
933
1224
|
max_tasks = int(os.environ.get("ORCH_MAX_TASKS", "0") or 0) # no limit unless you set one
|
|
934
1225
|
if max_tasks and len(enabled) > max_tasks:
|
|
935
1226
|
warns.append(f"{len(enabled)} enabled milestones (> ORCH_MAX_TASKS={max_tasks}). Merge coupled milestones "
|
|
@@ -956,6 +1247,9 @@ def cmd_sync(args):
|
|
|
956
1247
|
"base": base.split()[0] if base else None,
|
|
957
1248
|
"title": title_m.group(1) if title_m else branch,
|
|
958
1249
|
"commits": commits,
|
|
1250
|
+
"mode": mode,
|
|
1251
|
+
"quick_because": quick_because if quick else None,
|
|
1252
|
+
"green_tree": old.get("green_tree"),
|
|
959
1253
|
"integration_broken": old.get("integration_broken"),
|
|
960
1254
|
"schema": STATE_SCHEMA,
|
|
961
1255
|
"notified": old.get("notified", []),
|
|
@@ -998,6 +1292,7 @@ def cmd_sync(args):
|
|
|
998
1292
|
ow = old.get("workers", {}).get(name, {})
|
|
999
1293
|
st["workers"][name] = {"kind": kind, "task": ow.get("task"), "cooldown_until": ow.get("cooldown_until", 0),
|
|
1000
1294
|
"cooldown_reason": ow.get("cooldown_reason", ""),
|
|
1295
|
+
**({"off": ow["off"]} if ow.get("off") else {}), # kept until `orch bench <w> on`
|
|
1001
1296
|
"dir": ow.get("dir"), "setup_done": ow.get("setup_done", False),
|
|
1002
1297
|
"setup_hash": ow.get("setup_hash"), "delivery_fails": ow.get("delivery_fails", 0),
|
|
1003
1298
|
"pane": pane, "detect": detect(kind, pane, "Workers"),
|
|
@@ -1050,7 +1345,7 @@ def cmd_sync(args):
|
|
|
1050
1345
|
save(st)
|
|
1051
1346
|
for w in warns:
|
|
1052
1347
|
print("WARN:", w)
|
|
1053
|
-
print(f"OK: {len(tasks)} tasks, isolation={isolation}, max_parallel={max_par}, "
|
|
1348
|
+
print(f"OK: {len(tasks)} tasks, " + ("mode=quick, " if quick else "") + f"isolation={isolation}, max_parallel={max_par}, "
|
|
1054
1349
|
f"workers={list(workers)}, reviewer={reviewer}" + (f", lead={lead[0]}" if lead else ""))
|
|
1055
1350
|
|
|
1056
1351
|
|
|
@@ -1329,6 +1624,35 @@ def run_check(st, cwd):
|
|
|
1329
1624
|
return ok, tail, round(time.time() - t0, 1)
|
|
1330
1625
|
|
|
1331
1626
|
|
|
1627
|
+
def tree_of(d):
|
|
1628
|
+
"""Hash of the files git sees in d (tracked and untracked, not ignored), without touching the real index.
|
|
1629
|
+
Two checks of the same tree give the same answer, so a green check on it can be reused."""
|
|
1630
|
+
try:
|
|
1631
|
+
real = Path(git("rev-parse", "--path-format=absolute", "--git-path", "index", cwd=d).stdout.strip())
|
|
1632
|
+
with tempfile.TemporaryDirectory() as td:
|
|
1633
|
+
tmp = Path(td) / "index"
|
|
1634
|
+
if real.exists():
|
|
1635
|
+
shutil.copyfile(real, tmp)
|
|
1636
|
+
env = {**os.environ, "GIT_INDEX_FILE": str(tmp)}
|
|
1637
|
+
subprocess.run(["git", "add", "-A"], cwd=d, env=env, capture_output=True, timeout=120)
|
|
1638
|
+
r = subprocess.run(["git", "write-tree"], cwd=d, env=env, capture_output=True, text=True, timeout=60)
|
|
1639
|
+
return r.stdout.strip() if r.returncode == 0 and r.stdout.strip() else None
|
|
1640
|
+
except (OSError, subprocess.SubprocessError, SystemExit):
|
|
1641
|
+
return None
|
|
1642
|
+
|
|
1643
|
+
|
|
1644
|
+
def note_green(st, d, ok):
|
|
1645
|
+
"""Remember the tree a passing check ran on in the main folder (a failing one forgets it)."""
|
|
1646
|
+
if Path(d).resolve() != ROOT.resolve():
|
|
1647
|
+
return
|
|
1648
|
+
st["green_tree"] = tree_of(d) if ok else None
|
|
1649
|
+
|
|
1650
|
+
|
|
1651
|
+
def green_still(st, d):
|
|
1652
|
+
"""True when the main folder holds exactly the tree the last passing check ran on: no need to run it again."""
|
|
1653
|
+
return bool(st.get("check") and st.get("green_tree")) and tree_of(d) == st["green_tree"]
|
|
1654
|
+
|
|
1655
|
+
|
|
1332
1656
|
def path_allowed(path, patterns):
|
|
1333
1657
|
return any(path == p or fnmatch.fnmatch(path, p) or path.startswith(p.rstrip("/") + "/") for p in patterns)
|
|
1334
1658
|
|
|
@@ -1565,7 +1889,15 @@ def cmd_ready(args):
|
|
|
1565
1889
|
slots = free_slots(st)
|
|
1566
1890
|
if st["isolation"] == "shared" and slots <= 0 and active_count(st) == len(fix_jobs(st)) and fix_jobs(st):
|
|
1567
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))
|
|
1568
1898
|
print(f"SLOTS {max(slots, 0)}")
|
|
1899
|
+
if gone:
|
|
1900
|
+
print(f"NOAGENT {' '.join(gone)} (no agent in herdr: `orch team up`)")
|
|
1569
1901
|
for tid in fix_jobs(st): # fixes first: reviewed work merges sooner and unlocks dependents
|
|
1570
1902
|
print(f"FIX {tid} {st['tasks'][tid]['status']} {st['tasks'][tid]['title']}")
|
|
1571
1903
|
for tid in out:
|
|
@@ -1584,7 +1916,7 @@ def cooling(name, info):
|
|
|
1584
1916
|
|
|
1585
1917
|
|
|
1586
1918
|
def worker_free(st, name, w):
|
|
1587
|
-
if w.get("task") or cooling(name, w):
|
|
1919
|
+
if w.get("task") or w.get("off") or cooling(name, w):
|
|
1588
1920
|
return False
|
|
1589
1921
|
if not w.get("detect", True): # herdr can't watch it: no task + no cooldown = free
|
|
1590
1922
|
return True
|
|
@@ -2291,6 +2623,7 @@ def cmd_merge(args):
|
|
|
2291
2623
|
st["merging"] = None
|
|
2292
2624
|
_integration_failed(st, tid, tail)
|
|
2293
2625
|
git("commit", "-q", "-m", commit_message(st, tid), cwd=ROOT)
|
|
2626
|
+
note_green(st, ROOT, True)
|
|
2294
2627
|
fault("after-merge-commit")
|
|
2295
2628
|
git("update-ref", "-d", task_ref(st, tid), cwd=ROOT, check=False)
|
|
2296
2629
|
_finish(st, tid)
|
|
@@ -2448,6 +2781,70 @@ def cmd_cooldown(args):
|
|
|
2448
2781
|
print(f"COOLDOWN {name} for {args[1]} min" + (f" ({reason})" if reason else ""))
|
|
2449
2782
|
|
|
2450
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
|
+
|
|
2451
2848
|
STATUSES = {"pending", "coding", "verifying", "awaiting-review", "reviewing", "reviewed", "committed", "merged",
|
|
2452
2849
|
"needs-answer", "paused", "failed", "conflict", "skipped", "needs-fix", "held"}
|
|
2453
2850
|
|
|
@@ -2478,6 +2875,10 @@ def cmd_set(args):
|
|
|
2478
2875
|
|
|
2479
2876
|
def cmd_status(args):
|
|
2480
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!! "))
|
|
2481
2882
|
if driver_alive():
|
|
2482
2883
|
print(f"driven by {driver_line(driver_info())}")
|
|
2483
2884
|
elif needs_manager(st):
|
|
@@ -2486,6 +2887,8 @@ def cmd_status(args):
|
|
|
2486
2887
|
+ (f" since {_clock(beat)} ({_dur(now() - beat)} ago)" if beat else "")
|
|
2487
2888
|
+ " — nothing is watching this run, so it will not move.\n"
|
|
2488
2889
|
"!! Run `orch resume` (after a restart it also finds the agents again and re-sends their tasks).")
|
|
2890
|
+
if st.get("mode") == "quick":
|
|
2891
|
+
print(f"QUICK RUN because: {st.get('quick_because') or '-'}")
|
|
2489
2892
|
print(f"branch={st['branch']} base={st.get('base')} isolation={st['isolation']} "
|
|
2490
2893
|
f"max_parallel={st['max_parallel']} reviewer={st['reviewer']} (busy: {st.get('reviewer_busy')})")
|
|
2491
2894
|
if st.get("integration_broken"):
|
|
@@ -2493,17 +2896,27 @@ def cmd_status(args):
|
|
|
2493
2896
|
f"{st['integration_broken']} — fix it; autopilot re-checks before it continues")
|
|
2494
2897
|
for n, w in st["workers"].items():
|
|
2495
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")
|
|
2496
2903
|
print(f" worker {n:<12} {w['kind']:<8} task={w.get('task') or '-':<5} "
|
|
2497
2904
|
+ (f"model={w['model']} ({w.get('tier') or 'unrated'}) " if w.get("model") else "")
|
|
2498
2905
|
+ f"{'cooldown ' + str(cd // 60) + 'm' if cd else ''}"
|
|
2499
|
-
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 ""))
|
|
2500
2910
|
for tid in st["order"]:
|
|
2501
2911
|
t = st["tasks"][tid]
|
|
2502
2912
|
print(f" {tid:<4} {t['status']:<15} deps={','.join(t['deps']) or '-':<10} "
|
|
2503
2913
|
f"worker={t.get('worker') or '-':<10} "
|
|
2504
2914
|
+ (f"tier={t['tier'] if rank(t.get('min_tier')) <= rank(t.get('tier')) else t['min_tier'] + '^'} "
|
|
2505
2915
|
if need_rank(t) else "") + t["title"]
|
|
2506
|
-
+ (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 ""))
|
|
2507
2920
|
if lead_on(st):
|
|
2508
2921
|
ev = [e for e in st["lead_events"] if event_open(st, e)]
|
|
2509
2922
|
hold = undispatched(st)
|
|
@@ -2547,7 +2960,8 @@ def github_compare_url(remote, base, branch):
|
|
|
2547
2960
|
|
|
2548
2961
|
|
|
2549
2962
|
def cmd_finish(args):
|
|
2550
|
-
"""orch finish [--no-push] -> final check
|
|
2963
|
+
"""orch finish [--no-push] [--recheck] -> final check (reused when it already passed on exactly these files;
|
|
2964
|
+
--recheck runs it anyway), drop hidden refs and worktrees, push the feature branch, open a PR."""
|
|
2551
2965
|
st = load()
|
|
2552
2966
|
left = [f"{k} ({v['status']})" for k, v in st["tasks"].items() if v["status"] not in ("merged", "skipped")]
|
|
2553
2967
|
if left:
|
|
@@ -2555,7 +2969,9 @@ def cmd_finish(args):
|
|
|
2555
2969
|
if git("rev-parse", "--abbrev-ref", "HEAD", cwd=ROOT).stdout.strip() != st["branch"] or is_dirty(ROOT):
|
|
2556
2970
|
die(f"main tree must be clean and on {st['branch']}")
|
|
2557
2971
|
base = st.get("base") or default_base(st)
|
|
2558
|
-
if
|
|
2972
|
+
if "--recheck" not in args and green_still(st, ROOT):
|
|
2973
|
+
print(f"CHECK reused: it already passed on exactly these files ({st['green_tree'][:10]}), not run again")
|
|
2974
|
+
elif st.get("check"):
|
|
2559
2975
|
r = subprocess.run(st["check"], shell=True, cwd=ROOT, text=True, capture_output=True)
|
|
2560
2976
|
if r.returncode != 0:
|
|
2561
2977
|
die(f"the check fails on {st['branch']} — fix it before finishing:\n"
|
|
@@ -2732,14 +3148,29 @@ def start_manager():
|
|
|
2732
3148
|
return f"the event manager is running ({driver_line(driver_info())})"
|
|
2733
3149
|
if os.environ.get("ORCH_NO_AUTOSTART") == "1":
|
|
2734
3150
|
return "the event manager is NOT running — ask the developer to run `orch autopilot` in a terminal"
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
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
|
|
2743
3174
|
return ("could NOT start the event manager from here (see .orchestrate/manager.out) — ask the developer to run "
|
|
2744
3175
|
"`orch autopilot` in a terminal")
|
|
2745
3176
|
|
|
@@ -2758,6 +3189,16 @@ def cmd_dispatch(args):
|
|
|
2758
3189
|
st = load()
|
|
2759
3190
|
if opts.get("--to") and opts["--to"] not in st["workers"]:
|
|
2760
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")
|
|
2761
3202
|
if opts.get("--tier") and opts["--tier"] not in TIERS:
|
|
2762
3203
|
die("--tier must be small, medium or high")
|
|
2763
3204
|
for tid in args:
|
|
@@ -2778,8 +3219,14 @@ def cmd_dispatch(args):
|
|
|
2778
3219
|
_park(st, tid, "pending", "dispatched again by the lead")
|
|
2779
3220
|
who = [n for n in eligible_workers(st, t)]
|
|
2780
3221
|
waits = [d for d in t["deps"] if st["tasks"][d]["status"] != "merged"]
|
|
2781
|
-
print(f"DISPATCH {tid} -> {' or '.join(who)
|
|
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 "")
|
|
2782
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)")
|
|
2783
3230
|
save(st)
|
|
2784
3231
|
print(start_manager())
|
|
2785
3232
|
print("You will be woken with `orch events` when something needs you. Stop here; do not poll.")
|
|
@@ -2915,6 +3362,13 @@ EVENT_HELP = {
|
|
|
2915
3362
|
"reviewer-lost": "the reviewer can't be reached, so the milestone waits for review (its work is kept). Tell the "
|
|
2916
3363
|
"developer the fix in the event text (usually: rename the reviewer's new pane). Review resumes "
|
|
2917
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.",
|
|
2918
3372
|
"all_done": "every milestone landed. Finish .orchestrate/summary.md (see `orch lead run`, section ALL_DONE).",
|
|
2919
3373
|
"stopped": "the event manager stopped. Tell the developer why; they run `orch resume` (or `orch autopilot`).",
|
|
2920
3374
|
}
|
|
@@ -3051,25 +3505,138 @@ RATE_RE = re.compile(r"usage limit|rate.?limit|quota|too many requests|\b429\b|l
|
|
|
3051
3505
|
re.I)
|
|
3052
3506
|
|
|
3053
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
|
+
|
|
3054
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):
|
|
3055
3616
|
"""The event manager: a plain script that watches the agents, runs checks, sends fixes and reviews, merges, and
|
|
3056
3617
|
wakes the lead when something needs a decision. It is the only driver of a run: it holds the driver lease, and
|
|
3057
3618
|
other processes can't change the run meanwhile (the lead's `orch dispatch` / `orch answer` are requests it
|
|
3058
3619
|
carries out). Without a lead (`Lead mode: off`) it dispatches by itself and stops (exit 3) when a human is needed."""
|
|
3059
3620
|
me = [sys.executable, os.path.abspath(__file__)]
|
|
3060
|
-
|
|
3061
|
-
|
|
3621
|
+
if os.environ.get("ORCH_FAULT") == "autopilot-error":
|
|
3622
|
+
raise ValueError("test crash") # test hook: a Python error inside the event manager
|
|
3062
3623
|
|
|
3063
3624
|
def say(msg, important=False):
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
with log.open("a") as f:
|
|
3067
|
-
f.write(line + "\n")
|
|
3625
|
+
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
|
|
3626
|
+
log_line(msg)
|
|
3068
3627
|
if important and shutil.which("notify-send"):
|
|
3069
3628
|
subprocess.run(["notify-send", "orch autopilot", msg], capture_output=True)
|
|
3070
3629
|
|
|
3071
3630
|
def run(*a, ok=(0,)):
|
|
3072
|
-
|
|
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
|
|
3073
3640
|
out = (r.stdout + r.stderr).strip()
|
|
3074
3641
|
if r.returncode not in ok:
|
|
3075
3642
|
raise RuntimeError(f"orch {' '.join(str(x) for x in a)} -> exit {r.returncode}: {out}")
|
|
@@ -3083,6 +3650,7 @@ def cmd_autopilot(args):
|
|
|
3083
3650
|
|
|
3084
3651
|
def check(cwd, tid=None, where="worktree"):
|
|
3085
3652
|
ok, tail, secs = run_check(st, cwd)
|
|
3653
|
+
patch_state(lambda s_: note_green(s_, cwd, ok))
|
|
3086
3654
|
if tid:
|
|
3087
3655
|
patch_state(lambda s_: s_["tasks"][tid].setdefault("checks", []).append(
|
|
3088
3656
|
{"where": where, "ok": ok, "secs": secs, "ts": now()}))
|
|
@@ -3457,11 +4025,24 @@ def cmd_autopilot(args):
|
|
|
3457
4025
|
run("cooldown", agent, GONE_COOLDOWN_MIN, "gone")
|
|
3458
4026
|
say(f"reviewer {agent} is gone — restart it; {tid} waits for review (the coder's work is kept)", True)
|
|
3459
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")
|
|
3460
4036
|
park(tid, "pending", f"{agent} disappeared from herdr", important=False, lost=True)
|
|
3461
4037
|
run("cooldown", agent, GONE_COOLDOWN_MIN, "gone")
|
|
3462
|
-
|
|
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)
|
|
3463
4043
|
|
|
3464
4044
|
run("sync")
|
|
4045
|
+
manager_begin()
|
|
3465
4046
|
_, start_out = run("start")
|
|
3466
4047
|
for line in start_out.splitlines():
|
|
3467
4048
|
if line.startswith(("RECOVERED", "WARN agent")):
|
|
@@ -3507,9 +4088,42 @@ def cmd_autopilot(args):
|
|
|
3507
4088
|
last_tick = time.time()
|
|
3508
4089
|
slept = sleep_meter()
|
|
3509
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
|
|
3510
4118
|
|
|
3511
4119
|
while True:
|
|
4120
|
+
_stop_point()
|
|
3512
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()
|
|
3513
4127
|
# 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
|
|
3514
4128
|
el, last_tick = time.time() - last_tick, time.time()
|
|
3515
4129
|
asleep = slept()
|
|
@@ -3553,7 +4167,11 @@ def cmd_autopilot(args):
|
|
|
3553
4167
|
st = load()
|
|
3554
4168
|
tasks = st["tasks"]
|
|
3555
4169
|
if all(t["status"] in ("merged", "skipped") for t in tasks.values()):
|
|
3556
|
-
|
|
4170
|
+
if green_still(st, ROOT): # the last passing check ran on exactly these files
|
|
4171
|
+
ok, tail = True, ""
|
|
4172
|
+
say("final check: the check already passed on exactly these files, not run again")
|
|
4173
|
+
else:
|
|
4174
|
+
ok, tail = check(ROOT)
|
|
3557
4175
|
if not ok:
|
|
3558
4176
|
patch_state(lambda s_: s_.update(integration_broken="the final check"))
|
|
3559
4177
|
patch_state(lambda s_: s_["run"].update(ended=now()))
|
|
@@ -3576,12 +4194,14 @@ def cmd_autopilot(args):
|
|
|
3576
4194
|
models.append(f"| {k} | {v.get('tier') or 'any'} | {ran} | "
|
|
3577
4195
|
f"{'yes' if v.get('escalated') else 'no'} | {v.get('model_why') or '-'} |")
|
|
3578
4196
|
lead_ = lead_on(st)
|
|
4197
|
+
quick_run = st.get("mode") == "quick"
|
|
3579
4198
|
prev = ORCH / "summary.md"
|
|
3580
4199
|
if prev.exists(): # a fix after ALL_DONE writes the summary again: keep the lead's notes
|
|
3581
4200
|
shutil.copyfile(prev, ORCH / "summary.prev.md")
|
|
3582
4201
|
(ORCH / "summary.md").write_text(
|
|
3583
4202
|
f"# Summary: {st.get('title') or st['branch']}\n\nBranch `{st['branch']}` into `{base}`. "
|
|
3584
4203
|
f"Final check on the branch: {'PASS' if ok else 'FAIL'}\n\n"
|
|
4204
|
+
+ (f"Quick run because: {st.get('quick_because') or '-'}\n\n" if quick_run else "") +
|
|
3585
4205
|
"## Tasks\n" + "\n".join(f"- {k}: {v['title']} ({v['status']}, last coder {v.get('worker') or v.get('last_worker') or '-'})"
|
|
3586
4206
|
for k, v in tasks.items()) +
|
|
3587
4207
|
f"\n\n## Commits\n```\n{log_}```\n\n## Files changed\n```\n{stat}```\n\n"
|
|
@@ -3594,10 +4214,12 @@ def cmd_autopilot(args):
|
|
|
3594
4214
|
f"{auto_checked(st, ok)}\n\n"
|
|
3595
4215
|
f"## Run report\n```\n{report}\n```\n\n"
|
|
3596
4216
|
+ ("## Still to write (the lead was woken to write these)\n" if lead_ else
|
|
3597
|
-
"## Still to write (ask the lead: 'use the orch-run skill' to finish the summary)\n")
|
|
3598
|
-
"- Design decisions & study notes\n"
|
|
3599
|
-
"-
|
|
3600
|
-
|
|
4217
|
+
"## Still to write (ask the lead: 'use the orch-run skill' to finish the summary)\n")
|
|
4218
|
+
+ ("" if quick_run else "- Design decisions & study notes\n")
|
|
4219
|
+
+ ("- What changed: one line per change, in the developer's words, and how it was checked\n"
|
|
4220
|
+
if quick_run else
|
|
4221
|
+
"- Checked by the lead: what you verified yourself by running a command or reading the code, with "
|
|
4222
|
+
"the evidence\n") +
|
|
3601
4223
|
"- Manual verification checklist: only what a person must see or do (how the UI looks and behaves, a "
|
|
3602
4224
|
"real device, an outside account). Nothing a command or a look at the code can settle.\n"
|
|
3603
4225
|
+ ("\nThe summary before this one is in `.orchestrate/summary.prev.md`: carry its notes and checklist "
|
|
@@ -4163,7 +4785,7 @@ def team_up(args):
|
|
|
4163
4785
|
if not todo:
|
|
4164
4786
|
print("TEAM UP: every agent in the plan is running")
|
|
4165
4787
|
return
|
|
4166
|
-
failed, last = 0, None
|
|
4788
|
+
failed, last, opened = 0, None, []
|
|
4167
4789
|
for name, w, d in todo:
|
|
4168
4790
|
kind, model = w.get("kind"), w.get("model")
|
|
4169
4791
|
v = reg.get(kind)
|
|
@@ -4211,12 +4833,26 @@ def team_up(args):
|
|
|
4211
4833
|
time.sleep(min(2.0, max(0.2, TEAM_WAIT_S / 30)))
|
|
4212
4834
|
if named:
|
|
4213
4835
|
print(f"OPENED {name}: pane {pid} in {short(d)} running `{cmd}`")
|
|
4836
|
+
opened.append((name, w, pid, cmd))
|
|
4214
4837
|
else:
|
|
4215
4838
|
print(f"WAITING {name}: pane {pid} runs `{cmd}`, but herdr has not seen the agent start yet — if it "
|
|
4216
4839
|
f"shows a first-run question (trust this folder, sign in), answer it, then: herdr agent rename {pid} {name}")
|
|
4217
4840
|
failed += 1
|
|
4218
4841
|
if dry:
|
|
4219
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}")
|
|
4220
4856
|
print("TEAM UP: done — run `orch start` again; every agent should show herdr=found" if not failed else
|
|
4221
4857
|
f"TEAM UP: {failed} agent(s) not ready — see above, then `orch team up` again")
|
|
4222
4858
|
if failed:
|
|
@@ -4365,6 +5001,10 @@ def cmd_resume(args):
|
|
|
4365
5001
|
else:
|
|
4366
5002
|
print("Every agent in the plan is found. Nothing to resume.")
|
|
4367
5003
|
return
|
|
5004
|
+
if not from_manager:
|
|
5005
|
+
dead = note_dead_manager(st)
|
|
5006
|
+
if dead:
|
|
5007
|
+
print(dead)
|
|
4368
5008
|
beat = st["run"].get("beat")
|
|
4369
5009
|
busy = [(tid, st["tasks"][tid]["wait"]) for tid in st["order"] if st["tasks"][tid].get("wait")]
|
|
4370
5010
|
gap = account_downtime(st)
|
|
@@ -4432,10 +5072,11 @@ COMMANDS = {
|
|
|
4432
5072
|
"send-job": cmd_send_job, "handoff": cmd_handoff, "needs-fix": cmd_needs_fix, "review-ok": cmd_review_ok,
|
|
4433
5073
|
"requeue-review": cmd_requeue_review, "finish": cmd_finish, "resend": cmd_resend, "approve": cmd_approve,
|
|
4434
5074
|
"report": cmd_report, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer,
|
|
4435
|
-
"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),
|
|
4436
5077
|
}
|
|
4437
5078
|
# they lock per step instead of for the whole command (long-running, or they start the event manager after)
|
|
4438
|
-
UNLOCKED = {"autopilot", "poll", "events", "dispatch", "answer", "fix", "team", "resume"}
|
|
5079
|
+
UNLOCKED = {"autopilot", "poll", "events", "dispatch", "answer", "fix", "team", "resume", "bench", "stop", "doctor"}
|
|
4439
5080
|
|
|
4440
5081
|
USAGE = """usage: orch <command> [args]
|
|
4441
5082
|
version print the installed herdr-orchestra version
|
|
@@ -4477,10 +5118,13 @@ USAGE = """usage: orch <command> [args]
|
|
|
4477
5118
|
merge <Mn> squash the milestone, run the check on the result, commit it ONLY if green (CONFLICT 4, CHECK_FAILED 6, HELD 7)
|
|
4478
5119
|
park <Mn> paused|failed|pending [--lost] [reason] free the worker, keep its work in a hidden ref (refs/orch/...)
|
|
4479
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
|
|
4480
5124
|
set <Mn> <status> [reason] [--force] manual override: pending/paused/failed/skipped (others need --force)
|
|
4481
5125
|
approve <Mn> let a milestone held for risky changes land (works while autopilot runs)
|
|
4482
5126
|
cleanup remove clean worker worktrees
|
|
4483
|
-
finish [--no-push]
|
|
5127
|
+
finish [--no-push] [--recheck] final check (reused if it passed on these exact files), push, open a PR
|
|
4484
5128
|
write-task <Mn> generate TASKDIR/task.md from plan.md (+ reports of merged dependencies)
|
|
4485
5129
|
nudge <Mn> re-send the current prompt once to an agent that stopped early
|
|
4486
5130
|
autopilot the event manager: watches agents, checks, merges, wakes the lead; exits 0 ALL_DONE, 3 when it needs you
|
|
@@ -4924,6 +5568,30 @@ def doctor_kind(kind, v, full=True):
|
|
|
4924
5568
|
return out
|
|
4925
5569
|
|
|
4926
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
|
+
|
|
4927
5595
|
def cmd_doctor(args):
|
|
4928
5596
|
"""orch doctor [kind...] -> check each installed agent against the real tool (version, launch flags, skills,
|
|
4929
5597
|
herdr detection). Read-only. Exit 1 if anything is broken."""
|
|
@@ -4962,7 +5630,7 @@ if __name__ == "__main__":
|
|
|
4962
5630
|
NO_REPO_COMMANDS = {"lead": cmd_lead, "agents": cmd_agents, "doctor": cmd_doctor, "models": cmd_models,
|
|
4963
5631
|
"team": cmd_team}
|
|
4964
5632
|
if (len(sys.argv) >= 2 and sys.argv[1] in NO_REPO_COMMANDS # work outside a git repo
|
|
4965
|
-
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)
|
|
4966
5634
|
NO_REPO_COMMANDS[sys.argv[1]](sys.argv[2:])
|
|
4967
5635
|
sys.exit(0)
|
|
4968
5636
|
if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS:
|
|
@@ -4974,8 +5642,13 @@ if __name__ == "__main__":
|
|
|
4974
5642
|
STATE = ORCH / "state.json"
|
|
4975
5643
|
if sys.argv[1] not in LEASE_FREE:
|
|
4976
5644
|
require_driver()
|
|
4977
|
-
|
|
4978
|
-
|
|
4979
|
-
else:
|
|
4980
|
-
with state_lock():
|
|
5645
|
+
try:
|
|
5646
|
+
if sys.argv[1] in UNLOCKED:
|
|
4981
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)
|