herdr-orchestra 5.3.0 → 5.5.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/bin/orch CHANGED
@@ -34,6 +34,7 @@ LEAD_SETTLE_S = int(os.environ.get("ORCH_LEAD_SETTLE_S", "300")) # at ALL_DO
34
34
  LEAD_MAX_WAKES = int(os.environ.get("ORCH_LEAD_MAX_WAKES", "3")) # ...this many times, then tell the developer
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
+ DOWN_MIN_S = int(os.environ.get("ORCH_DOWN_MIN_S", "120")) # the event manager silent for longer than this was down
37
38
  MAX_FIX = 3
38
39
  MAX_REVIEW = 2
39
40
  MAX_CONFLICT = 2
@@ -63,6 +64,7 @@ CHECK_TIMEOUT_S = int(os.environ.get("ORCH_CHECK_TIMEOUT_MIN", "30")) * 60
63
64
  ACTIVE = {"coding", "verifying", "awaiting-review", "reviewing", "reviewed", "committed", "conflict", "needs-fix",
64
65
  "held"}
65
66
  TERMINAL_OK = {"merged"}
67
+ RESTING = {"pending", "paused", "failed", "needs-fix", "conflict"} # no agent on it; a coder takes it up again later
66
68
 
67
69
 
68
70
  # ---------------------------------------------------------------- helpers
@@ -150,7 +152,7 @@ def state_lock():
150
152
 
151
153
  # usable while autopilot drives: reads, and the lead's requests (the event manager carries them out)
152
154
  LEASE_FREE = {"status", "ready", "pick", "report", "approve", "autopilot", "events", "dispatch", "answer", "fix",
153
- "team"}
155
+ "team", "resume"}
154
156
  _LEASE = None
155
157
 
156
158
 
@@ -987,6 +989,7 @@ def cmd_sync(args):
987
989
  "lead_seq": old.get("lead_seq", 0),
988
990
  "lead_wake": old.get("lead_wake"),
989
991
  "lead_ready_told": old.get("lead_ready_told"),
992
+ "tree_task": old.get("tree_task"),
990
993
  "workers": {},
991
994
  "order": ids,
992
995
  "tasks": {},
@@ -1112,6 +1115,106 @@ def restore_stash(st, tid):
1112
1115
  git("update-ref", "-d", ref, cwd=ROOT)
1113
1116
 
1114
1117
 
1118
+ def rescue_ref(st, who):
1119
+ """A hidden ref for unsaved files orch found and could not give to a milestone. Kept by `orch finish`."""
1120
+ ref = f"{REF_NS}/{st['branch'].replace('/', '-')}/rescue-{who}-{time.strftime('%Y%m%d-%H%M%S')}"
1121
+ n = 1
1122
+ while ref_ok(ref if n == 1 else f"{ref}-{n}"): # never write over an earlier rescue
1123
+ n += 1
1124
+ return ref if n == 1 else f"{ref}-{n}"
1125
+
1126
+
1127
+ def _last_task_of(st, name):
1128
+ """The milestone this coder worked on most recently (by its recorded attempts), or None."""
1129
+ best = (0, None)
1130
+ for tid in st["order"]:
1131
+ ends = [a.get("end", 0) for a in st["tasks"][tid].get("attempts") or []
1132
+ if a.get("kind") == "coder" and a.get("agent") == name]
1133
+ if ends and max(ends) > best[0]:
1134
+ best = (max(ends), tid)
1135
+ return best[1]
1136
+
1137
+
1138
+ def save_stray(st, name, rescue=True):
1139
+ """Worktree mode: a coder that holds no milestone has uncommitted files in its folder (it kept working after
1140
+ its milestone was parked, or the machine went down). Save them into the milestone they belong to: the one
1141
+ whose saved work this folder is on, else the one this coder worked on last if nothing of it was saved yet.
1142
+ When orch can't tell whose they are, they go to a rescue ref (rescue=True) or stay where they are.
1143
+ Returns a line saying what happened, or None when there was nothing to save."""
1144
+ w = st["workers"].get(name) or {}
1145
+ d = w.get("dir")
1146
+ if st["isolation"] != "worktree" or w.get("task") or not d or not Path(d).exists() or not is_dirty(d):
1147
+ return None
1148
+ head = git("rev-parse", "HEAD", cwd=d).stdout.strip()
1149
+ owner = None
1150
+ for tid in st["order"]:
1151
+ if st["tasks"][tid]["status"] in RESTING and ref_ok(task_ref(st, tid)) and \
1152
+ git("rev-parse", task_ref(st, tid), cwd=ROOT).stdout.strip() == head:
1153
+ owner = tid
1154
+ break
1155
+ if not owner:
1156
+ last = _last_task_of(st, name)
1157
+ lt = st["tasks"].get(last) or {}
1158
+ if last and lt["status"] in RESTING and lt.get("last_worker") == name and not lt.get("worker") \
1159
+ and not work_ref(st, last) and not ahead_of_branch(st, d):
1160
+ owner = last
1161
+ if owner:
1162
+ wip_commit(d, f"orch wip {owner}: files written after it was parked")
1163
+ git("update-ref", task_ref(st, owner), "HEAD", cwd=d)
1164
+ return f"SAVED {name}'s unsaved files into {owner}'s saved work ({task_ref(st, owner)})"
1165
+ if not rescue:
1166
+ return None
1167
+ ref = rescue_ref(st, name)
1168
+ wip_commit(d, f"orch rescue: unsaved files found in {name}'s folder")
1169
+ git("update-ref", ref, "HEAD", cwd=d)
1170
+ return (f"RESCUED {name}'s unsaved files: orch can't tell which milestone they belong to, so they are kept in "
1171
+ f"{ref} (`git show --stat {ref}` to look)")
1172
+
1173
+
1174
+ def shared_fold(st, tid):
1175
+ """Shared mode: the main folder has uncommitted files that belong to Mn (written after Mn was parked). Add
1176
+ them to Mn's saved work and leave the folder clean. If they can't be combined with what was saved before,
1177
+ the newer files are kept in a rescue ref. Returns a line saying what happened."""
1178
+ ref = task_ref(st, tid)
1179
+ if not ref_ok(ref):
1180
+ stash_to_ref(st, tid)
1181
+ return f"SAVED the unsaved files in the main folder into {tid}'s saved work ({ref})"
1182
+ old = git("rev-parse", ref, cwd=ROOT).stdout.strip()
1183
+ git("stash", "push", "--include-untracked", "-q", "-m", f"orch {tid} later", cwd=ROOT)
1184
+ new = git("rev-parse", "stash@{0}", cwd=ROOT).stdout.strip()
1185
+ keep = rescue_ref(st, tid)
1186
+ git("update-ref", keep, new, cwd=ROOT) # safe before anything else is tried
1187
+ git("stash", "drop", "-q", cwd=ROOT)
1188
+
1189
+ def wipe():
1190
+ git("reset", "--hard", "-q", "HEAD", cwd=ROOT)
1191
+ git("clean", "-fdq", cwd=ROOT) # only what the applies below put there: both are kept in refs
1192
+ if git("stash", "apply", "-q", old, cwd=ROOT, check=False).returncode == 0 and \
1193
+ git("stash", "apply", "-q", new, cwd=ROOT, check=False).returncode == 0:
1194
+ stash_to_ref(st, tid) # both together are Mn's saved work now
1195
+ git("update-ref", "-d", keep, cwd=ROOT)
1196
+ return f"SAVED the unsaved files in the main folder into {tid}'s saved work ({ref})"
1197
+ wipe()
1198
+ return (f"RESCUED the unsaved files in the main folder: they don't fit on top of {tid}'s saved work, so they "
1199
+ f"are kept in {keep} (`git stash show -p {new[:12]}` to look); {tid} keeps its earlier saved work")
1200
+
1201
+
1202
+ def stop_note(st, agent, tid, status, reason):
1203
+ """Tell a coder whose milestone was just paused or failed to stop. Only when it is (or may be) still working;
1204
+ whatever it writes anyway is saved the next time the milestone or its folder is used."""
1205
+ if watched(st, agent):
1206
+ s = herdr_state(agent)
1207
+ if s is None or not word(s, "working"):
1208
+ return False
1209
+ why = " ".join((reason or status).split())[:160]
1210
+ try:
1211
+ deliver(st, agent, f"STOP: {tid} is {status} ({why}). Stop working on it now and do not change any more "
1212
+ f"files. What you did so far is saved. You get a new prompt if it continues.")
1213
+ except DeliveryError:
1214
+ return False
1215
+ return True
1216
+
1217
+
1115
1218
  def commit_message(st, tid):
1116
1219
  """Commit message for a landed milestone: the coder's `COMMIT:` line (what changed), else the title.
1117
1220
  The milestone id is a trailer, never the subject."""
@@ -1384,6 +1487,7 @@ def cmd_start(args):
1384
1487
  agents = [(name, w, "WORKER") for name, w in st["workers"].items()]
1385
1488
  if st.get("reviewer"):
1386
1489
  agents.append((st["reviewer"], st.get("reviewer_info") or {}, "REVIEWER"))
1490
+ lost = False
1387
1491
  for name, w, label in agents:
