herdr-orchestra 5.4.0 → 5.6.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
@@ -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")
@@ -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
@@ -58,11 +59,18 @@ RISK_RULES = [
58
59
  (re.compile(r"(^|/)\.env(\.(?!example$|sample$|template$)[^/]+)?$|(^|/)[^/]*\.(pem|key|p12)$", re.I),
59
60
  "secrets or environment file"),
60
61
  ]
62
+ # quick runs (`Mode: quick`): small, clear changes only. Files that always need the full process...
63
+ QUICK_NEVER = RISK_RULES + [(LOCKFILE_RE, "dependency file")]
64
+ # ...and names that usually mean auth or payment code: the lead should be sure before calling it quick
65
+ QUICK_CAREFUL_RE = re.compile(r"auth|login|logout|password|session|token|oauth|permission|rbac|acl|payment|billing|"
66
+ r"invoice|checkout|stripe|paypal|razorpay|subscription|schema\.(prisma|sql|rb)|models?\.py$",
67
+ re.I)
61
68
  RISK_MAX_LINES = int(os.environ.get("ORCH_RISK_MAX_LINES", "1500"))
62
69
  CHECK_TIMEOUT_S = int(os.environ.get("ORCH_CHECK_TIMEOUT_MIN", "30")) * 60
63
70
  ACTIVE = {"coding", "verifying", "awaiting-review", "reviewing", "reviewed", "committed", "conflict", "needs-fix",
64
71
  "held"}
65
72
  TERMINAL_OK = {"merged"}
73
+ RESTING = {"pending", "paused", "failed", "needs-fix", "conflict"} # no agent on it; a coder takes it up again later
66
74
 
67
75
 
68
76
  # ---------------------------------------------------------------- helpers
@@ -150,7 +158,7 @@ def state_lock():
150
158
 
151
159
  # usable while autopilot drives: reads, and the lead's requests (the event manager carries them out)
152
160
  LEASE_FREE = {"status", "ready", "pick", "report", "approve", "autopilot", "events", "dispatch", "answer", "fix",
153
- "team"}
161
+ "team", "resume"}
154
162
  _LEASE = None
155
163
 
156
164
 
@@ -707,7 +715,12 @@ def cmd_sync(args):
707
715
  if commits not in ("per-milestone", "single"):
708
716
  errors.append(f"Commits must be per-milestone or single, got {commits!r}")
709
717
  title_m = re.search(r"(?m)^# Plan:\s*(.+?)\s*$", plan_text)
710
- isolation = get("isolation", "worktree").split()[0].lower()
718
+ mode = (get("mode", "full").split() or ["full"])[0].lower()
719
+ if mode not in ("quick", "full"):
720
+ errors.append(f"Mode must be quick or full, got {mode!r}")
721
+ quick = mode == "quick"
722
+ quick_because = get("quick because")
723
+ isolation = get("isolation", "shared" if quick else "worktree").split()[0].lower()
711
724
  if isolation not in ("worktree", "shared"):
712
725
  errors.append(f"Isolation must be worktree or shared, got {isolation!r}")
713
726
  try:
@@ -928,6 +941,28 @@ def cmd_sync(args):
928
941
  if not field(by_id[tid], "why separate"):
929
942
  warns.append(f"{tid} has no `Why separate:` — say why it is its own milestone (parallel work, a "
930
943
  f"foundation others build on, too big for one sitting), or merge it into another")
944
+ # a quick run: one small, clear milestone, the lead says why it is small, and nothing that needs the full process
945
+ if quick:
946
+ if not quick_because:
947
+ errors.append("`Mode: quick` needs `Quick because: <what you found in the code that makes this small>` "
948
+ "— e.g. `Quick because: the column already exists, only the response changes`")
949
+ if len(enabled) > 1:
950
+ errors.append(f"`Mode: quick` is one milestone, and this plan has {len(enabled)} — put the small changes "
951
+ f"in one milestone (one acceptance criterion each), or use `Mode: full`")
952
+ if isolation == "worktree":
953
+ warns.append("`Mode: quick` with `Isolation: worktree`: one milestone needs no separate folder — "
954
+ "`Isolation: shared` skips the worktree and its setup")
955
+ for tid in enabled:
956
+ never = sorted({f"{what}: {f}" for f in files[tid] for rx, what in QUICK_NEVER if rx.search(f)})
957
+ if never:
958
+ errors.append(f"{tid} lists {', '.join(never)} — a quick run never touches these; use `Mode: full`")
959
+ careful = sorted(f for f in files[tid] if QUICK_CAREFUL_RE.search(f))
960
+ if careful:
961
+ warns.append(f"{tid} lists {', '.join(careful)}, which looks like auth, payment or schema code — "
962
+ f"those take the full process; keep `Mode: quick` only if the change does not touch them")
963
+ if has_open_questions(by_id[tid]):
964
+ errors.append(f"{tid} has open questions — a quick run needs a clear change; answer them or use "
965
+ f"`Mode: full`")
931
966
  max_tasks = int(os.environ.get("ORCH_MAX_TASKS", "0") or 0) # no limit unless you set one
932
967
  if max_tasks and len(enabled) > max_tasks:
933
968
  warns.append(f"{len(enabled)} enabled milestones (> ORCH_MAX_TASKS={max_tasks}). Merge coupled milestones "
@@ -954,6 +989,9 @@ def cmd_sync(args):
954
989
  "base": base.split()[0] if base else None,
955
990
  "title": title_m.group(1) if title_m else branch,
956
991
  "commits": commits,
992
+ "mode": mode,
993
+ "quick_because": quick_because if quick else None,
994
+ "green_tree": old.get("green_tree"),
957
995
  "integration_broken": old.get("integration_broken"),
958
996
  "schema": STATE_SCHEMA,
959
997
  "notified": old.get("notified", []),
@@ -987,6 +1025,7 @@ def cmd_sync(args):
987
1025
  "lead_seq": old.get("lead_seq", 0),
988
1026
  "lead_wake": old.get("lead_wake"),
989
1027
  "lead_ready_told": old.get("lead_ready_told"),
1028
+ "tree_task": old.get("tree_task"),
990
1029
  "workers": {},
991
1030
  "order": ids,
992
1031
  "tasks": {},
@@ -1047,7 +1086,7 @@ def cmd_sync(args):
1047
1086
  save(st)
1048
1087
  for w in warns:
1049
1088
  print("WARN:", w)
1050
- print(f"OK: {len(tasks)} tasks, isolation={isolation}, max_parallel={max_par}, "
1089
+ print(f"OK: {len(tasks)} tasks, " + ("mode=quick, " if quick else "") + f"isolation={isolation}, max_parallel={max_par}, "
1051
1090
  f"workers={list(workers)}, reviewer={reviewer}" + (f", lead={lead[0]}" if lead else ""))
1052
1091
 
1053
1092
 
@@ -1112,6 +1151,106 @@ def restore_stash(st, tid):
1112
1151
  git("update-ref", "-d", ref, cwd=ROOT)
1113
1152
 
1114
1153
 
1154
+ def rescue_ref(st, who):
1155
+ """A hidden ref for unsaved files orch found and could not give to a milestone. Kept by `orch finish`."""
1156
+ ref = f"{REF_NS}/{st['branch'].replace('/', '-')}/rescue-{who}-{time.strftime('%Y%m%d-%H%M%S')}"
1157
+ n = 1
1158
+ while ref_ok(ref if n == 1 else f"{ref}-{n}"): # never write over an earlier rescue
1159
+ n += 1
1160
+ return ref if n == 1 else f"{ref}-{n}"
1161
+
1162
+
1163
+ def _last_task_of(st, name):
1164
+ """The milestone this coder worked on most recently (by its recorded attempts), or None."""
1165
+ best = (0, None)
1166
+ for tid in st["order"]:
1167
+ ends = [a.get("end", 0) for a in st["tasks"][tid].get("attempts") or []
1168
+ if a.get("kind") == "coder" and a.get("agent") == name]
1169
+ if ends and max(ends) > best[0]:
1170
+ best = (max(ends), tid)
1171
+ return best[1]
1172
+
1173
+
1174
+ def save_stray(st, name, rescue=True):
1175
+ """Worktree mode: a coder that holds no milestone has uncommitted files in its folder (it kept working after
1176
+ its milestone was parked, or the machine went down). Save them into the milestone they belong to: the one
1177
+ whose saved work this folder is on, else the one this coder worked on last if nothing of it was saved yet.
1178
+ When orch can't tell whose they are, they go to a rescue ref (rescue=True) or stay where they are.
1179
+ Returns a line saying what happened, or None when there was nothing to save."""
1180
+ w = st["workers"].get(name) or {}
1181
+ d = w.get("dir")
1182
+ if st["isolation"] != "worktree" or w.get("task") or not d or not Path(d).exists() or not is_dirty(d):
1183
+ return None
1184
+ head = git("rev-parse", "HEAD", cwd=d).stdout.strip()
1185
+ owner = None
1186
+ for tid in st["order"]:
1187
+ if st["tasks"][tid]["status"] in RESTING and ref_ok(task_ref(st, tid)) and \
1188
+ git("rev-parse", task_ref(st, tid), cwd=ROOT).stdout.strip() == head:
1189
+ owner = tid
1190
+ break
1191
+ if not owner:
1192
+ last = _last_task_of(st, name)
1193
+ lt = st["tasks"].get(last) or {}
1194
+ if last and lt["status"] in RESTING and lt.get("last_worker") == name and not lt.get("worker") \
1195
+ and not work_ref(st, last) and not ahead_of_branch(st, d):
1196
+ owner = last
1197
+ if owner:
1198
+ wip_commit(d, f"orch wip {owner}: files written after it was parked")
1199
+ git("update-ref", task_ref(st, owner), "HEAD", cwd=d)
1200
+ return f"SAVED {name}'s unsaved files into {owner}'s saved work ({task_ref(st, owner)})"
1201
+ if not rescue:
1202
+ return None
1203
+ ref = rescue_ref(st, name)
1204
+ wip_commit(d, f"orch rescue: unsaved files found in {name}'s folder")
1205
+ git("update-ref", ref, "HEAD", cwd=d)
1206
+ return (f"RESCUED {name}'s unsaved files: orch can't tell which milestone they belong to, so they are kept in "
1207
+ f"{ref} (`git show --stat {ref}` to look)")
1208
+
1209
+
1210
+ def shared_fold(st, tid):
1211
+ """Shared mode: the main folder has uncommitted files that belong to Mn (written after Mn was parked). Add
1212
+ them to Mn's saved work and leave the folder clean. If they can't be combined with what was saved before,
1213
+ the newer files are kept in a rescue ref. Returns a line saying what happened."""
1214
+ ref = task_ref(st, tid)
1215
+ if not ref_ok(ref):
1216
+ stash_to_ref(st, tid)
1217
+ return f"SAVED the unsaved files in the main folder into {tid}'s saved work ({ref})"
1218
+ old = git("rev-parse", ref, cwd=ROOT).stdout.strip()
1219
+ git("stash", "push", "--include-untracked", "-q", "-m", f"orch {tid} later", cwd=ROOT)
1220
+ new = git("rev-parse", "stash@{0}", cwd=ROOT).stdout.strip()
1221
+ keep = rescue_ref(st, tid)
1222
+ git("update-ref", keep, new, cwd=ROOT) # safe before anything else is tried
1223
+ git("stash", "drop", "-q", cwd=ROOT)
1224
+
1225
+ def wipe():
1226
+ git("reset", "--hard", "-q", "HEAD", cwd=ROOT)
1227
+ git("clean", "-fdq", cwd=ROOT) # only what the applies below put there: both are kept in refs
1228
+ if git("stash", "apply", "-q", old, cwd=ROOT, check=False).returncode == 0 and \
1229
+ git("stash", "apply", "-q", new, cwd=ROOT, check=False).returncode == 0:
1230
+ stash_to_ref(st, tid) # both together are Mn's saved work now
1231
+ git("update-ref", "-d", keep, cwd=ROOT)
1232
+ return f"SAVED the unsaved files in the main folder into {tid}'s saved work ({ref})"
1233
+ wipe()
1234
+ return (f"RESCUED the unsaved files in the main folder: they don't fit on top of {tid}'s saved work, so they "
1235
+ f"are kept in {keep} (`git stash show -p {new[:12]}` to look); {tid} keeps its earlier saved work")
1236
+
1237
+
1238
+ def stop_note(st, agent, tid, status, reason):
1239
+ """Tell a coder whose milestone was just paused or failed to stop. Only when it is (or may be) still working;
1240
+ whatever it writes anyway is saved the next time the milestone or its folder is used."""
1241
+ if watched(st, agent):
1242
+ s = herdr_state(agent)
1243
+ if s is None or not word(s, "working"):
1244
+ return False
1245
+ why = " ".join((reason or status).split())[:160]
1246
+ try:
1247
+ deliver(st, agent, f"STOP: {tid} is {status} ({why}). Stop working on it now and do not change any more "
1248
+ f"files. What you did so far is saved. You get a new prompt if it continues.")
1249
+ except DeliveryError:
1250
+ return False
1251
+ return True
1252
+
1253
+
1115
1254
  def commit_message(st, tid):
1116
1255
  """Commit message for a landed milestone: the coder's `COMMIT:` line (what changed), else the title.
1117
1256
  The milestone id is a trailer, never the subject."""
@@ -1226,6 +1365,35 @@ def run_check(st, cwd):
1226
1365
  return ok, tail, round(time.time() - t0, 1)
1227
1366
 
1228
1367
 
1368
+ def tree_of(d):
1369
+ """Hash of the files git sees in d (tracked and untracked, not ignored), without touching the real index.
1370
+ Two checks of the same tree give the same answer, so a green check on it can be reused."""
1371
+ try:
1372
+ real = Path(git("rev-parse", "--path-format=absolute", "--git-path", "index", cwd=d).stdout.strip())
1373
+ with tempfile.TemporaryDirectory() as td:
1374
+ tmp = Path(td) / "index"
1375
+ if real.exists():
1376
+ shutil.copyfile(real, tmp)
1377
+ env = {**os.environ, "GIT_INDEX_FILE": str(tmp)}
1378
+ subprocess.run(["git", "add", "-A"], cwd=d, env=env, capture_output=True, timeout=120)
1379
+ r = subprocess.run(["git", "write-tree"], cwd=d, env=env, capture_output=True, text=True, timeout=60)
1380
+ return r.stdout.strip() if r.returncode == 0 and r.stdout.strip() else None
1381
+ except (OSError, subprocess.SubprocessError, SystemExit):
1382
+ return None
1383
+
1384
+
1385
+ def note_green(st, d, ok):
1386
+ """Remember the tree a passing check ran on in the main folder (a failing one forgets it)."""
1387
+ if Path(d).resolve() != ROOT.resolve():
1388
+ return
1389
+ st["green_tree"] = tree_of(d) if ok else None
1390
+
1391
+
1392
+ def green_still(st, d):
1393
+ """True when the main folder holds exactly the tree the last passing check ran on: no need to run it again."""
1394
+ return bool(st.get("check") and st.get("green_tree")) and tree_of(d) == st["green_tree"]
1395
+
1396
+
1229
1397
  def path_allowed(path, patterns):
1230
1398
  return any(path == p or fnmatch.fnmatch(path, p) or path.startswith(p.rstrip("/") + "/") for p in patterns)
1231
1399
 
@@ -1384,6 +1552,7 @@ def cmd_start(args):
1384
1552
  agents = [(name, w, "WORKER") for name, w in st["workers"].items()]
1385
1553
  if st.get("reviewer"):
1386
1554
  agents.append((st["reviewer"], st.get("reviewer_info") or {}, "REVIEWER"))
1555
+ lost = False
1387
1556
  for name, w, label in agents:
1388
1557
  where = f" dir={w['dir']}" if label == "WORKER" else ""
1389
1558
  if w.get("pane"):
@@ -1398,7 +1567,11 @@ def cmd_start(args):
1398
1567
  herdr = "detect:off (relying on its done file)"
1399
1568
  else:
1400
1569
  herdr = "found" if herdr_state(name) is not None else "NOT FOUND"
1570
+ lost = lost or herdr == "NOT FOUND"
1401
1571
  print(f"{label} {name} kind={w.get('kind')}{where} herdr={herdr}")
1572
+ if lost:
1573
+ print("HINT an agent herdr can't find: after a herdr or computer restart the panes come back without their "
1574
+ "names — `orch resume` names them again; `orch team up` opens the ones that are really gone")
1402
1575
 
1403
1576
 
1404
1577
  def deps_met(st, t):
@@ -1519,23 +1692,36 @@ def cmd_prepare(args):
1519
1692
  die("no free slot (max parallel reached)")
1520
1693
  d = Path(w["dir"] or ROOT)
1521
1694
  if st["isolation"] == "worktree":
1522
- if is_dirty(d):
1523
- die(f"{d} has uncommitted changes — park or clean that worker first")
1695
+ in_place = w.get("task") == tid and is_dirty(d) # its own work in progress: it carries on right there
1696
+ if is_dirty(d) and not in_place: # never refuse: save what is there first, then hand the folder over
1697
+ print(save_stray(st, worker))
1524
1698
  src = work_ref(st, tid)
1525
1699
  if src and src != task_ref(st, tid): # pre-4.5 task branch: carry its work over to the hidden ref
1526
1700
  git("update-ref", task_ref(st, tid), src, cwd=ROOT)
1527
1701
  src = task_ref(st, tid)
1528
- git("switch", "-q", "--detach", src or st["branch"], cwd=d)
1702
+ if not in_place:
1703
+ git("switch", "-q", "--detach", src or st["branch"], cwd=d)
1529
1704
  else:
1530
1705
  if git("rev-parse", "--abbrev-ref", "HEAD", cwd=ROOT).stdout.strip() != st["branch"]:
1531
1706
  die(f"main tree is not on {st['branch']}")
1707
+ mine = False
1708
+ if is_dirty(ROOT) and not holds(st, tid) and not coders_busy(st):
1709
+ # files written after a milestone was parked belong to the milestone that had the folder last
1710
+ last = st.get("tree_task")
1711
+ if last == tid:
1712
+ mine = True
1713
+ if ref_ok(task_ref(st, tid)):
1714
+ print(shared_fold(st, tid))
1715
+ elif last in st["tasks"] and st["tasks"][last]["status"] in RESTING:
1716
+ print(shared_fold(st, last))
1532
1717
  if ref_ok(task_ref(st, tid)):
1533
1718
  if is_dirty(ROOT):
1534
1719
  die(f"main tree has uncommitted changes, so {tid}'s parked work ({task_ref(st, tid)}) can't be "
1535
1720
  f"restored — finish or discard them first")
1536
1721
  restore_stash(st, tid)
1537
- elif is_dirty(ROOT) and t["status"] == "pending" and not holds(st, tid):
1722
+ elif is_dirty(ROOT) and t["status"] == "pending" and not holds(st, tid) and not mine:
1538
1723
  die("main tree has uncommitted changes that no milestone owns — commit, stash or discard them first")
1724
+ st["tree_task"] = tid
1539
1725
  (d / TASK_DIR / tid).mkdir(parents=True, exist_ok=True)
1540
1726
  t.update(worker=worker, last_worker=worker, dir=str(d))
1541
1727
  t.pop("assign", None) # a lead's "this coder" holds for one dispatch; later retries may move
@@ -1561,14 +1747,83 @@ def cmd_setup_done(args):
1561
1747
  print("OK")
1562
1748
 
1563
1749
 
1750
+ def sleep_meter():
1751
+ """Returns a function that tells how many seconds the computer was suspended since its last call (0 when
1752
+ less than DOWN_MIN_S). The wall clock keeps going while a laptop sleeps and the monotonic clock does not,
1753
+ so the difference is the time this process could not run. (ORCH_TEST_SLEPT_S: a test's pretend sleep.)"""
1754
+ last = [time.time(), time.monotonic()]
1755
+ fake = [float(os.environ.get("ORCH_TEST_SLEPT_S") or 0)]
1756
+
1757
+ def slept():
1758
+ wall, mono = time.time(), time.monotonic()
1759
+ s = (wall - last[0]) - (mono - last[1]) + fake[0]
1760
+ last[0], last[1], fake[0] = wall, mono, 0
1761
+ return int(s) if s >= DOWN_MIN_S else 0
1762
+ return slept
1763
+
1764
+
1765
+ def account_downtime(st, slept=0):
1766
+ """The event manager writes a heartbeat (`run.beat`) every loop. A heartbeat older than DOWN_MIN_S when it
1767
+ starts again means nothing was watching the run meanwhile (computer off, herdr closed, manager killed).
1768
+ `slept` is the same thing found while running: the computer was suspended for that many seconds until now.
1769
+ That time is nobody's working time: every open wait is moved forward by it, so no task is paused as "over
1770
+ its time budget" for time orch was not there, and the window is kept in `run.downs` for the time report.
1771
+ Returns the seconds newly taken out (0 = orch was not down, or that time was taken out already)."""
1772
+ run = st.setdefault("run", {})
1773
+ t = now()
1774
+ beat = t - slept if slept else run.get("beat")
1775
+ run["beat"] = t
1776
+ if not beat or t - beat < DOWN_MIN_S:
1777
+ return 0
1778
+ # never the same time twice: `orch poll` and the event manager both notice one sleep, seconds apart
1779
+ known = sum(max(0, min(t, d["to"]) - max(beat, d["from"])) for d in run.get("downs") or [])
1780
+ if t - beat - known < (DOWN_MIN_S if slept else 1):
1781
+ return 0
1782
+ beat += known
1783
+ run.setdefault("downs", []).append({"from": beat, "to": t})
1784
+ del run["downs"][:-100]
1785
+ for task_ in st["tasks"].values():
1786
+ w = task_.get("wait")
1787
+ if w:
1788
+ w["down_s"] = w.get("down_s", 0) + max(0, t - max(beat, w.get("started", w["since"])))
1789
+ w["since"] += max(0, t - max(beat, w["since"]))
1790
+ if w.get("blocked_since"):
1791
+ w["blocked_since"] += max(0, t - max(beat, w["blocked_since"]))
1792
+ if task_.get("ready_ts"): # the lead could not dispatch while orch was down either
1793
+ task_["ready_ts"] += max(0, t - max(beat, task_["ready_ts"]))
1794
+ return t - beat
1795
+
1796
+
1797
+ def needs_manager(st):
1798
+ """True when the run has work only the event manager can move on: an agent being waited on, a step in
1799
+ progress, or a milestone that is ready and released."""
1800
+ if not (st.get("run") or {}).get("started"):
1801
+ return False # never driven yet: `orch autopilot` (or a dispatch) starts it
1802
+ for t in st["tasks"].values():
1803
+ if t.get("wait") or (t["status"] in ACTIVE and t["status"] != "held"):
1804
+ return True
1805
+ if t["status"] == "pending" and deps_met(st, t) and (t.get("go") or not lead_on(st)):
1806
+ return True
1807
+ return False
1808
+
1809
+
1810
+ def _clock(ts):
1811
+ """11:42 for today, else 2026-11-14 11:42."""
1812
+ lt = time.localtime(ts)
1813
+ return time.strftime("%H:%M" if lt[:3] == time.localtime()[:3] else "%Y-%m-%d %H:%M", lt)
1814
+
1815
+
1564
1816
  def record_attempt(t, outcome, usage=None):
1565
1817
  """Close the task's current wait as one attempt in its metrics (Phase 3: orch report)."""
1566
1818
  w = t.get("wait")
1567
1819
  if not w:
1568
1820
  return
1569
1821
  start = w.get("started", w.get("since", now()))
1822
+ down = min(w.get("down_s", 0), max(0, now() - start)) # orch was not running: not the agent's time
1570
1823
  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}
1824
+ "secs": max(0, now() - start - down), "nudges": w.get("nudges", 0), "outcome": outcome}
1825
+ if down:
1826
+ a["down_s"] = down
1572
1827
  if w.get("model"):