1388
1492
  where = f" dir={w['dir']}" if label == "WORKER" else ""
1389
1493
  if w.get("pane"):
@@ -1398,7 +1502,11 @@ def cmd_start(args):
1398
1502
  herdr = "detect:off (relying on its done file)"
1399
1503
  else:
1400
1504
  herdr = "found" if herdr_state(name) is not None else "NOT FOUND"
1505
+ lost = lost or herdr == "NOT FOUND"
1401
1506
  print(f"{label} {name} kind={w.get('kind')}{where} herdr={herdr}")
1507
+ if lost:
1508
+ print("HINT an agent herdr can't find: after a herdr or computer restart the panes come back without their "
1509
+ "names — `orch resume` names them again; `orch team up` opens the ones that are really gone")
1402
1510
 
1403
1511
 
1404
1512
  def deps_met(st, t):
@@ -1519,23 +1627,36 @@ def cmd_prepare(args):
1519
1627
  die("no free slot (max parallel reached)")
1520
1628
  d = Path(w["dir"] or ROOT)
1521
1629
  if st["isolation"] == "worktree":
1522
- if is_dirty(d):
1523
- die(f"{d} has uncommitted changes — park or clean that worker first")
1630
+ in_place = w.get("task") == tid and is_dirty(d) # its own work in progress: it carries on right there
1631
+ if is_dirty(d) and not in_place: # never refuse: save what is there first, then hand the folder over
1632
+ print(save_stray(st, worker))
1524
1633
  src = work_ref(st, tid)
1525
1634
  if src and src != task_ref(st, tid): # pre-4.5 task branch: carry its work over to the hidden ref
1526
1635
  git("update-ref", task_ref(st, tid), src, cwd=ROOT)
1527
1636
  src = task_ref(st, tid)
1528
- git("switch", "-q", "--detach", src or st["branch"], cwd=d)
1637
+ if not in_place:
1638
+ git("switch", "-q", "--detach", src or st["branch"], cwd=d)
1529
1639
  else:
1530
1640
  if git("rev-parse", "--abbrev-ref", "HEAD", cwd=ROOT).stdout.strip() != st["branch"]:
1531
1641
  die(f"main tree is not on {st['branch']}")
1642
+ mine = False
1643
+ if is_dirty(ROOT) and not holds(st, tid) and not coders_busy(st):
1644
+ # files written after a milestone was parked belong to the milestone that had the folder last
1645
+ last = st.get("tree_task")
1646
+ if last == tid:
1647
+ mine = True
1648
+ if ref_ok(task_ref(st, tid)):
1649
+ print(shared_fold(st, tid))
1650
+ elif last in st["tasks"] and st["tasks"][last]["status"] in RESTING:
1651
+ print(shared_fold(st, last))
1532
1652
  if ref_ok(task_ref(st, tid)):
1533
1653
  if is_dirty(ROOT):
1534
1654
  die(f"main tree has uncommitted changes, so {tid}'s parked work ({task_ref(st, tid)}) can't be "
1535
1655
  f"restored — finish or discard them first")
1536
1656
  restore_stash(st, tid)
1537
- elif is_dirty(ROOT) and t["status"] == "pending" and not holds(st, tid):
1657
+ elif is_dirty(ROOT) and t["status"] == "pending" and not holds(st, tid) and not mine:
1538
1658
  die("main tree has uncommitted changes that no milestone owns — commit, stash or discard them first")
1659
+ st["tree_task"] = tid
1539
1660
  (d / TASK_DIR / tid).mkdir(parents=True, exist_ok=True)
1540
1661
  t.update(worker=worker, last_worker=worker, dir=str(d))
1541
1662
  t.pop("assign", None) # a lead's "this coder" holds for one dispatch; later retries may move
@@ -1561,14 +1682,83 @@ def cmd_setup_done(args):
1561
1682
  print("OK")
1562
1683
 
1563
1684
 
1685
+ def sleep_meter():
1686
+ """Returns a function that tells how many seconds the computer was suspended since its last call (0 when
1687
+ less than DOWN_MIN_S). The wall clock keeps going while a laptop sleeps and the monotonic clock does not,
1688
+ so the difference is the time this process could not run. (ORCH_TEST_SLEPT_S: a test's pretend sleep.)"""
1689
+ last = [time.time(), time.monotonic()]
1690
+ fake = [float(os.environ.get("ORCH_TEST_SLEPT_S") or 0)]
1691
+
1692
+ def slept():
1693
+ wall, mono = time.time(), time.monotonic()
1694
+ s = (wall - last[0]) - (mono - last[1]) + fake[0]
1695
+ last[0], last[1], fake[0] = wall, mono, 0
1696
+ return int(s) if s >= DOWN_MIN_S else 0
1697
+ return slept
1698
+
1699
+
1700
+ def account_downtime(st, slept=0):
1701
+ """The event manager writes a heartbeat (`run.beat`) every loop. A heartbeat older than DOWN_MIN_S when it
1702
+ starts again means nothing was watching the run meanwhile (computer off, herdr closed, manager killed).
1703
+ `slept` is the same thing found while running: the computer was suspended for that many seconds until now.
1704
+ That time is nobody's working time: every open wait is moved forward by it, so no task is paused as "over
1705
+ its time budget" for time orch was not there, and the window is kept in `run.downs` for the time report.
1706
+ Returns the seconds newly taken out (0 = orch was not down, or that time was taken out already)."""
1707
+ run = st.setdefault("run", {})
1708
+ t = now()
1709
+ beat = t - slept if slept else run.get("beat")
1710
+ run["beat"] = t
1711
+ if not beat or t - beat < DOWN_MIN_S:
1712
+ return 0
1713
+ # never the same time twice: `orch poll` and the event manager both notice one sleep, seconds apart
1714
+ known = sum(max(0, min(t, d["to"]) - max(beat, d["from"])) for d in run.get("downs") or [])
1715
+ if t - beat - known < (DOWN_MIN_S if slept else 1):
1716
+ return 0
1717
+ beat += known
1718
+ run.setdefault("downs", []).append({"from": beat, "to": t})
1719
+ del run["downs"][:-100]
1720
+ for task_ in st["tasks"].values():
1721
+ w = task_.get("wait")
1722
+ if w:
1723
+ w["down_s"] = w.get("down_s", 0) + max(0, t - max(beat, w.get("started", w["since"])))
1724
+ w["since"] += max(0, t - max(beat, w["since"]))
1725
+ if w.get("blocked_since"):
1726
+ w["blocked_since"] += max(0, t - max(beat, w["blocked_since"]))
1727
+ if task_.get("ready_ts"): # the lead could not dispatch while orch was down either
1728
+ task_["ready_ts"] += max(0, t - max(beat, task_["ready_ts"]))
1729
+ return t - beat
1730
+
1731
+
1732
+ def needs_manager(st):
1733
+ """True when the run has work only the event manager can move on: an agent being waited on, a step in
1734
+ progress, or a milestone that is ready and released."""
1735
+ if not (st.get("run") or {}).get("started"):
1736
+ return False # never driven yet: `orch autopilot` (or a dispatch) starts it
1737
+ for t in st["tasks"].values():
1738
+ if t.get("wait") or (t["status"] in ACTIVE and t["status"] != "held"):
1739
+ return True
1740
+ if t["status"] == "pending" and deps_met(st, t) and (t.get("go") or not lead_on(st)):
1741
+ return True
1742
+ return False
1743
+
1744
+
1745
+ def _clock(ts):
1746
+ """11:42 for today, else 2026-11-14 11:42."""
1747
+ lt = time.localtime(ts)
1748
+ return time.strftime("%H:%M" if lt[:3] == time.localtime()[:3] else "%Y-%m-%d %H:%M", lt)
1749
+
1750
+
1564
1751
  def record_attempt(t, outcome, usage=None):
1565
1752
  """Close the task's current wait as one attempt in its metrics (Phase 3: orch report)."""
1566
1753
  w = t.get("wait")
1567
1754
  if not w:
1568
1755
  return
1569
1756
  start = w.get("started", w.get("since", now()))
1757
+ down = min(w.get("down_s", 0), max(0, now() - start)) # orch was not running: not the agent's time
1570
1758
  a = {"kind": w.get("kind"), "agent": w.get("agent"), "file": w.get("file"), "start": start, "end": now(),
1571
- "secs": max(0, now() - start), "nudges": w.get("nudges", 0), "outcome": outcome}
1759
+ "secs": max(0, now() - start - down), "nudges": w.get("nudges", 0), "outcome": outcome}
1760
+ if down:
1761
+ a["down_s"] = down
1572
1762
  if w.get("model"):
1573
1763
  a["model"], a["tier"] = w["model"], w.get("tier")
1574
1764
  blocked = w.get("blocked_s", 0) + (now() - w["blocked_since"] if w.get("blocked_since") else 0)
@@ -1902,10 +2092,14 @@ def cmd_poll(args):
1902
2092
  secs = int(args[0]) if args else 100
1903
2093
  start = time.time()
1904
2094
  end = start + secs
2095
+ slept = sleep_meter()
1905
2096
  while True:
1906
2097
  with state_lock():
1907
2098
  st = load()
1908
2099
  events, changed = [], False
2100
+ asleep = slept()
2101
+ if asleep and account_downtime(st, asleep):
2102
+ changed = True # the computer was asleep: that time is not on any agent's clock
1909
2103
  for tid in st["order"]:
1910
2104
  t = st["tasks"][tid]
1911
2105
  w = t.get("wait")
@@ -2189,7 +2383,11 @@ def _park(st, tid, status, reason, force=False):
2189
2383
  t = st["tasks"][tid]
2190
2384
  record_attempt(t, f"parked as {status}: {reason}" if reason else f"parked as {status}")
2191
2385
  d, w = t.get("dir"), t.get("worker")
2386
+ wait, note_to = t.get("wait") or {}, None
2192
2387
  if w and holds(st, tid):
2388
+ if status in ("paused", "failed") and wait.get("kind") == "coder" and wait.get("agent") == w \
2389
+ and not Path(wait["sentinel"]).exists():
2390
+ note_to = w # parked under a coder that had not finished: tell it to stop
2193
2391
  if st["isolation"] == "worktree" and d and Path(d).exists():
2194
2392
  if is_dirty(d):
2195
2393
  wip_commit(d, f"orch wip {tid}: parked — {reason or status}")
@@ -2198,6 +2396,15 @@ def _park(st, tid, status, reason, force=False):
2198
2396
  elif st["isolation"] == "shared":
2199
2397
  stash_to_ref(st, tid) # the tree is clean again, so the next milestone can start
2200
2398
  st["workers"][w]["task"] = None
2399
+ elif t["status"] in RESTING:
2400
+ # already parked, but its coder may have kept writing since: that work is saved too, never skipped
2401
+ saved = None
2402
+ if st["isolation"] == "worktree":
2403
+ saved = save_stray(st, w or t.get("last_worker"), rescue=False)
2404
+ elif st.get("tree_task") == tid and not coders_busy(st) and is_dirty(ROOT):
2405
+ saved = shared_fold(st, tid)
2406
+ if saved:
2407
+ print(saved)
2201
2408
  if w:
2202
2409
  t["last_worker"], t["worker"] = w, None
2203
2410
  if st.get("reviewer_busy") == tid:
@@ -2205,6 +2412,8 @@ def _park(st, tid, status, reason, force=False):
2205
2412
  move(st, tid, status, reason, force=force)
2206
2413
  t["wait"] = None
2207
2414
  save(st)
2415
+ if note_to and stop_note(st, note_to, tid, status, reason):
2416
+ print(f"STOP_NOTE {tid} -> {note_to}: told to stop and not change more files")
2208
2417
 
2209
2418
 
2210
2419
  def cmd_park(args):
@@ -2271,6 +2480,12 @@ def cmd_status(args):
2271
2480
  st = load()
2272
2481
  if driver_alive():
2273
2482
  print(f"driven by {driver_line(driver_info())}")
2483
+ elif needs_manager(st):
2484
+ beat = (st.get("run") or {}).get("beat")
2485
+ print("!! EVENT MANAGER NOT RUNNING"
2486
+ + (f" since {_clock(beat)} ({_dur(now() - beat)} ago)" if beat else "")
2487
+ + " — nothing is watching this run, so it will not move.\n"
2488
+ "!! Run `orch resume` (after a restart it also finds the agents again and re-sends their tasks).")
2274
2489
  print(f"branch={st['branch']} base={st.get('base')} isolation={st['isolation']} "
2275
2490
  f"max_parallel={st['max_parallel']} reviewer={st['reviewer']} (busy: {st.get('reviewer_busy')})")
2276
2491
  if st.get("integration_broken"):
@@ -2296,7 +2511,7 @@ def cmd_status(args):
2296
2511
  + (f"; waiting for `orch dispatch`: {', '.join(hold)}" if hold else "")
2297
2512
  + (f"; wake-up sent {lw['n']}x (last {_fmt_secs(now() - lw.get('ts', now()))} ago), not picked up yet"
2298
2513
  if unread_events(st) and (lw := st.get("lead_wake") or {}).get("n") else "")
2299
- + ("" if driver_alive() else "; the event manager is NOT running (`orch autopilot`)"))
2514
+ + ("" if driver_alive() else "; the event manager is NOT running (`orch resume`)"))
2300
2515
  if all(t["status"] in ("merged", "skipped") for t in st["tasks"].values()):
2301
2516
  print(f"ALL_DONE — run `orch finish` to push {st['branch']} and open a PR into {st.get('base')}")
2302
2517
  elif lead_on(st) and (undispatched(st) or any(event_open(st, e) for e in st["lead_events"])):
@@ -2360,12 +2575,17 @@ def cmd_finish(args):
2360
2575
  cwd=ROOT).stdout.split()
2361
2576
  if st["isolation"] == "worktree":
2362
2577
  remove_worktrees(st)
2578
+ rescued = [r for r in refs if "/rescue-" in r]
2579
+ refs = [r for r in refs if r not in rescued]
2363
2580
  for ref in refs:
2364
2581
  git("update-ref", "-d", ref, cwd=ROOT)
2365
2582
  for tid in st["order"]: # task branches left by orch < 4.5
2366
2583
  if branch_exists(f"{st['branch']}-{tid}"):
2367
2584
  git("branch", "-D", "-q", f"{st['branch']}-{tid}", cwd=ROOT, check=False)
2368
2585
  print(f"CLEAN {st['branch']} is the only branch this run made ({len(refs)} hidden ref(s) removed)")
2586
+ for ref in rescued:
2587
+ print(f"KEPT {ref}: unsaved files orch rescued during the run and no milestone used — look with "
2588
+ f"`git show --stat {ref}`, delete with `git update-ref -d {ref}`")
2369
2589
  if "--no-push" in args:
2370
2590
  print(f"NOT PUSHED (--no-push): push {st['branch']} and open a PR into {base} when ready")
2371
2591
  return
@@ -2696,7 +2916,7 @@ EVENT_HELP = {
2696
2916
  "developer the fix in the event text (usually: rename the reviewer's new pane). Review resumes "
2697
2917
  "by itself once herdr finds the reviewer again.",
2698
2918
  "all_done": "every milestone landed. Finish .orchestrate/summary.md (see `orch lead run`, section ALL_DONE).",
2699
- "stopped": "the event manager stopped. Tell the developer why; they run `orch autopilot` again.",
2919
+ "stopped": "the event manager stopped. Tell the developer why; they run `orch resume` (or `orch autopilot`).",
2700
2920
  }
2701
2921
 
2702
2922
 
@@ -2735,7 +2955,8 @@ def cmd_events(args):
2735
2955
  f"{n} ({w['kind']}" + (f": {w['model']}, {w.get('tier') or 'unrated'}" if w.get("model") else "") + ")"
2736
2956
  + (" free" if n in free else f" on {w['task']}") for n, w in st["workers"].items()))
2737
2957
  print("event manager: " + (driver_line(driver_info()) if driver_alive() else
2738
- "NOT running — your next `orch dispatch` or `orch answer` starts it"))
2958
+ "NOT running — your next `orch dispatch` or `orch answer` starts it"
2959
+ + (" (work is in progress: run `orch resume` now)" if needs_manager(st) else "")))
2739
2960
  if not new and not old and not hold:
2740
2961
  print("Nothing needs you.")
2741
2962
  print("Handle each event above, then STOP: you are woken again when something else happens. Never prompt a "
@@ -3249,6 +3470,14 @@ def cmd_autopilot(args):
3249
3470
  if stale:
3250
3471
  say("A pane id in plan.md is stale. Stopping.\n" + "\n".join(stale), True)
3251
3472
  sys.exit(3)
3473
+ # after a gap (computer off, herdr closed, manager killed): don't count the gap, find the agents again, save
3474
+ # unsaved work and re-send what was in progress. Nothing happens when there was no gap.
3475
+ try:
3476
+ _, rout = run("resume", "--from-manager")
3477
+ if rout:
3478
+ say("back after a gap:\n" + rout, True)
3479
+ except RuntimeError as e:
3480
+ say(f"could not run the restart recovery — carrying on without it\n{e}")
3252
3481
  st = load()
3253
3482
  for name in [n for n in st["workers"] if not watched(st, n)] + (
3254
3483
  [st["reviewer"]] if st.get("reviewer") and not watched(st, st["reviewer"]) else []):
@@ -3276,15 +3505,21 @@ def cmd_autopilot(args):
3276
3505
  + (f", budget {st['budget_s'] // 60} min" if st.get("budget_s") else "")
3277
3506
  + (f"; events go to the lead ({st['lead']['name']})" if lead_on(st) else ""))
3278
3507
  last_tick = time.time()
3508
+ slept = sleep_meter()
3279
3509
  waiting_since = None # set while nothing runs and the run waits for the lead or the developer
3280
3510
 
3281
3511
  while True:
3282
3512
  st = load()
3283
3513
  # 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
3284
3514
  el, last_tick = time.time() - last_tick, time.time()
3515
+ asleep = slept()
3516
+ if asleep: # the computer was suspended: nobody's time, not the budget's either
3517
+ patch_state(lambda s_: account_downtime(s_, asleep))
3518
+ say(f"the computer was asleep for {_dur(asleep)}: that time is not counted against any task")
3519
+ el = max(0, el - asleep)
3285
3520
  if waiting_since:
3286
3521
  el = 0
3287
- patch_state(lambda s_: s_["run"].update(driven_s=round(s_["run"].get("driven_s", 0) + el, 1)))
3522
+ patch_state(lambda s_: s_["run"].update(driven_s=round(s_["run"].get("driven_s", 0) + el, 1), beat=now()))
3288
3523
  st = load()
3289
3524
  if st.get("budget_s") and st["run"].get("driven_s", 0) > st["budget_s"]:
3290
3525
  say(f"STOPPED — the run's budget ({st['budget_s'] // 60} min of autopilot time) is used up. Raise "
@@ -3574,6 +3809,11 @@ def time_account(st, at=None):
3574
3809
  time orch can't place is shown as orch's own steps, and a missing estimate stays missing."""
3575
3810
  at = at or now()
3576
3811
  trans, rows = _transitions(st), []
3812
+ downs = (st.get("run") or {}).get("downs") or []
3813
+
3814
+ def down_in(a, b):
3815
+ """Seconds of [a, b] in which orch was not running (computer off, event manager stopped)."""
3816
+ return sum(max(0, min(b, d["to"]) - max(a, d["from"])) for d in downs)
3577
3817
  for tid in st["order"]:
3578
3818
  t = st["tasks"][tid]
3579
3819
  if t["status"] == "skipped":
@@ -3581,7 +3821,8 @@ def time_account(st, at=None):
3581
3821
  evs = trans.get(tid, [])
3582
3822
  first = next((i for i, e in enumerate(evs) if e.get("to") == "coding"), None)
3583
3823
  row = {"task": tid, "title": t.get("title", ""), "estimate_s": t.get("estimate_s"), "actual_s": None,
3584
- "landed": t["status"] == "merged", "start": None, "end": None, "parts": [], "over_s": None}
3824
+ "landed": t["status"] == "merged", "start": None, "end": None, "parts": [], "over_s": None,
3825
+ "down_s": 0}
3585
3826
  rows.append(row)
3586
3827
  if first is None:
3587
3828
  continue
@@ -3601,7 +3842,7 @@ def time_account(st, at=None):
3601
3842
  a_, b_ = max(evs[i]["ts"], start), min(evs[i + 1]["ts"] if i + 1 < len(evs) else end, end)
3602
3843
  w = _wait_part(st, evs[i].get("to"), evs[i].get("why"), evs[i].get("agent"))
3603
3844
  if w and b_ > a_:
3604
- add(w[0], w[1], b_ - a_, True)
3845
+ add(w[0], w[1], b_ - a_ - down_in(a_, b_), True)
3605
3846
  # working: from the attempts
3606
3847
  esc = next((e["ts"] for e in evs[first:] if (e.get("why") or "").startswith("escalated")), None)
3607
3848
  built = reviewed = False
@@ -3634,10 +3875,11 @@ def time_account(st, at=None):
3634
3875
  again = c.get("where") in seen
3635
3876
  seen.add(c.get("where"))
3636
3877
  add("checks run again after fixes" if again else "checks", "check command", c.get("secs", 0), again)
3637
- total = end - start
3878
+ down = down_in(start, end) # not counted: nobody could work or be watched
3879
+ total = end - start - down
3638
3880
  placed = sum(p["secs"] for p in parts.values())
3639
3881
  add("orch's own steps (setup, prompts, merge)", "orch", max(0, total - placed), False)
3640
- row.update(start=start, end=end, actual_s=total,
3882
+ row.update(start=start, end=end, actual_s=total, down_s=down,
3641
3883
  parts=sorted(parts.values(), key=lambda p: (p["extra"], -p["secs"])))
3642
3884
  if row["estimate_s"]:
3643
3885
  row["over_s"] = total - row["estimate_s"]
@@ -3645,21 +3887,22 @@ def time_account(st, at=None):
3645
3887
  # landed and before a fix asked with `orch fix` is not counted, time with nothing running is
3646
3888
  started = sorted((r for r in rows if r["start"]), key=lambda r: r["start"])
3647
3889
  feat = {"estimate_s": st.get("estimate_s"), "actual_s": None, "over_s": None, "idle_s": 0, "after_done_s": 0,
3648
- "landed": bool(rows) and all(r["landed"] for r in rows), "why": []}
3890
+ "down_s": 0, "landed": bool(rows) and all(r["landed"] for r in rows), "why": []}
3649
3891
  if started:
3650
3892
  fstart = started[0]["start"]
3651
3893
  fend = max(r["end"] for r in started)
3652
3894
  reach, idle, after = started[0]["end"], 0, 0
3653
3895
  for r in started[1:]:
3654
3896
  if r["start"] > reach:
3655
- gap = r["start"] - reach
3897
+ gap = r["start"] - reach - down_in(reach, r["start"])
3656
3898
  if st["tasks"][r["task"]].get("fix_of") and all(x["landed"] and x["end"] <= reach
3657
3899
  for x in started if x["start"] < r["start"]):
3658
3900
  after += gap
3659
3901
  else:
3660
3902
  idle += gap
3661
3903
  reach = max(reach, r["end"])
3662
- feat.update(actual_s=fend - fstart - after, idle_s=idle, after_done_s=after)
3904
+ fdown = down_in(fstart, fend)
3905
+ feat.update(actual_s=fend - fstart - after - fdown, idle_s=idle, after_done_s=after, down_s=fdown)
3663
3906
  if feat["estimate_s"]:
3664
3907
  feat["over_s"] = feat["actual_s"] - feat["estimate_s"]
3665
3908
  agg = {}
@@ -3698,7 +3941,11 @@ def time_lines(acct):
3698
3941
  if est and act is not None:
3699
3942
  head += (f", {_dur(f['over_s'])} longer than estimated" if f["over_s"] > 0 else
3700
3943
  f", {_dur(f['over_s'])} quicker than estimated" if f["over_s"] < 0 else ", on time")
3701
- out += [head, "", "| Milestone | Estimate | Actual | Difference | Built by |", "|---|---|---|---|---|"]
3944
+ out += [head]
3945
+ if f.get("down_s"):
3946
+ out += [f"Not counted: {_dur(f['down_s'])} while orch was not running (computer off, herdr closed or the "
3947
+ f"event manager stopped). No agent is charged for that time."]
3948
+ out += ["", "| Milestone | Estimate | Actual | Difference | Built by |", "|---|---|---|---|---|"]
3702
3949
  for r in acct["tasks"]:
3703
3950
  diff = "-" if r["over_s"] is None else ("on time" if r["over_s"] == 0 else
3704
3951
  f"{'+' if r['over_s'] > 0 else '-'}{_dur(r['over_s'])}")
@@ -3898,6 +4145,9 @@ def team_up(args):
3898
4145
  missing_dirs = [n for n, w, d in agents if n in st["workers"] and not d]
3899
4146
  if missing_dirs:
3900
4147
  die(f"run `orch start` first: it makes each coder's folder ({', '.join(missing_dirs)} have none yet)")
4148
+ # after a restart: panes that only lost their name get it back, and a coder's own pane that came back as a
4149
+ # plain shell gets its agent started again, instead of a second pane next to it
4150
+ empty = {} if dry else rename_lost(dict(st, lead=None), hints=False)
3901
4151
  todo = []
3902
4152
  for name, w, d in agents:
3903
4153
  if w.get("pane"):
@@ -3928,20 +4178,21 @@ def team_up(args):
3928
4178
  print(f"WOULD {name}: {' '.join(shlex.quote(x) for x in split)} then herdr pane run <new pane> "
3929
4179
  f"{shlex.quote(cmd)} then herdr agent rename <new pane> {name}")
3930
4180
  continue
3931
- ok, data, out = _herdr_json(split)
3932
- pid = None
3933
- try:
3934
- pid = data["result"]["pane"]["pane_id"] if ok else None
3935
- except (TypeError, KeyError):
3936
- pid = (re.search(r'"pane_id"\s*:\s*"([\w:.-]+)"', out) or [None, None])[1]
4181
+ pid = empty.get(name)
3937
4182
  if not pid:
3938
- print(f"FAILED {name}: herdr could not open a pane ({out.splitlines()[-1] if out else 'no output'})")
3939
- failed += 1
3940
- continue
3941
- last = pid
4183
+ ok, data, out = _herdr_json(split)
4184
+ try:
4185
+ pid = data["result"]["pane"]["pane_id"] if ok else None
4186
+ except (TypeError, KeyError):
4187
+ pid = (re.search(r'"pane_id"\s*:\s*"([\w:.-]+)"', out) or [None, None])[1]
4188
+ if not pid:
4189
+ print(f"FAILED {name}: herdr could not open a pane ({out.splitlines()[-1] if out else 'no output'})")
4190
+ failed += 1
4191
+ continue
4192
+ last = pid
3942
4193
  ok, _, out = _herdr_json([HERDR, "pane", "run", pid, cmd])
3943
4194
  if not ok:
3944
- print(f"FAILED {name}: pane {pid} opened, but `herdr pane run` failed ({out[-120:]})")
4195
+ print(f"FAILED {name}: pane {pid} is there, but `herdr pane run` failed ({out[-120:]})")
3945
4196
  failed += 1
3946
4197
  continue
3947
4198
  if model and not v.get("model_flag"):
@@ -3972,7 +4223,207 @@ def team_up(args):
3972
4223
  sys.exit(3)
3973
4224
 
3974
4225
 
4226
+ # ---------------------------------------------------------------- resume: carry on after a restart
4227
+ def _dicts_with(obj, key, parent=None):
4228
+ """Every dict (with its parent dict) anywhere in a JSON value that has a string under `key`."""
4229
+ out = []
4230
+ if isinstance(obj, dict):
4231
+ if isinstance(obj.get(key), str):
4232
+ out.append((obj, parent))
4233
+ for v in obj.values():
4234
+ out += _dicts_with(v, key, obj)
4235
+ elif isinstance(obj, list):
4236
+ for v in obj:
4237
+ out += _dicts_with(v, key, parent)
4238
+ return out
4239
+
4240
+
4241
+ def herdr_panes():
4242
+ """{pane id: {"cwds": [...], "kind": str or None}} from `herdr pane list` and `herdr agent list`, or None
4243
+ when herdr can't list panes. Read loosely: any object with a `pane_id`, its `cwd` / `foreground_cwd`, and the
4244
+ agent kind where herdr gives one, so a changed JSON layout still yields the ids and folders."""
4245
+ panes, listed = {}, False
4246
+ for sub in ("pane", "agent"):
4247
+ ok, data, _ = _herdr_json([HERDR, sub, "list"])
4248
+ if not ok or data is None:
4249
+ continue
4250
+ listed = True
4251
+ for d, parent in _dicts_with(data, "pane_id"):
4252
+ p = panes.setdefault(d["pane_id"], {"cwds": [], "kind": None})
4253
+ srcs = [d] + [x for x in (d.get("agent"), parent if sub == "agent" else None) if isinstance(x, dict)]
4254
+ for src in srcs:
4255
+ for k in ("foreground_cwd", "cwd"):
4256
+ if isinstance(src.get(k), str) and src[k] and src[k] not in p["cwds"]:
4257
+ p["cwds"].append(src[k])
4258
+ for k in ("agent_kind", "kind", "agent"):
4259
+ if isinstance(src.get(k), str) and src[k] and not p["kind"]:
4260
+ p["kind"] = src[k].lower()
4261
+ return panes if listed else None
4262
+
4263
+
4264
+ def agent_pane(name):
4265
+ """The pane id herdr reports for a live agent name, or None."""
4266
+ ok, data, _ = _herdr_json([HERDR, "agent", "get", name])
4267
+ return _find_key(data, "pane_id") if ok and data is not None else None
4268
+
4269
+
4270
+ def _inside(path, folder):
4271
+ a, b = os.path.realpath(path), os.path.realpath(folder)
4272
+ return a == b or a.startswith(b.rstrip("/") + "/")
4273
+
4274
+
4275
+ def rename_lost(st, hints=True):
4276
+ """herdr brings panes back after a restart, but not the agents' names, and orch reaches agents by name. For
4277
+ every agent in the plan that herdr can't find, look for its pane by folder and give the name back. A coder's
4278
+ worktree is its own folder, so one pane there is its pane. The reviewer and the lead sit in the main folder,
4279
+ next to the developer's own panes, so there the pane must also show the agent's kind. Where that can't be
4280
+ decided, print the exact command (hints=False: only say what was named).
4281
+ Returns {name: pane id or None} for the agents still not found; a pane id means "its pane is there (a
4282
+ coder's own folder), but no agent runs in it"."""
4283
+ plan = [(n, w, w.get("dir") or str(ROOT), st["isolation"] == "worktree" and bool(w.get("dir")))
4284
+ for n, w in st["workers"].items()]
4285
+ if st.get("reviewer"):
4286
+ plan.append((st["reviewer"], st.get("reviewer_info") or {}, str(ROOT), False))
4287
+ if st.get("lead"):
4288
+ plan.append((st["lead"]["name"], st["lead"], str(ROOT), False))
4289
+ plan = [x for x in plan if not x[1].get("pane") and x[1].get("detect", True)]
4290
+ lost = [x for x in plan if herdr_state(x[0]) is None]
4291
+ if not lost:
4292
+ return {}
4293
+ say = print if hints else (lambda *_: None)
4294
+ panes = herdr_panes()
4295
+ if panes is None:
4296
+ for n, _, d, _ in lost:
4297
+ say(f"LOST {n}: herdr has no agent with this name, and `herdr pane list` did not answer (is herdr "
4298
+ f"open?). Find its pane with `herdr agent list` (folder {short(d)}), then: herdr agent rename <pane> {n}")
4299
+ return {x[0]: None for x in lost}
4300
+ found = {x[0] for x in plan} - {x[0] for x in lost}
4301
+ taken = {agent_pane(n) for n in found} - {None}
4302
+ reg = registry(required=False) or {}
4303
+ still, pending, progress, cands = {}, list(lost), True, {}
4304
+ while pending and progress: # a pane given to one agent can settle who gets another
4305
+ progress = False
4306
+ for item in list(pending):
4307
+ n, w, d, own = item
4308
+ kind = (w.get("kind") or "").lower()
4309
+ here = [pid for pid, p in panes.items() if pid not in taken and any(_inside(x, d) for x in p["cwds"])]
4310
+ same = [pid for pid in here if kind and panes[pid]["kind"]
4311
+ and (kind in panes[pid]["kind"] or panes[pid]["kind"] in kind)]
4312
+ cands[n] = here
4313
+ pick = here[0] if own and len(here) == 1 else same[0] if len(same) == 1 else None
4314
+ if not pick:
4315
+ continue
4316
+ pending.remove(item)
4317
+ taken.add(pick)
4318
+ progress = True
4319
+ ok, _, _ = _herdr_json([HERDR, "agent", "rename", pick, n])
4320
+ if ok:
4321
+ print(f"NAMED {n}: pane {pick} (in {short(d)}) has its name back")
4322
+ continue
4323
+ still[n] = pick if own else None
4324
+ v = reg.get(w.get("kind"))
4325
+ cmd = launch_cmd(w.get("kind"), v, w.get("model"), strict=False) if v else (w.get("kind") or "<its agent>")
4326
+ say(f"LOST {n}: pane {pick} is in its folder ({short(d)}), but herdr sees no agent running in it. "
4327
+ + (f"`orch team up` starts it there; or start it yourself (`{cmd}`)" if own else
4328
+ f"Start it there (`{cmd}`)") + f", then: herdr agent rename {pick} {n}")
4329
+ for n, w, d, own in pending:
4330
+ still[n] = None
4331
+ if cands.get(n):
4332
+ say(f"LOST {n}: can't tell which pane is {n} ({', '.join(cands[n])} "
4333
+ f"{'is' if len(cands[n]) == 1 else 'are'} in {short(d)}). Look, then: herdr agent rename <pane> {n}")
4334
+ else:
4335
+ say(f"LOST {n}: no pane is left in its folder ({short(d)}). `orch team up` opens one, or start it "
4336
+ f"yourself there and: herdr agent rename <pane> {n}")
4337
+ return still
4338
+
4339
+
4340
+ RESUME_CODER = ("orch was restarted (the computer or herdr was off), so here is your task again. The changes you "
4341
+ "made before are still in this folder: look at them first (`git status`, `git diff`), keep what is "
4342
+ "right and carry on from there. Do not start over. ")
4343
+ RESUME_REVIEWER = "orch was restarted (the computer or herdr was off), so here is your review task again. "
4344
+
4345
+
4346
+ def cmd_resume(args):
4347
+ """orch resume -> carry on after a restart (the computer was off, herdr was closed, the event manager died).
4348
+ 1. says how long orch was down, and does not count that time against any task;
4349
+ 2. gives the agents' panes their names back (found by folder), or prints the exact rename command;
4350
+ 3. saves unsaved files left in the coders' folders;
4351
+ 4. sends each task that was in progress to its agent again (a fresh conversation carries on from the files);
4352
+ 5. starts the event manager, which wakes the lead if events wait for it.
4353
+ Safe to run at any time and more than once. Exit 3: an agent with work in progress is still not found.
4354
+ (`--from-manager`: the event manager's own call when it starts; it does 1-4 only after a real gap.)"""
4355
+ from_manager = "--from-manager" in args
4356
+ waiting = []
4357
+ with state_lock():
4358
+ st = load()
4359
+ info = driver_info()
4360
+ mine = from_manager and bool(os.environ.get("ORCH_DRIVER")) and os.environ.get("ORCH_DRIVER") == info.get("token")
4361
+ if driver_alive() and not mine:
4362
+ print(f"The event manager is running ({driver_line(info)}), so the run is being watched.")
4363
+ if rename_lost(st):
4364
+ print("Fix the agents above; the event manager carries on by itself once herdr finds them.")
4365
+ else:
4366
+ print("Every agent in the plan is found. Nothing to resume.")
4367
+ return
4368
+ beat = st["run"].get("beat")
4369
+ busy = [(tid, st["tasks"][tid]["wait"]) for tid in st["order"] if st["tasks"][tid].get("wait")]
4370
+ gap = account_downtime(st)
4371
+ save(st)
4372
+ if from_manager and not gap:
4373
+ return
4374
+ if gap and (busy or not from_manager):
4375
+ print(f"DOWN orch was not running from {_clock(beat)} to {_clock(now())} ({_dur(gap)}). That time is "
4376
+ f"not counted against any task or agent.")
4377
+ elif not from_manager:
4378
+ print("RESUME the event manager is not running" + (f" (last seen {_clock(beat)})" if beat else "") + ".")
4379
+ for tid, w in busy:
4380
+ print(f"WAS {tid} \"{st['tasks'][tid]['title']}\": {w['agent']} was "
4381
+ + ("reviewing it" if w.get("kind") == "reviewer" else "working on it"))
4382
+ rename_lost(st)
4383
+ for name, w in st["workers"].items():
4384
+ saved = save_stray(st, name)
4385
+ if saved:
4386
+ print(saved)
4387
+ for tid, w in busy:
4388
+ agent = w["agent"]
4389
+ if any(w.get(k) and Path(w[k]).exists() for k in ("sentinel", "report", "result")):
4390
+ print(f"DONE {tid}: {agent} had finished; the event manager takes it from here")
4391
+ continue
4392
+ if watched(st, agent):
4393
+ hs = herdr_state(agent)
4394
+ if hs is None:
4395
+ waiting.append((tid, agent))
4396
+ print(f"NOT SENT {tid}: {agent} is not found in herdr (see above)")
4397
+ continue
4398
+ if word(hs, "working", "blocked"):
4399
+ print(f"OK {tid}: {agent} is already "
4400
+ + ("at a question in its pane" if word(hs, "blocked") else "working"))
4401
+ continue
4402
+ w["delivering"], w["since"] = True, now() # recorded first, like every send: confirmed or sent again
4403
+ save(st)
4404
+ try:
4405
+ deliver(st, agent, (RESUME_REVIEWER if w.get("kind") == "reviewer" else RESUME_CODER) + w["prompt"])
4406
+ except DeliveryError as e:
4407
+ print(f"NOT SENT {tid} -> {agent}: {e} — the event manager sends it again")
4408
+ continue
4409
+ _delivered(st, agent)
4410
+ w["delivering"] = False
4411
+ save(st)
4412
+ print(f"RESENT {tid} -> {agent}: it carries on from the files in its folder")
4413
+ if from_manager:
4414
+ return
4415
+ if waiting:
4416
+ print("NOT STARTED: " + ", ".join(f"{a} ({t})" for t, a in waiting) + " must be running first. Do what the "
4417
+ "LOST lines say, then run `orch resume` again. (To go on without them, run `orch autopilot`: their "
4418
+ "milestones then move to another coder with the work so far.)")
4419
+ sys.exit(3)
4420
+ print(start_manager())
4421
+ if lead_on(st):
4422
+ print("The lead is woken with `orch events` when something needs it.")
4423
+
4424
+
3975
4425
  COMMANDS = {
4426
+ "resume": cmd_resume,
3976
4427
  "sync": cmd_sync, "start": cmd_start, "ready": cmd_ready, "pick": cmd_pick, "prepare": cmd_prepare,
3977
4428
  "setup-done": cmd_setup_done, "send": cmd_send, "review": cmd_review, "poll": cmd_poll, "bump": cmd_bump,
3978
4429
  "commit": cmd_commit, "merge": cmd_merge, "park": cmd_park, "cooldown": cmd_cooldown, "set": cmd_set,
@@ -3984,7 +4435,7 @@ COMMANDS = {
3984
4435
  "escalate": cmd_escalate, "fix": cmd_fix, "team": cmd_team,
3985
4436
  }
3986
4437
  # they lock per step instead of for the whole command (long-running, or they start the event manager after)
3987
- UNLOCKED = {"autopilot", "poll", "events", "dispatch", "answer", "fix", "team"}
4438
+ UNLOCKED = {"autopilot", "poll", "events", "dispatch", "answer", "fix", "team", "resume"}
3988
4439
 
3989
4440
  USAGE = """usage: orch <command> [args]
3990
4441
  version print the installed herdr-orchestra version
@@ -3998,13 +4449,16 @@ USAGE = """usage: orch <command> [args]
3998
4449
  agents launch <kind> [--model <id>] print the command that starts <kind> in a pane (auto-approve edits)
3999
4450
  models the model catalog: tiers (small / medium / high), ratings, and what policy forbids
4000
4451
  models show|check <id> one model's ratings and evidence / is it allowed?
4452
+ resume after a restart (computer off, herdr closed): name the agents' panes again, save unsaved
4453
+ work, re-send the tasks that were in progress and start the event manager
4001
4454
  events [--peek] (lead) what you were woken for; reading acknowledges it
4002
4455
  dispatch <Mn>... [--to <worker>] [--tier <tier>] (lead) start or restart milestones; starts the event manager
4003
4456
  answer <Mn> <text> (lead) the developer's answer: into plan.md, and back to the same coder
4004
4457
  fix <Mn> <text> [--to <worker>] a change to something Mn already landed: a small follow-up milestone, sent
4005
4458
  straight to the coder who built Mn (no new plan; check, review and summary still apply)
4006
- agents sync [kind...] install the orch-plan / orch-run skills for every installed agent (run it after adding a new agent)
4007
- agents check check the orch-plan / orch-run skills are installed for every installed agent
4459
+ agents sync [kind...] install the orch-plan / orch-run skills so every installed agent sees each one exactly once,
4460
+ and remove old copies (run it after adding a new agent; the installer runs it)
4461
+ agents check check every installed agent sees each orch skill once (not missing, not twice)
4008
4462
  doctor [kind...] check installed agents against the real tool: version, launch flags, skills, herdr
4009
4463
  sync parse .orchestrate/plan.md -> state.json (validates deps, cycles, overlaps)
4010
4464
  start create/switch to the feature branch (plan `Branch:`); create worker worktrees (worktree mode)
@@ -4040,7 +4494,7 @@ USAGE = """usage: orch <command> [args]
4040
4494
  Exit codes: 2 error · 3 needs you / busy / cap · 4 merge conflict · 5 prompt not delivered (retried later) ·
4041
4495
  6 check fails on the feature branch (nothing committed) · 7 held for approval · 10 poll wait
4042
4496
  While `orch autopilot` runs it holds the driver lease: other commands that change the run are refused
4043
- (status, ready, pick, report, approve, fix and the lead's events / dispatch / answer still work).
4497
+ (status, ready, pick, report, approve, fix, resume and the lead's events / dispatch / answer still work).
4044
4498
  """
4045
4499
 
4046
4500
  # Env vars a Herdr pane carries. Agents whose tools run in a separate background process (Hermes runs
@@ -4119,15 +4573,25 @@ def short(p):
4119
4573
  return "~" + p[len(home):] if p.startswith(home) else p
4120
4574
 
4121
4575
 
4122
- def manifest_record(*paths):
4123
- """Append paths to the installer's manifest so `install.sh --uninstall` removes them."""
4576
+ def manifest_lines():
4577
+ mf = manifest_path()
4578
+ return mf.read_text().splitlines() if mf.exists() else []
4579
+
4580
+
4581
+ def manifest_write(lines):
4124
4582
  mf = manifest_path()
4125
4583
  mf.parent.mkdir(parents=True, exist_ok=True)
4126
- lines = mf.read_text().splitlines() if mf.exists() else []
4127
- for p in paths:
4128
- if str(p) not in lines:
4129
- lines.append(str(p))
4130
- mf.write_text("".join(line + "\n" for line in lines))
4584
+ seen, out = set(), []
4585
+ for line in lines:
4586
+ if line and line not in seen:
4587
+ seen.add(line)
4588
+ out.append(line)
4589
+ mf.write_text("".join(line + "\n" for line in out))
4590
+
4591
+
4592
+ def manifest_record(*paths):
4593
+ """Append paths to the installer's manifest so `install.sh --uninstall` removes them."""
4594
+ manifest_write(manifest_lines() + [str(p) for p in paths])
4131
4595
 
4132
4596
 
4133
4597
  def _copy_asset(src, dst):
@@ -4139,74 +4603,214 @@ def _copy_asset(src, dst):
4139
4603
  return True
4140
4604
 
4141
4605
 
4142
- def sync_skills(d):
4143
- """Copy orch-plan / orch-run into <d>/<skill>/SKILL.md. Returns (changed, paths to record)."""
4606
+ SHARED_SKILLS = "~/.agents/skills" # read by several tools; used when it doesn't make a second copy
4607
+ SHARED_COMMANDS = ("~/.config/opencode/commands", "opencode-commands") # written even before OpenCode is installed
4608
+
4609
+
4610
+ def shipped_skills():
4144
4611
  src = asset("skills") or die("skills/ not found next to orch or in the install")
4145
- changed, recs = False, []
4146
- for s in ("orch-plan", "orch-run"):
4147
- changed |= _copy_asset(src / s / "SKILL.md", d / s / "SKILL.md")
4148
- recs.append(d / s)
4149
- return changed, recs
4612
+ return sorted(p.name for p in src.iterdir() if (p / "SKILL.md").exists() and p.name.startswith("orch-"))
4150
4613
 
4151
4614
 
4152
- def sync_commands(d, flavor):
4153
- """Copy the orch-*.md slash commands into d. Returns (changed, paths to record)."""
4615
+ def shipped_commands(flavor):
4154
4616
  src = asset(flavor)
4155
- if not src:
4156
- return False, []
4157
- changed, recs = False, []
4158
- for f in sorted(src.glob("orch-*.md")):
4159
- changed |= _copy_asset(f, d / f.name)
4160
- recs.append(d / f.name)
4161
- return changed, recs
4617
+ return sorted(f.name for f in src.glob("orch-*.md")) if src else []
4162
4618
 
4163
4619
 
4164
- def agent_assets(v):
4165
- """[(path, installed?)] for every skill/slash-command the registry says an agent should have."""
4166
- out = []
4167
- for d in v.get("skills_dirs", []):
4168
- for s in ("orch-plan", "orch-run"):
4169
- p = expand(d) / s / "SKILL.md"
4170
- out.append((p, p.exists()))
4171
- for d in v.get("commands_dirs", []):
4172
- for s in ("orch-plan", "orch-run"):
4173
- p = expand(d) / f"{s}.md"
4174
- out.append((p, p.exists()))
4620
+ def _dirs(v, key):
4621
+ return [expand(d) for d in v.get(key, []) or []]
4622
+
4623
+
4624
+ def _same(d):
4625
+ """A folder's identity: two paths that are one folder (a symlinked skills folder) count once."""
4626
+ return os.path.realpath(d)
4627
+
4628
+
4629
+ def agent_reads(v, what):
4630
+ """Every global folder the tool reads skills (or slash commands) from: `skills_reads` / `commands_reads`
4631
+ plus the folders the registry installs into. Order kept, no repeats (a symlink to a listed folder is the
4632
+ same folder)."""
4633
+ out, seen = [], set()
4634
+ for d in _dirs(v, f"{what}_reads") + _dirs(v, f"{what}_dirs"):
4635
+ if _same(d) not in seen:
4636
+ seen.add(_same(d))
4637
+ out.append(d)
4175
4638
  return out
4176
4639
 
4177
4640
 
4178
- def agents_sync(reg, installed, want=None):
4179
- """Copy the orch skills/commands into the shared dirs + every installed agent's folders.
4180
- Idempotent; records each written path in the uninstall manifest. Prints a status table."""
4181
- home = expand("~")
4182
- targets = [("base", [("skills", home / ".agents/skills", None)] +
4183
- [("commands", d, "opencode-commands")
4184
- for d in (home / ".config/opencode/commands", home / ".config/opencode/command")], "")]
4641
+ def pick_dirs(agents, shared=None):
4642
+ """agents: [(kind, reads, candidates, one_wins)]. Pick the fewest folders to write so every agent reads exactly
4643
+ one copy (an agent with one_wins shows a skill once even when two folders have it, so two copies are fine).
4644
+ Returns (chosen folders, {kind: [folders it reads a copy from]}). Prefers the shared folder, then the folders
4645
+ each agent lists first. When no exact choice exists, the fewest agents with two copies."""
4646
+ import itertools
4647
+ pool = []
4648
+ for _, reads, cands, _ in agents:
4649
+ for d in cands:
4650
+ if _same(d) not in {_same(p) for p in pool}:
4651
+ pool.append(d)
4652
+ if shared is not None and _same(shared) not in {_same(p) for p in pool}:
4653
+ pool.append(shared)
4654
+ if not agents:
4655
+ return ([shared] if shared is not None else []), {}
4656
+
4657
+ def rank(d):
4658
+ return min((c.index(d) for _, _, c, _ in agents if d in c), default=9)
4659
+
4660
+ best = None
4661
+ for n in range(1, len(pool) + 1):
4662
+ for combo in itertools.combinations(pool, n):
4663
+ s = {_same(d) for d in combo}
4664
+ seen = [(len(s & {_same(d) for d in reads}), ow) for _, reads, _, ow in agents]
4665
+ cost = (sum(c == 0 for c, _ in seen), sum(c > 1 and not ow for c, ow in seen), n,
4666
+ 0 if shared is not None and _same(shared) in s else 1, sum(rank(d) for d in combo))
4667
+ if best is None or cost < best[0]:
4668
+ best = (cost, combo)
4669
+ if best and best[0][:2] == (0, 0):
4670
+ break # bigger sets only cost more
4671
+ chosen = list(best[1])
4672
+ ids = {_same(d) for d in chosen}
4673
+ return chosen, {k: [d for d in reads if _same(d) in ids] for k, reads, _, _ in agents}
4674
+
4675
+
4676
+ def _ours(p):
4677
+ """Is this skill folder / command file one of orch's thin wrappers (so safe to remove)?"""
4678
+ f = p / "SKILL.md" if p.is_dir() else p
4679
+ try:
4680
+ text = f.read_text(errors="replace") if f.is_file() else ""
4681
+ except OSError:
4682
+ return False
4683
+ # every version's skills and commands: thin wrappers say "orch lead", the first (4.0) skills "Orchestrator step"
4684
+ return "orch lead" in text or "Orchestrator step" in text
4685
+
4686
+
4687
+ def _remove(p):
4688
+ if p.is_dir() and not p.is_symlink():
4689
+ shutil.rmtree(p)
4690
+ else:
4691
+ p.unlink()
4692
+
4693
+
4694
+ def sync_plan(reg, installed):
4695
+ """What `orch agents sync` writes: {(kind of item, folder): flavor}, plus the per-agent view."""
4696
+ agents = [(k, agent_reads(v, "skills"), _dirs(v, "skills_dirs") or agent_reads(v, "skills"),
4697
+ bool(v.get("skills_one_wins")))
4698
+ for k, v in reg.items() if installed[k]]
4699
+ agents = [a for a in agents if a[1]]
4700
+ sdirs, sview = pick_dirs(agents, expand(SHARED_SKILLS))
4701
+ flavor, cagents = {}, []
4185
4702
  for k, v in reg.items():
4186
- if want is not None and k not in want:
4703
+ if not installed[k] or not agent_reads(v, "commands"):
4187
4704
  continue
4188
- if not installed[k]:
4189
- if want is not None:
4705
+ cands = _dirs(v, "commands_dirs") or agent_reads(v, "commands")
4706
+ for d in cands:
4707
+ flavor.setdefault(d, v.get("commands_from", "claude-commands"))
4708
+ cagents.append((k, agent_reads(v, "commands"), cands, False))
4709
+ shared = expand(SHARED_COMMANDS[0])
4710
+ flavor.setdefault(shared, SHARED_COMMANDS[1])
4711
+ cdirs, cview = pick_dirs(cagents, shared)
4712
+ return sdirs, sview, [(d, flavor[d]) for d in cdirs], cview
4713
+
4714
+
4715
+ def agents_sync(reg, installed, want=None):
4716
+ """Copy the orch skills/commands so that every installed agent reads exactly one copy, and remove orch's
4717
+ copies from every other folder (old folders, renamed or dropped skills). Idempotent; keeps the uninstall
4718
+ manifest in step. Prints a status table."""
4719
+ if want is not None:
4720
+ for k in sorted(want):
4721
+ if not installed.get(k):
4190
4722
  print(f"skip {k:<9} not installed")
4723
+ was_ok = {k: all(st == "ok" for _, st in agent_assets(v)) for k, v in reg.items() if installed[k]}
4724
+ sdirs, sview, cdirs, cview = sync_plan(reg, installed)
4725
+ skills = shipped_skills()
4726
+ keep, changed_dirs = set(), set()
4727
+ for d in sdirs:
4728
+ src = asset("skills")
4729
+ for s in skills:
4730
+ if _copy_asset(src / s / "SKILL.md", d / s / "SKILL.md"):
4731
+ changed_dirs.add(d)
4732
+ keep.add(d / s)
4733
+ for d, fl in cdirs:
4734
+ src = asset(fl)
4735
+ for name in shipped_commands(fl):
4736
+ if _copy_asset(src / name, d / name):
4737
+ changed_dirs.add(d)
4738
+ keep.add(d / name)
4739
+
4740
+ # Remove the copies that make a tool list a skill twice: orch's copies in any folder an installed agent
4741
+ # reads (or used to read: old_dirs) that is not a chosen one, and skills orch no longer ships (renamed or
4742
+ # dropped) wherever an earlier install put them. A copy in a folder no installed agent reads is left: it
4743
+ # shows up nowhere, and it may belong to an agent that is only missing from PATH right now.
4744
+ removed = []
4745
+ lines = manifest_lines()
4746
+ keep_ids = {_same(p) for p in keep}
4747
+ read_ids = {_same(d) for k, v in reg.items() if installed[k]
4748
+ for d in agent_reads(v, "skills") + agent_reads(v, "commands") + _dirs(v, "old_dirs")}
4749
+ current = set(skills) | {n for fl in ("claude-commands", "opencode-commands") for n in shipped_commands(fl)}
4750
+ candidates = [Path(p) for p in lines if Path(p).name.startswith("orch-")]
4751
+ for k, v in reg.items():
4752
+ if installed[k]:
4753
+ for d in agent_reads(v, "skills") + agent_reads(v, "commands") + _dirs(v, "old_dirs"):
4754
+ if d.is_dir():
4755
+ candidates += [p for p in sorted(d.iterdir()) if p.name.startswith("orch-")]
4756
+ for p in candidates:
4757
+ if not (p.exists() or p.is_symlink()) or _same(p) in keep_ids or p in removed:
4758
+ continue
4759
+ if not (str(p) in lines or _ours(p)):
4760
+ continue # the developer's own orch-... skill
4761
+ if p.name in current and _same(p.parent) not in read_ids:
4191
4762
  continue
4192
- items = [("skills", expand(d), None) for d in v.get("skills_dirs", [])]
4193
- items += [("commands", expand(d), v.get("commands_from", "claude-commands"))
4194
- for d in v.get("commands_dirs", [])]
4195
- targets.append((k, items, v.get("invoke", "Run `orch lead plan` and follow it. Feature: <feature>")))
4763
+ _remove(p)
4764
+ removed.append(p)
4765
+ manifest_write([p for p in lines if Path(p) not in removed] + [str(p) for p in sorted(keep)])
4766
+
4196
4767
  new = same = 0
4197
- for k, items, invoke in targets:
4198
- changed, recs = False, []
4199
- for what, d, flavor in items:
4200
- c, r = sync_skills(d) if what == "skills" else sync_commands(d, flavor)
4201
- changed, recs = changed or c, recs + r
4202
- manifest_record(*recs)
4768
+ for k, v in reg.items():
4769
+ if not installed[k] or (want is not None and k not in want):
4770
+ continue
4771
+ mine = sview.get(k, []) + [d for d in cview.get(k, [])]
4772
+ changed = not was_ok[k] or any(d in changed_dirs for d in mine)
4203
4773
  new += changed
4204
4774
  same += not changed
4205
- status, whats = ("NEW" if changed else "ok "), " ".join(
4206
- f"{what}: {short(d)}" for what, d, _ in items)
4207
- print(f" {status} {k:<8} {whats}" + (f" {invoke}" if invoke else ""))
4208
- print(f"synced {len(targets)} row(s): {new} new, {same} unchanged — "
4209
- f"restart running agents so they pick up the skills")
4775
+ parts = []
4776
+ if k in sview:
4777
+ parts.append("skills: " + (", ".join(short(d) for d in sview[k]) or "NONE"))
4778
+ if k in cview:
4779
+ parts.append("commands: " + (", ".join(short(d) for d in cview[k]) or "NONE"))
4780
+ dup = len(cview.get(k, [])) > 1 or (len(sview.get(k, [])) > 1 and not v.get("skills_one_wins"))
4781
+ status = "DUP " if dup else ("NEW " if changed else "ok ")
4782
+ print(f" {status} {k:<8} {' '.join(parts)} {v.get('invoke', 'Run `orch lead plan` and follow it. Feature: <feature>')}")
4783
+ for d, what, view in ((expand(SHARED_SKILLS), "skills", sview), (expand(SHARED_COMMANDS[0]), "commands", cview)):
4784
+ if d in (sdirs if what == "skills" else [c for c, _ in cdirs]) and not any(d in x for x in view.values()):
4785
+ print(f" {'NEW ' if d in changed_dirs else 'ok '} {'shared':<8} {what}: {short(d)}")
4786
+ for p in removed:
4787
+ print(f" removed old copy {short(p)}")
4788
+ print(f"synced {new + same} agent(s): {new} new, {same} unchanged, {len(removed)} old cop"
4789
+ f"{'y' if len(removed) == 1 else 'ies'} removed — every agent sees each skill once. "
4790
+ f"Restart running agents so they pick up the skills")
4791
+
4792
+
4793
+ def agent_assets(v):
4794
+ """[(text, state)] per skill / slash command an installed agent should see once: state is ok, missing or
4795
+ duplicate (the same skill in two folders the tool reads, so it is listed twice)."""
4796
+ out = []
4797
+ reads = agent_reads(v, "skills")
4798
+ for s in shipped_skills() if reads else []:
4799
+ copies = [d for d in reads if (d / s / "SKILL.md").exists()]
4800
+ out.append(_asset_state(f"skill {s}", copies[:1] if v.get("skills_one_wins") else copies, reads))
4801
+ reads = agent_reads(v, "commands")
4802
+ for name in shipped_commands(v.get("commands_from", "claude-commands")) if reads else []:
4803
+ copies = [d for d in reads if (d / name).exists()]
4804
+ out.append(_asset_state(f"command {name}", copies, reads))
4805
+ return out
4806
+
4807
+
4808
+ def _asset_state(label, copies, reads):
4809
+ if not copies:
4810
+ return f"{label} not in {', '.join(short(d) for d in reads)}", "missing"
4811
+ if len(copies) > 1:
4812
+ return f"{label} twice: {' and '.join(short(d) for d in copies)}", "duplicate"
4813
+ return f"{label} {short(copies[0])}", "ok"
4210
4814
 
4211
4815
 
4212
4816
  def cmd_agents(args):
@@ -4226,27 +4830,25 @@ def cmd_agents(args):
4226
4830
  f"(add it in {user_agents_file()})")
4227
4831
  print(launch_cmd(kind, v, model))
4228
4832
  return
4229
- if sub == "dirs": # for install.sh: <kind>\t<skills|commands|invoke>\t<dir or text>[\t<commands_from>]
4230
- for k, v in reg.items():
4231
- if not installed[k]:
4232
- continue
4233
- print(f"{k}\tinvoke\t{v.get('invoke', 'Run `orch lead plan` and follow it. Feature: <feature>')}")
4234
- for d in v.get("skills_dirs", []):
4235
- print(f"{k}\tskills\t{expand(d)}")
4236
- for d in v.get("commands_dirs", []):
4237
- print(f"{k}\tcommands\t{expand(d)}\t{v.get('commands_from', 'claude-commands')}")
4833
+ if sub == "dirs": # the folders `orch agents sync` writes: <skills|commands>\t<dir>[\t<commands_from>]
4834
+ sdirs, _, cdirs, _ = sync_plan(reg, installed)
4835
+ for d in sdirs:
4836
+ print(f"skills\t{d}")
4837
+ for d, fl in cdirs:
4838
+ print(f"commands\t{d}\t{fl}")
4238
4839
  return
4239
4840
  if sub == "check":
4240
- bad = 0
4841
+ bad = {"missing": 0, "duplicate": 0}
4241
4842
  for k, v in reg.items():
4242
4843
  if not installed[k]:
4243
4844
  continue
4244
- for p, ok in agent_assets(v):
4245
- bad += not ok
4246
- label = "skill " if p.name == "SKILL.md" else "command "
4247
- print(f"{'ok ' if ok else 'MISSING'} {k:<9} {label}{p}")
4248
- if bad:
4249
- print(f"{bad} missing — run: orch agents sync")
4845
+ for text, state in agent_assets(v):
4846
+ if state != "ok":
4847
+ bad[state] += 1
4848
+ print(f"{ {'ok': 'ok ', 'missing': 'MISSING ', 'duplicate': 'DUPLICATE'}[state]} {k:<9} {text}")
4849
+ if bad["missing"] or bad["duplicate"]:
4850
+ print(", ".join(f"{n} {w}" for w, n in bad.items() if n) + " — run: orch agents sync"
4851
+ + (" (a duplicate means the tool lists that skill twice)" if bad["duplicate"] else ""))
4250
4852
  sys.exit(1)
4251
4853
  return
4252
4854
  if sub == "sync":
@@ -4266,9 +4868,9 @@ def cmd_agents(args):
4266
4868
  f"{'yes' if v.get('verified') else 'no':<8} {','.join(v.get('roles', [])):<22} "
4267
4869
  f"{v.get('launch', v.get('binary', k))}")