1573
1828
  a["model"], a["tier"] = w["model"], w.get("tier")
1574
1829
  blocked = w.get("blocked_s", 0) + (now() - w["blocked_since"] if w.get("blocked_since") else 0)
@@ -1902,10 +2157,14 @@ def cmd_poll(args):
1902
2157
  secs = int(args[0]) if args else 100
1903
2158
  start = time.time()
1904
2159
  end = start + secs
2160
+ slept = sleep_meter()
1905
2161
  while True:
1906
2162
  with state_lock():
1907
2163
  st = load()
1908
2164
  events, changed = [], False
2165
+ asleep = slept()
2166
+ if asleep and account_downtime(st, asleep):
2167
+ changed = True # the computer was asleep: that time is not on any agent's clock
1909
2168
  for tid in st["order"]:
1910
2169
  t = st["tasks"][tid]
1911
2170
  w = t.get("wait")
@@ -2097,6 +2356,7 @@ def cmd_merge(args):
2097
2356
  st["merging"] = None
2098
2357
  _integration_failed(st, tid, tail)
2099
2358
  git("commit", "-q", "-m", commit_message(st, tid), cwd=ROOT)
2359
+ note_green(st, ROOT, True)
2100
2360
  fault("after-merge-commit")
2101
2361
  git("update-ref", "-d", task_ref(st, tid), cwd=ROOT, check=False)
2102
2362
  _finish(st, tid)
@@ -2189,7 +2449,11 @@ def _park(st, tid, status, reason, force=False):
2189
2449
  t = st["tasks"][tid]
2190
2450
  record_attempt(t, f"parked as {status}: {reason}" if reason else f"parked as {status}")
2191
2451
  d, w = t.get("dir"), t.get("worker")
2452
+ wait, note_to = t.get("wait") or {}, None
2192
2453
  if w and holds(st, tid):
2454
+ if status in ("paused", "failed") and wait.get("kind") == "coder" and wait.get("agent") == w \
2455
+ and not Path(wait["sentinel"]).exists():
2456
+ note_to = w # parked under a coder that had not finished: tell it to stop
2193
2457
  if st["isolation"] == "worktree" and d and Path(d).exists():
2194
2458
  if is_dirty(d):
2195
2459
  wip_commit(d, f"orch wip {tid}: parked — {reason or status}")
@@ -2198,6 +2462,15 @@ def _park(st, tid, status, reason, force=False):
2198
2462
  elif st["isolation"] == "shared":
2199
2463
  stash_to_ref(st, tid) # the tree is clean again, so the next milestone can start
2200
2464
  st["workers"][w]["task"] = None
2465
+ elif t["status"] in RESTING:
2466
+ # already parked, but its coder may have kept writing since: that work is saved too, never skipped
2467
+ saved = None
2468
+ if st["isolation"] == "worktree":
2469
+ saved = save_stray(st, w or t.get("last_worker"), rescue=False)
2470
+ elif st.get("tree_task") == tid and not coders_busy(st) and is_dirty(ROOT):
2471
+ saved = shared_fold(st, tid)
2472
+ if saved:
2473
+ print(saved)
2201
2474
  if w:
2202
2475
  t["last_worker"], t["worker"] = w, None
2203
2476
  if st.get("reviewer_busy") == tid:
@@ -2205,6 +2478,8 @@ def _park(st, tid, status, reason, force=False):
2205
2478
  move(st, tid, status, reason, force=force)
2206
2479
  t["wait"] = None
2207
2480
  save(st)
2481
+ if note_to and stop_note(st, note_to, tid, status, reason):
2482
+ print(f"STOP_NOTE {tid} -> {note_to}: told to stop and not change more files")
2208
2483
 
2209
2484
 
2210
2485
  def cmd_park(args):
@@ -2271,6 +2546,14 @@ def cmd_status(args):
2271
2546
  st = load()
2272
2547
  if driver_alive():
2273
2548
  print(f"driven by {driver_line(driver_info())}")
2549
+ elif needs_manager(st):
2550
+ beat = (st.get("run") or {}).get("beat")
2551
+ print("!! EVENT MANAGER NOT RUNNING"
2552
+ + (f" since {_clock(beat)} ({_dur(now() - beat)} ago)" if beat else "")
2553
+ + " — nothing is watching this run, so it will not move.\n"
2554
+ "!! Run `orch resume` (after a restart it also finds the agents again and re-sends their tasks).")
2555
+ if st.get("mode") == "quick":
2556
+ print(f"QUICK RUN because: {st.get('quick_because') or '-'}")
2274
2557
  print(f"branch={st['branch']} base={st.get('base')} isolation={st['isolation']} "
2275
2558
  f"max_parallel={st['max_parallel']} reviewer={st['reviewer']} (busy: {st.get('reviewer_busy')})")
2276
2559
  if st.get("integration_broken"):
@@ -2296,7 +2579,7 @@ def cmd_status(args):
2296
2579
  + (f"; waiting for `orch dispatch`: {', '.join(hold)}" if hold else "")
2297
2580
  + (f"; wake-up sent {lw['n']}x (last {_fmt_secs(now() - lw.get('ts', now()))} ago), not picked up yet"
2298
2581
  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`)"))
2582
+ + ("" if driver_alive() else "; the event manager is NOT running (`orch resume`)"))
2300
2583
  if all(t["status"] in ("merged", "skipped") for t in st["tasks"].values()):
2301
2584
  print(f"ALL_DONE — run `orch finish` to push {st['branch']} and open a PR into {st.get('base')}")
2302
2585
  elif lead_on(st) and (undispatched(st) or any(event_open(st, e) for e in st["lead_events"])):
@@ -2332,7 +2615,8 @@ def github_compare_url(remote, base, branch):
2332
2615
 
2333
2616
 
2334
2617
  def cmd_finish(args):
2335
- """orch finish [--no-push] -> final check, drop hidden refs and worktrees, push the feature branch, open a PR."""
2618
+ """orch finish [--no-push] [--recheck] -> final check (reused when it already passed on exactly these files;
2619
+ --recheck runs it anyway), drop hidden refs and worktrees, push the feature branch, open a PR."""
2336
2620
  st = load()
2337
2621
  left = [f"{k} ({v['status']})" for k, v in st["tasks"].items() if v["status"] not in ("merged", "skipped")]
2338
2622
  if left:
@@ -2340,7 +2624,9 @@ def cmd_finish(args):
2340
2624
  if git("rev-parse", "--abbrev-ref", "HEAD", cwd=ROOT).stdout.strip() != st["branch"] or is_dirty(ROOT):
2341
2625
  die(f"main tree must be clean and on {st['branch']}")
2342
2626
  base = st.get("base") or default_base(st)
2343
- if st.get("check"):
2627
+ if "--recheck" not in args and green_still(st, ROOT):
2628
+ print(f"CHECK reused: it already passed on exactly these files ({st['green_tree'][:10]}), not run again")
2629
+ elif st.get("check"):
2344
2630
  r = subprocess.run(st["check"], shell=True, cwd=ROOT, text=True, capture_output=True)
2345
2631
  if r.returncode != 0:
2346
2632
  die(f"the check fails on {st['branch']} — fix it before finishing:\n"
@@ -2360,12 +2646,17 @@ def cmd_finish(args):
2360
2646
  cwd=ROOT).stdout.split()
2361
2647
  if st["isolation"] == "worktree":
2362
2648
  remove_worktrees(st)
2649
+ rescued = [r for r in refs if "/rescue-" in r]
2650
+ refs = [r for r in refs if r not in rescued]
2363
2651
  for ref in refs:
2364
2652
  git("update-ref", "-d", ref, cwd=ROOT)
2365
2653
  for tid in st["order"]: # task branches left by orch < 4.5
2366
2654
  if branch_exists(f"{st['branch']}-{tid}"):
2367
2655
  git("branch", "-D", "-q", f"{st['branch']}-{tid}", cwd=ROOT, check=False)
2368
2656
  print(f"CLEAN {st['branch']} is the only branch this run made ({len(refs)} hidden ref(s) removed)")
2657
+ for ref in rescued:
2658
+ print(f"KEPT {ref}: unsaved files orch rescued during the run and no milestone used — look with "
2659
+ f"`git show --stat {ref}`, delete with `git update-ref -d {ref}`")
2369
2660
  if "--no-push" in args:
2370
2661
  print(f"NOT PUSHED (--no-push): push {st['branch']} and open a PR into {base} when ready")
2371
2662
  return
@@ -2696,7 +2987,7 @@ EVENT_HELP = {
2696
2987
  "developer the fix in the event text (usually: rename the reviewer's new pane). Review resumes "
2697
2988
  "by itself once herdr finds the reviewer again.",
2698
2989
  "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.",
2990
+ "stopped": "the event manager stopped. Tell the developer why; they run `orch resume` (or `orch autopilot`).",
2700
2991
  }
2701
2992
 
2702
2993
 
@@ -2735,7 +3026,8 @@ def cmd_events(args):
2735
3026
  f"{n} ({w['kind']}" + (f": {w['model']}, {w.get('tier') or 'unrated'}" if w.get("model") else "") + ")"
2736
3027
  + (" free" if n in free else f" on {w['task']}") for n, w in st["workers"].items()))
2737
3028
  print("event manager: " + (driver_line(driver_info()) if driver_alive() else
2738
- "NOT running — your next `orch dispatch` or `orch answer` starts it"))
3029
+ "NOT running — your next `orch dispatch` or `orch answer` starts it"
3030
+ + (" (work is in progress: run `orch resume` now)" if needs_manager(st) else "")))
2739
3031
  if not new and not old and not hold:
2740
3032
  print("Nothing needs you.")
2741
3033
  print("Handle each event above, then STOP: you are woken again when something else happens. Never prompt a "
@@ -2862,6 +3154,7 @@ def cmd_autopilot(args):
2862
3154
 
2863
3155
  def check(cwd, tid=None, where="worktree"):
2864
3156
  ok, tail, secs = run_check(st, cwd)
3157
+ patch_state(lambda s_: note_green(s_, cwd, ok))
2865
3158
  if tid:
2866
3159
  patch_state(lambda s_: s_["tasks"][tid].setdefault("checks", []).append(
2867
3160
  {"where": where, "ok": ok, "secs": secs, "ts": now()}))
@@ -3249,6 +3542,14 @@ def cmd_autopilot(args):
3249
3542
  if stale:
3250
3543
  say("A pane id in plan.md is stale. Stopping.\n" + "\n".join(stale), True)
3251
3544
  sys.exit(3)
3545
+ # after a gap (computer off, herdr closed, manager killed): don't count the gap, find the agents again, save
3546
+ # unsaved work and re-send what was in progress. Nothing happens when there was no gap.
3547
+ try:
3548
+ _, rout = run("resume", "--from-manager")
3549
+ if rout:
3550
+ say("back after a gap:\n" + rout, True)
3551
+ except RuntimeError as e:
3552
+ say(f"could not run the restart recovery — carrying on without it\n{e}")
3252
3553
  st = load()
3253
3554
  for name in [n for n in st["workers"] if not watched(st, n)] + (
3254
3555
  [st["reviewer"]] if st.get("reviewer") and not watched(st, st["reviewer"]) else []):
@@ -3276,15 +3577,21 @@ def cmd_autopilot(args):
3276
3577
  + (f", budget {st['budget_s'] // 60} min" if st.get("budget_s") else "")
3277
3578
  + (f"; events go to the lead ({st['lead']['name']})" if lead_on(st) else ""))
3278
3579
  last_tick = time.time()
3580
+ slept = sleep_meter()
3279
3581
  waiting_since = None # set while nothing runs and the run waits for the lead or the developer
3280
3582
 
3281
3583
  while True:
3282
3584
  st = load()
3283
3585
  # 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
3284
3586
  el, last_tick = time.time() - last_tick, time.time()
3587
+ asleep = slept()
3588
+ if asleep: # the computer was suspended: nobody's time, not the budget's either
3589
+ patch_state(lambda s_: account_downtime(s_, asleep))
3590
+ say(f"the computer was asleep for {_dur(asleep)}: that time is not counted against any task")
3591
+ el = max(0, el - asleep)
3285
3592
  if waiting_since:
3286
3593
  el = 0
3287
- patch_state(lambda s_: s_["run"].update(driven_s=round(s_["run"].get("driven_s", 0) + el, 1)))
3594
+ patch_state(lambda s_: s_["run"].update(driven_s=round(s_["run"].get("driven_s", 0) + el, 1), beat=now()))
3288
3595
  st = load()
3289
3596
  if st.get("budget_s") and st["run"].get("driven_s", 0) > st["budget_s"]:
3290
3597
  say(f"STOPPED — the run's budget ({st['budget_s'] // 60} min of autopilot time) is used up. Raise "
@@ -3318,7 +3625,11 @@ def cmd_autopilot(args):
3318
3625
  st = load()
3319
3626
  tasks = st["tasks"]
3320
3627
  if all(t["status"] in ("merged", "skipped") for t in tasks.values()):
3321
- ok, tail = check(ROOT)
3628
+ if green_still(st, ROOT): # the last passing check ran on exactly these files
3629
+ ok, tail = True, ""
3630
+ say("final check: the check already passed on exactly these files, not run again")
3631
+ else:
3632
+ ok, tail = check(ROOT)
3322
3633
  if not ok:
3323
3634
  patch_state(lambda s_: s_.update(integration_broken="the final check"))
3324
3635
  patch_state(lambda s_: s_["run"].update(ended=now()))
@@ -3341,12 +3652,14 @@ def cmd_autopilot(args):
3341
3652
  models.append(f"| {k} | {v.get('tier') or 'any'} | {ran} | "
3342
3653
  f"{'yes' if v.get('escalated') else 'no'} | {v.get('model_why') or '-'} |")
3343
3654
  lead_ = lead_on(st)
3655
+ quick_run = st.get("mode") == "quick"
3344
3656
  prev = ORCH / "summary.md"
3345
3657
  if prev.exists(): # a fix after ALL_DONE writes the summary again: keep the lead's notes
3346
3658
  shutil.copyfile(prev, ORCH / "summary.prev.md")
3347
3659
  (ORCH / "summary.md").write_text(
3348
3660
  f"# Summary: {st.get('title') or st['branch']}\n\nBranch `{st['branch']}` into `{base}`. "
3349
3661
  f"Final check on the branch: {'PASS' if ok else 'FAIL'}\n\n"
3662
+ + (f"Quick run because: {st.get('quick_because') or '-'}\n\n" if quick_run else "") +
3350
3663
  "## Tasks\n" + "\n".join(f"- {k}: {v['title']} ({v['status']}, last coder {v.get('worker') or v.get('last_worker') or '-'})"
3351
3664
  for k, v in tasks.items()) +
3352
3665
  f"\n\n## Commits\n```\n{log_}```\n\n## Files changed\n```\n{stat}```\n\n"
@@ -3359,10 +3672,12 @@ def cmd_autopilot(args):
3359
3672
  f"{auto_checked(st, ok)}\n\n"
3360
3673
  f"## Run report\n```\n{report}\n```\n\n"
3361
3674
  + ("## Still to write (the lead was woken to write these)\n" if lead_ else
3362
- "## Still to write (ask the lead: 'use the orch-run skill' to finish the summary)\n") +
3363
- "- Design decisions & study notes\n"
3364
- "- Checked by the lead: what you verified yourself by running a command or reading the code, with the "
3365
- "evidence\n"
3675
+ "## Still to write (ask the lead: 'use the orch-run skill' to finish the summary)\n")
3676
+ + ("" if quick_run else "- Design decisions & study notes\n")
3677
+ + ("- What changed: one line per change, in the developer's words, and how it was checked\n"
3678
+ if quick_run else
3679
+ "- Checked by the lead: what you verified yourself by running a command or reading the code, with "
3680
+ "the evidence\n") +
3366
3681
  "- Manual verification checklist: only what a person must see or do (how the UI looks and behaves, a "
3367
3682
  "real device, an outside account). Nothing a command or a look at the code can settle.\n"
3368
3683
  + ("\nThe summary before this one is in `.orchestrate/summary.prev.md`: carry its notes and checklist "
@@ -3574,6 +3889,11 @@ def time_account(st, at=None):
3574
3889
  time orch can't place is shown as orch's own steps, and a missing estimate stays missing."""
3575
3890
  at = at or now()
3576
3891
  trans, rows = _transitions(st), []
3892
+ downs = (st.get("run") or {}).get("downs") or []
3893
+
3894
+ def down_in(a, b):
3895
+ """Seconds of [a, b] in which orch was not running (computer off, event manager stopped)."""
3896
+ return sum(max(0, min(b, d["to"]) - max(a, d["from"])) for d in downs)
3577
3897
  for tid in st["order"]:
3578
3898
  t = st["tasks"][tid]
3579
3899
  if t["status"] == "skipped":
@@ -3581,7 +3901,8 @@ def time_account(st, at=None):
3581
3901
  evs = trans.get(tid, [])
3582
3902
  first = next((i for i, e in enumerate(evs) if e.get("to") == "coding"), None)
3583
3903
  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}
3904
+ "landed": t["status"] == "merged", "start": None, "end": None, "parts": [], "over_s": None,
3905
+ "down_s": 0}
3585
3906
  rows.append(row)
3586
3907
  if first is None:
3587
3908
  continue
@@ -3601,7 +3922,7 @@ def time_account(st, at=None):
3601
3922
  a_, b_ = max(evs[i]["ts"], start), min(evs[i + 1]["ts"] if i + 1 < len(evs) else end, end)
3602
3923
  w = _wait_part(st, evs[i].get("to"), evs[i].get("why"), evs[i].get("agent"))
3603
3924
  if w and b_ > a_:
3604
- add(w[0], w[1], b_ - a_, True)
3925
+ add(w[0], w[1], b_ - a_ - down_in(a_, b_), True)
3605
3926
  # working: from the attempts
3606
3927
  esc = next((e["ts"] for e in evs[first:] if (e.get("why") or "").startswith("escalated")), None)
3607
3928
  built = reviewed = False
@@ -3634,10 +3955,11 @@ def time_account(st, at=None):
3634
3955
  again = c.get("where") in seen
3635
3956
  seen.add(c.get("where"))
3636
3957
  add("checks run again after fixes" if again else "checks", "check command", c.get("secs", 0), again)
3637
- total = end - start
3958
+ down = down_in(start, end) # not counted: nobody could work or be watched
3959
+ total = end - start - down
3638
3960
  placed = sum(p["secs"] for p in parts.values())
3639
3961
  add("orch's own steps (setup, prompts, merge)", "orch", max(0, total - placed), False)
3640
- row.update(start=start, end=end, actual_s=total,
3962
+ row.update(start=start, end=end, actual_s=total, down_s=down,
3641
3963
  parts=sorted(parts.values(), key=lambda p: (p["extra"], -p["secs"])))
3642
3964
  if row["estimate_s"]:
3643
3965
  row["over_s"] = total - row["estimate_s"]
@@ -3645,21 +3967,22 @@ def time_account(st, at=None):
3645
3967
  # landed and before a fix asked with `orch fix` is not counted, time with nothing running is
3646
3968
  started = sorted((r for r in rows if r["start"]), key=lambda r: r["start"])
3647
3969
  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": []}
3970
+ "down_s": 0, "landed": bool(rows) and all(r["landed"] for r in rows), "why": []}
3649
3971
  if started:
3650
3972
  fstart = started[0]["start"]
3651
3973
  fend = max(r["end"] for r in started)
3652
3974
  reach, idle, after = started[0]["end"], 0, 0
3653
3975
  for r in started[1:]:
3654
3976
  if r["start"] > reach:
3655
- gap = r["start"] - reach
3977
+ gap = r["start"] - reach - down_in(reach, r["start"])
3656
3978
  if st["tasks"][r["task"]].get("fix_of") and all(x["landed"] and x["end"] <= reach
3657
3979
  for x in started if x["start"] < r["start"]):
3658
3980
  after += gap
3659
3981
  else:
3660
3982
  idle += gap
3661
3983
  reach = max(reach, r["end"])
3662
- feat.update(actual_s=fend - fstart - after, idle_s=idle, after_done_s=after)
3984
+ fdown = down_in(fstart, fend)
3985
+ feat.update(actual_s=fend - fstart - after - fdown, idle_s=idle, after_done_s=after, down_s=fdown)
3663
3986
  if feat["estimate_s"]:
3664
3987
  feat["over_s"] = feat["actual_s"] - feat["estimate_s"]
3665
3988
  agg = {}
@@ -3698,7 +4021,11 @@ def time_lines(acct):
3698
4021
  if est and act is not None:
3699
4022
  head += (f", {_dur(f['over_s'])} longer than estimated" if f["over_s"] > 0 else
3700
4023
  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 |", "|---|---|---|---|---|"]
4024
+ out += [head]
4025
+ if f.get("down_s"):
4026
+ out += [f"Not counted: {_dur(f['down_s'])} while orch was not running (computer off, herdr closed or the "
4027
+ f"event manager stopped). No agent is charged for that time."]
4028
+ out += ["", "| Milestone | Estimate | Actual | Difference | Built by |", "|---|---|---|---|---|"]
3702
4029
  for r in acct["tasks"]:
3703
4030
  diff = "-" if r["over_s"] is None else ("on time" if r["over_s"] == 0 else
3704
4031
  f"{'+' if r['over_s'] > 0 else '-'}{_dur(r['over_s'])}")
@@ -3898,6 +4225,9 @@ def team_up(args):
3898
4225
  missing_dirs = [n for n, w, d in agents if n in st["workers"] and not d]
3899
4226
  if missing_dirs:
3900
4227
  die(f"run `orch start` first: it makes each coder's folder ({', '.join(missing_dirs)} have none yet)")
4228
+ # after a restart: panes that only lost their name get it back, and a coder's own pane that came back as a
4229
+ # plain shell gets its agent started again, instead of a second pane next to it
4230
+ empty = {} if dry else rename_lost(dict(st, lead=None), hints=False)
3901
4231
  todo = []
3902
4232
  for name, w, d in agents:
3903
4233
  if w.get("pane"):
@@ -3928,20 +4258,21 @@ def team_up(args):
3928
4258
  print(f"WOULD {name}: {' '.join(shlex.quote(x) for x in split)} then herdr pane run <new pane> "
3929
4259
  f"{shlex.quote(cmd)} then herdr agent rename <new pane> {name}")
3930
4260
  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]
4261
+ pid = empty.get(name)
3937
4262
  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
4263
+ ok, data, out = _herdr_json(split)
4264
+ try:
4265
+ pid = data["result"]["pane"]["pane_id"] if ok else None
4266
+ except (TypeError, KeyError):
4267
+ pid = (re.search(r'"pane_id"\s*:\s*"([\w:.-]+)"', out) or [None, None])[1]
4268
+ if not pid:
4269
+ print(f"FAILED {name}: herdr could not open a pane ({out.splitlines()[-1] if out else 'no output'})")
4270
+ failed += 1
4271
+ continue
4272
+ last = pid
3942
4273
  ok, _, out = _herdr_json([HERDR, "pane", "run", pid, cmd])
3943
4274
  if not ok:
3944
- print(f"FAILED {name}: pane {pid} opened, but `herdr pane run` failed ({out[-120:]})")
4275
+ print(f"FAILED {name}: pane {pid} is there, but `herdr pane run` failed ({out[-120:]})")
3945
4276
  failed += 1
3946
4277
  continue
3947
4278
  if model and not v.get("model_flag"):
@@ -3972,7 +4303,207 @@ def team_up(args):
3972
4303
  sys.exit(3)
3973
4304
 
3974
4305
 
4306
+ # ---------------------------------------------------------------- resume: carry on after a restart
4307
+ def _dicts_with(obj, key, parent=None):
4308
+ """Every dict (with its parent dict) anywhere in a JSON value that has a string under `key`."""
4309
+ out = []
4310
+ if isinstance(obj, dict):
4311
+ if isinstance(obj.get(key), str):
4312
+ out.append((obj, parent))
4313
+ for v in obj.values():
4314
+ out += _dicts_with(v, key, obj)
4315
+ elif isinstance(obj, list):
4316
+ for v in obj:
4317
+ out += _dicts_with(v, key, parent)
4318
+ return out
4319
+
4320
+
4321
+ def herdr_panes():
4322
+ """{pane id: {"cwds": [...], "kind": str or None}} from `herdr pane list` and `herdr agent list`, or None
4323
+ when herdr can't list panes. Read loosely: any object with a `pane_id`, its `cwd` / `foreground_cwd`, and the
4324
+ agent kind where herdr gives one, so a changed JSON layout still yields the ids and folders."""
4325
+ panes, listed = {}, False
4326
+ for sub in ("pane", "agent"):
4327
+ ok, data, _ = _herdr_json([HERDR, sub, "list"])
4328
+ if not ok or data is None:
4329
+ continue
4330
+ listed = True
4331
+ for d, parent in _dicts_with(data, "pane_id"):
4332
+ p = panes.setdefault(d["pane_id"], {"cwds": [], "kind": None})
4333
+ srcs = [d] + [x for x in (d.get("agent"), parent if sub == "agent" else None) if isinstance(x, dict)]
4334
+ for src in srcs:
4335
+ for k in ("foreground_cwd", "cwd"):
4336
+ if isinstance(src.get(k), str) and src[k] and src[k] not in p["cwds"]:
4337
+ p["cwds"].append(src[k])
4338
+ for k in ("agent_kind", "kind", "agent"):
4339
+ if isinstance(src.get(k), str) and src[k] and not p["kind"]:
4340
+ p["kind"] = src[k].lower()
4341
+ return panes if listed else None
4342
+
4343
+
4344
+ def agent_pane(name):
4345
+ """The pane id herdr reports for a live agent name, or None."""
4346
+ ok, data, _ = _herdr_json([HERDR, "agent", "get", name])
4347
+ return _find_key(data, "pane_id") if ok and data is not None else None
4348
+
4349
+
4350
+ def _inside(path, folder):
4351
+ a, b = os.path.realpath(path), os.path.realpath(folder)
4352
+ return a == b or a.startswith(b.rstrip("/") + "/")
4353
+
4354
+
4355
+ def rename_lost(st, hints=True):
4356
+ """herdr brings panes back after a restart, but not the agents' names, and orch reaches agents by name. For
4357
+ every agent in the plan that herdr can't find, look for its pane by folder and give the name back. A coder's
4358
+ worktree is its own folder, so one pane there is its pane. The reviewer and the lead sit in the main folder,
4359
+ next to the developer's own panes, so there the pane must also show the agent's kind. Where that can't be
4360
+ decided, print the exact command (hints=False: only say what was named).
4361
+ Returns {name: pane id or None} for the agents still not found; a pane id means "its pane is there (a
4362
+ coder's own folder), but no agent runs in it"."""
4363
+ plan = [(n, w, w.get("dir") or str(ROOT), st["isolation"] == "worktree" and bool(w.get("dir")))
4364
+ for n, w in st["workers"].items()]
4365
+ if st.get("reviewer"):
4366
+ plan.append((st["reviewer"], st.get("reviewer_info") or {}, str(ROOT), False))
4367
+ if st.get("lead"):
4368
+ plan.append((st["lead"]["name"], st["lead"], str(ROOT), False))
4369
+ plan = [x for x in plan if not x[1].get("pane") and x[1].get("detect", True)]
4370
+ lost = [x for x in plan if herdr_state(x[0]) is None]
4371
+ if not lost:
4372
+ return {}
4373
+ say = print if hints else (lambda *_: None)
4374
+ panes = herdr_panes()
4375
+ if panes is None:
4376
+ for n, _, d, _ in lost:
4377
+ say(f"LOST {n}: herdr has no agent with this name, and `herdr pane list` did not answer (is herdr "
4378
+ f"open?). Find its pane with `herdr agent list` (folder {short(d)}), then: herdr agent rename <pane> {n}")
4379
+ return {x[0]: None for x in lost}
4380
+ found = {x[0] for x in plan} - {x[0] for x in lost}
4381
+ taken = {agent_pane(n) for n in found} - {None}
4382
+ reg = registry(required=False) or {}
4383
+ still, pending, progress, cands = {}, list(lost), True, {}
4384
+ while pending and progress: # a pane given to one agent can settle who gets another
4385
+ progress = False
4386
+ for item in list(pending):
4387
+ n, w, d, own = item
4388
+ kind = (w.get("kind") or "").lower()
4389
+ here = [pid for pid, p in panes.items() if pid not in taken and any(_inside(x, d) for x in p["cwds"])]
4390
+ same = [pid for pid in here if kind and panes[pid]["kind"]
4391
+ and (kind in panes[pid]["kind"] or panes[pid]["kind"] in kind)]
4392
+ cands[n] = here
4393
+ pick = here[0] if own and len(here) == 1 else same[0] if len(same) == 1 else None
4394
+ if not pick:
4395
+ continue
4396
+ pending.remove(item)
4397
+ taken.add(pick)
4398
+ progress = True
4399
+ ok, _, _ = _herdr_json([HERDR, "agent", "rename", pick, n])
4400
+ if ok:
4401
+ print(f"NAMED {n}: pane {pick} (in {short(d)}) has its name back")
4402
+ continue
4403
+ still[n] = pick if own else None
4404
+ v = reg.get(w.get("kind"))
4405
+ cmd = launch_cmd(w.get("kind"), v, w.get("model"), strict=False) if v else (w.get("kind") or "<its agent>")
4406
+ say(f"LOST {n}: pane {pick} is in its folder ({short(d)}), but herdr sees no agent running in it. "
4407
+ + (f"`orch team up` starts it there; or start it yourself (`{cmd}`)" if own else
4408
+ f"Start it there (`{cmd}`)") + f", then: herdr agent rename {pick} {n}")
4409
+ for n, w, d, own in pending:
4410
+ still[n] = None
4411
+ if cands.get(n):
4412
+ say(f"LOST {n}: can't tell which pane is {n} ({', '.join(cands[n])} "
4413
+ f"{'is' if len(cands[n]) == 1 else 'are'} in {short(d)}). Look, then: herdr agent rename <pane> {n}")
4414
+ else:
4415
+ say(f"LOST {n}: no pane is left in its folder ({short(d)}). `orch team up` opens one, or start it "
4416
+ f"yourself there and: herdr agent rename <pane> {n}")
4417
+ return still
4418
+
4419
+
4420
+ RESUME_CODER = ("orch was restarted (the computer or herdr was off), so here is your task again. The changes you "
4421
+ "made before are still in this folder: look at them first (`git status`, `git diff`), keep what is "
4422
+ "right and carry on from there. Do not start over. ")
4423
+ RESUME_REVIEWER = "orch was restarted (the computer or herdr was off), so here is your review task again. "
4424
+
4425
+
4426
+ def cmd_resume(args):
4427
+ """orch resume -> carry on after a restart (the computer was off, herdr was closed, the event manager died).
4428
+ 1. says how long orch was down, and does not count that time against any task;
4429
+ 2. gives the agents' panes their names back (found by folder), or prints the exact rename command;
4430
+ 3. saves unsaved files left in the coders' folders;
4431
+ 4. sends each task that was in progress to its agent again (a fresh conversation carries on from the files);
4432
+ 5. starts the event manager, which wakes the lead if events wait for it.
4433
+ Safe to run at any time and more than once. Exit 3: an agent with work in progress is still not found.
4434
+ (`--from-manager`: the event manager's own call when it starts; it does 1-4 only after a real gap.)"""
4435
+ from_manager = "--from-manager" in args
4436
+ waiting = []
4437
+ with state_lock():
4438
+ st = load()
4439
+ info = driver_info()
4440
+ mine = from_manager and bool(os.environ.get("ORCH_DRIVER")) and os.environ.get("ORCH_DRIVER") == info.get("token")
4441
+ if driver_alive() and not mine:
4442
+ print(f"The event manager is running ({driver_line(info)}), so the run is being watched.")
4443
+ if rename_lost(st):
4444
+ print("Fix the agents above; the event manager carries on by itself once herdr finds them.")
4445
+ else:
4446
+ print("Every agent in the plan is found. Nothing to resume.")
4447
+ return
4448
+ beat = st["run"].get("beat")
4449
+ busy = [(tid, st["tasks"][tid]["wait"]) for tid in st["order"] if st["tasks"][tid].get("wait")]
4450
+ gap = account_downtime(st)
4451
+ save(st)
4452
+ if from_manager and not gap:
4453
+ return
4454
+ if gap and (busy or not from_manager):
4455
+ print(f"DOWN orch was not running from {_clock(beat)} to {_clock(now())} ({_dur(gap)}). That time is "
4456
+ f"not counted against any task or agent.")
4457
+ elif not from_manager:
4458
+ print("RESUME the event manager is not running" + (f" (last seen {_clock(beat)})" if beat else "") + ".")
4459
+ for tid, w in busy:
4460
+ print(f"WAS {tid} \"{st['tasks'][tid]['title']}\": {w['agent']} was "
4461
+ + ("reviewing it" if w.get("kind") == "reviewer" else "working on it"))
4462
+ rename_lost(st)
4463
+ for name, w in st["workers"].items():
4464
+ saved = save_stray(st, name)
4465
+ if saved:
4466
+ print(saved)
4467
+ for tid, w in busy:
4468
+ agent = w["agent"]
4469
+ if any(w.get(k) and Path(w[k]).exists() for k in ("sentinel", "report", "result")):
4470
+ print(f"DONE {tid}: {agent} had finished; the event manager takes it from here")
4471
+ continue
4472
+ if watched(st, agent):
4473
+ hs = herdr_state(agent)
4474
+ if hs is None:
4475
+ waiting.append((tid, agent))
4476
+ print(f"NOT SENT {tid}: {agent} is not found in herdr (see above)")
4477
+ continue
4478
+ if word(hs, "working", "blocked"):
4479
+ print(f"OK {tid}: {agent} is already "
4480
+ + ("at a question in its pane" if word(hs, "blocked") else "working"))
4481
+ continue
4482
+ w["delivering"], w["since"] = True, now() # recorded first, like every send: confirmed or sent again
4483
+ save(st)
4484
+ try:
4485
+ deliver(st, agent, (RESUME_REVIEWER if w.get("kind") == "reviewer" else RESUME_CODER) + w["prompt"])
4486
+ except DeliveryError as e:
4487
+ print(f"NOT SENT {tid} -> {agent}: {e} — the event manager sends it again")
4488
+ continue
4489
+ _delivered(st, agent)
4490
+ w["delivering"] = False
4491
+ save(st)
4492
+ print(f"RESENT {tid} -> {agent}: it carries on from the files in its folder")
4493
+ if from_manager:
4494
+ return
4495
+ if waiting:
4496
+ print("NOT STARTED: " + ", ".join(f"{a} ({t})" for t, a in waiting) + " must be running first. Do what the "
4497
+ "LOST lines say, then run `orch resume` again. (To go on without them, run `orch autopilot`: their "
4498
+ "milestones then move to another coder with the work so far.)")
4499
+ sys.exit(3)
4500
+ print(start_manager())
4501
+ if lead_on(st):
4502
+ print("The lead is woken with `orch events` when something needs it.")
4503
+
4504
+
3975
4505
  COMMANDS = {
4506
+ "resume": cmd_resume,
3976
4507
  "sync": cmd_sync, "start": cmd_start, "ready": cmd_ready, "pick": cmd_pick, "prepare": cmd_prepare,
3977
4508
  "setup-done": cmd_setup_done, "send": cmd_send, "review": cmd_review, "poll": cmd_poll, "bump": cmd_bump,
3978
4509
  "commit": cmd_commit, "merge": cmd_merge, "park": cmd_park, "cooldown": cmd_cooldown, "set": cmd_set,
@@ -3984,7 +4515,7 @@ COMMANDS = {
3984
4515
  "escalate": cmd_escalate, "fix": cmd_fix, "team": cmd_team,
3985
4516
  }
3986
4517
  # 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"}
4518
+ UNLOCKED = {"autopilot", "poll", "events", "dispatch", "answer", "fix", "team", "resume"}
3988
4519
 
3989
4520
  USAGE = """usage: orch <command> [args]
3990
4521
  version print the installed herdr-orchestra version
@@ -3998,6 +4529,8 @@ USAGE = """usage: orch <command> [args]
3998
4529
  agents launch <kind> [--model <id>] print the command that starts <kind> in a pane (auto-approve edits)
3999
4530
  models the model catalog: tiers (small / medium / high), ratings, and what policy forbids
4000
4531
  models show|check <id> one model's ratings and evidence / is it allowed?
4532
+ resume after a restart (computer off, herdr closed): name the agents' panes again, save unsaved
4533
+ work, re-send the tasks that were in progress and start the event manager
4001
4534
  events [--peek] (lead) what you were woken for; reading acknowledges it
4002
4535
  dispatch <Mn>... [--to <worker>] [--tier <tier>] (lead) start or restart milestones; starts the event manager
4003
4536
  answer <Mn> <text> (lead) the developer's answer: into plan.md, and back to the same coder
@@ -4027,7 +4560,7 @@ USAGE = """usage: orch <command> [args]
4027
4560
  set <Mn> <status> [reason] [--force] manual override: pending/paused/failed/skipped (others need --force)
4028
4561
  approve <Mn> let a milestone held for risky changes land (works while autopilot runs)
4029
4562
  cleanup remove clean worker worktrees
4030
- finish [--no-push] final check, drop hidden refs + worktrees, push the feature branch, open a PR into base
4563
+ finish [--no-push] [--recheck] final check (reused if it passed on these exact files), push, open a PR
4031
4564
  write-task <Mn> generate TASKDIR/task.md from plan.md (+ reports of merged dependencies)
4032
4565
  nudge <Mn> re-send the current prompt once to an agent that stopped early
4033
4566
  autopilot the event manager: watches agents, checks, merges, wakes the lead; exits 0 ALL_DONE, 3 when it needs you
@@ -4041,7 +4574,7 @@ USAGE = """usage: orch <command> [args]
4041
4574
  Exit codes: 2 error · 3 needs you / busy / cap · 4 merge conflict · 5 prompt not delivered (retried later) ·
4042
4575
  6 check fails on the feature branch (nothing committed) · 7 held for approval · 10 poll wait
4043
4576
  While `orch autopilot` runs it holds the driver lease: other commands that change the run are refused
4044
- (status, ready, pick, report, approve, fix and the lead's events / dispatch / answer still work).
4577
+ (status, ready, pick, report, approve, fix, resume and the lead's events / dispatch / answer still work).
4045
4578
  """
4046
4579
 
4047
4580
  # Env vars a Herdr pane carries. Agents whose tools run in a separate background process (Hermes runs