4268
4870
  missing = [k for k, v in reg.items()
4269
- if installed[k] and any(not ok for _, ok in agent_assets(v))]
4871
+ if installed[k] and any(st != "ok" for _, st in agent_assets(v))]
4270
4872
  if missing:
4271
- print(f"\n{', '.join(missing)}: orch-plan/orch-run missing — run: orch agents sync")
4873
+ print(f"\n{', '.join(missing)}: orch-plan/orch-run missing or listed twice — run: orch agents sync")
4272
4874
  print(f"\nOverride or add kinds in {user_agents_file()}")
4273
4875
 
4274
4876
 
@@ -4308,8 +4910,9 @@ def doctor_kind(kind, v, full=True):
4308
4910
  out.append((False, f"launch flag {fl} is NOT in `{hcmd}` — the launch command in the registry may be out "
4309
4911
  f"of date (override it in {short(user_agents_file())})"))
4310
4912
  if full:
4311
- for p, ok in agent_assets(v):
4312
- out.append((ok, f"skill {short(p)}" + ("" if ok else " missing — run `orch agents sync`")))
4913
+ for text, st in agent_assets(v):
4914
+ out.append((st == "ok", " ".join(text.split()) + ("" if st == "ok" else
4915
+ f" ({st}) — run `orch agents sync`")))
4313
4916
  if v.get("herdr_detect", True):
4314
4917
  code, txt = _probe([HERDR, "agent"])
4315
4918
  if code == 0: