herdr-orchestra 5.4.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/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  All notable changes. Versions follow [semantic versioning](https://semver.org).
4
4
 
5
+ ## [5.5.0] - 2026-11-14
6
+
7
+ Found in a real run: the developer closed herdr and switched the computer off in the middle of a run, and came back 2 hours later. The panes were back, but the agents had no names and no conversations. The event manager was started again and paused the milestone at once as "over its time budget (121 min)". Dispatching it again failed with "has uncommitted changes — park or clean that worker first", and the work had to be saved with git by hand.
8
+
9
+ ### Added
10
+ - **`orch resume`: one command after a restart.** Run it once after a reboot or after closing herdr. It says how long orch was down, gives the agents' panes their names back, saves unsaved work, sends each task that was in progress to its agent again, and starts the event manager. You no longer resume each conversation and type "continue" in each pane: the task and the code are in files, so a fresh conversation carries on from them. Panes are found by folder: a coder's worktree is its own folder, so the pane in it is its pane (`NAMED opencode-1: pane w1:p3`). The reviewer and the lead sit in the main folder next to your own panes, so there a pane is renamed only when herdr shows the right agent kind; otherwise the exact command is printed (`herdr agent rename <pane> reviewer`). It is safe to run more than once, and it stops with exit 3 when an agent with work in progress is still missing. `orch autopilot` and the lead's `orch dispatch` do the same steps by themselves when the event manager starts after a gap.
11
+ - **`orch status` says loudly when nothing is watching the run.** When work is in progress and the event manager is not running, the first lines are `!! EVENT MANAGER NOT RUNNING since 11:42 (1h49m ago)` and `!! Run orch resume`. It used to be a few words at the end of the lead line. `orch start` points at `orch resume` when herdr can't find an agent.
12
+ - **A paused coder is told to stop.** When a milestone is paused or failed while its coder is still working, the coder gets one line: stop, don't change more files, your work is saved.
13
+
14
+ ### Fixed
15
+ - **Time orch was down no longer counts as working time.** The time budget was measured from the moment the prompt was sent, so 2 hours with the computer off were 2 hours of "work". The event manager now writes a heartbeat every loop. When it starts and the last heartbeat is older than `ORCH_DOWN_MIN_S` (120 seconds), the gap is taken out of every open task. Example: M4 was sent at 11:30, the computer went off at 11:42 and came back at 13:31. M4 counts 12 minutes, not 2 hours. The time report leaves that time out too and says so: `Not counted: 1h49m while orch was not running`. Real working time still counts as before. The same holds for a laptop that sleeps while the event manager stays up: the sleep is noticed (the wall clock moved on, the process did not run) and taken out, and the log says `the computer was asleep for 2h00m: that time is not counted against any task`. It is not charged to the run's `Budget:` either.
16
+ - **Unsaved work never blocks a task.** `orch prepare` refused a coder's folder that had uncommitted files, and a second `orch park` on an already parked milestone printed PARKED and saved nothing. So a paused coder that kept writing left the milestone stuck. Now `orch park`, `orch dispatch` and `orch prepare` always save what is in the folder first, into the milestone's saved work, and go on. Files orch can't give to a milestone (and files written after a milestone went to review, so nothing slips in behind the reviewer) are kept in a rescue ref whose name is printed, such as `refs/orch/feature-x/rescue-opencode-1-20261114-133100`. `orch finish` keeps rescue refs and lists them. Shared mode does the same for files written in the main folder after a pause; your own uncommitted files there are still left alone.
17
+ - **`orch team up` after a restart does not open a second pane next to the old one.** A pane that only lost its name gets it back, and a coder's pane that came back as a plain shell gets its agent started again in that pane.
18
+
19
+ Tested with simulated agents and a simulated herdr only. herdr's docs say `pane list` gives each pane's `cwd`, but not the exact JSON, so orch reads it loosely and falls back to printing the rename commands.
20
+
5
21
  ## [5.4.0] - 2026-11-14
6
22
 
7
23
  ### Fixed
package/README.md CHANGED
@@ -235,6 +235,8 @@ When a milestone passes its checks it's saved to its hidden ref and the coder is
235
235
  | A prompt can't be delivered | the task goes back in the queue (its job kept) and that agent is retried after 2 min; 3 in a row bench it for 30 min |
236
236
  | Attempts keep getting lost (unreachable, gone, rate-limited) | after 4 (`ORCH_MAX_LOST`) the task fails with the history instead of looping |
237
237
  | Autopilot is killed mid-step | the next run confirms or re-sends an unconfirmed prompt to the same agent, and finishes or undoes a half-done merge |
238
+ | The computer was off, herdr was closed, or the event manager died | `orch status` says so in its first lines. `orch resume` carries on: the time orch was down is not counted against any task, the agents' panes get their names back, unsaved work is saved and the tasks in progress are sent again (see [After a restart](#after-a-restart)) |
239
+ | A paused coder keeps writing files | it is told to stop; whatever it writes anyway is saved into the milestone the next time the milestone or that folder is used. orch never refuses a task because a folder has unsaved files |
238
240
  | Lockfiles changed since a folder was set up | the setup command runs again there (and in your main folder before the merge check) |
239
241
  | Risky change (deleted file, migration, CI config, secrets file, unlisted dependency change, very large diff) | the milestone is **held** until you run `orch approve Mn`; the rest keeps going |
240
242
  | The wake-up prompt never became a turn for the lead (it sat in the input box, or you were typing there) | sent again after 30s, then 1 min; after 3 tries you get a notification. The event manager does not leave at ALL_DONE before the lead has read the last events |
@@ -245,6 +247,25 @@ When a milestone passes its checks it's saved to its hidden ref and the coder is
245
247
  | Agent stops early | nudged once, then parked |
246
248
  | Worker writes `QUESTION:` | that task and its dependents wait, the lead is woken to answer or ask you; everything else continues |
247
249
 
250
+ ### After a restart
251
+ Nothing on a switched-off computer can restart itself, so after a reboot (or after closing herdr) one command is needed. Open herdr, then run in the repo:
252
+
253
+ ```bash
254
+ orch resume
255
+ ```
256
+
257
+ It does five things, and says what it did:
258
+
259
+ 1. **The time orch was down is not counted.** Example: M4 was sent at 11:30, the computer went off at 11:42 and came back at 13:31. M4 counts 12 minutes of work, not 2 hours, so it is not paused as "over its time budget", and the time report says `Not counted: 1h49m while orch was not running`. A laptop that only slept, with the event manager still up, is handled without any command: the sleep is taken out the same way.
260
+ 2. **Agents get their names back.** herdr brings the panes back, but not the agents' names, and orch reaches agents by name. `orch resume` finds each coder's pane by its folder and names it again (`NAMED opencode-1: pane w1:p3`). Where it can't decide (the reviewer and the lead sit in the main folder, next to your own panes), it prints the exact command: `herdr agent rename w1:p5 reviewer`. A pane that came back as a plain shell needs its agent started: `orch team up` does that in the same pane.
261
+ 3. **Unsaved work is saved** into the milestone it belongs to.
262
+ 4. **Each task that was in progress is sent to its agent again.** The agent's old conversation is not needed: the task and the code are in files, so a fresh conversation carries on from them. You don't have to type "continue" in each pane.
263
+ 5. **The event manager is started**, and it wakes the lead if events wait for it.
264
+
265
+ It is safe to run more than once. If an agent with work in progress is still missing, it stops and says what to do. `orch autopilot` and the lead's `orch dispatch` do steps 1 to 4 by themselves when they start the event manager after a gap.
266
+
267
+ orch can't bring an agent's old conversation back, and it can't start itself when the computer starts.
268
+
248
269
  ### Contracts and reports
249
270
  `plan.md` stays the file you edit. From it `orch` generates a `task.json` for each milestone (numbered acceptance criteria `AC1…`, allowed files, interfaces, the commits of its dependencies). Coders answer with a `result-N.json` (status, commit message, files changed, the check they ran, each criterion met or not), and the reviewer with a `review-N.json` (a verdict per criterion plus findings). The old line formats (`COMMIT:`, `QUESTION:`, `BLOCKER:`) still work as a fallback. The shapes are in [docs/contracts.md](docs/contracts.md).
250
271
 
@@ -253,9 +274,9 @@ Every status change is written to `.orchestrate/events.jsonl`, and `orch report
253
274
  Optional plan header lines: `Lead mode: events | off` (default `events` when the plan has a `Lead:` line) · `Scope: warn | strict` · `Risk hold: on | off` · `Budget: 3h` (autopilot stops when its running time is used up) · `Estimate: 1h30m` (the lead's estimate for the feature) · `Setup inputs: <globs>` (which files mean "run setup again"; default: lockfiles and manifests). Per milestone: `Why separate` (why it is its own milestone; needed when the plan has more than one) · `Tier`, `Needs`, `Model why` (see [Models and tiers](#models-and-tiers)) · `Estimate: 40m` (dispatch to landed if nothing goes wrong) · `Parallel: allow` lets it run next to a milestone that shares its `Likely files`.
254
275
 
255
276
  ### Commands
256
- `orch status` · `orch report` · `orch approve Mn` · `orch models [show|check <id>]` · `orch events [--peek]` · `orch dispatch Mn... [--to <worker>] [--tier <tier>]` · `orch answer Mn "<answer>"` · `orch fix Mn "<change>" [--to <worker>]` · `orch doctor [kind]` · `orch ready` · `orch autopilot` · `orch lead plan|run|check|whoami` · `orch agents [launch <kind> [--model <id>]|sync|check]` · `orch handoff Mn` · `orch needs-fix Mn` · `orch set M3 pending` · `orch park M2 paused "why"` · `orch cooldown claude-1 60` · `orch cleanup` · `orch finish [--no-push]` · `orch version` · `orch` (full help)
277
+ `orch status` · `orch resume` · `orch report` · `orch approve Mn` · `orch models [show|check <id>]` · `orch events [--peek]` · `orch dispatch Mn... [--to <worker>] [--tier <tier>]` · `orch answer Mn "<answer>"` · `orch fix Mn "<change>" [--to <worker>]` · `orch doctor [kind]` · `orch ready` · `orch autopilot` · `orch lead plan|run|check|whoami` · `orch agents [launch <kind> [--model <id>]|sync|check]` · `orch handoff Mn` · `orch needs-fix Mn` · `orch set M3 pending` · `orch park M2 paused "why"` · `orch cooldown claude-1 60` · `orch cleanup` · `orch finish [--no-push]` · `orch version` · `orch` (full help)
257
278
 
258
- Tunables: `ORCH_CODER_BUDGET_MIN` (45) · `ORCH_REVIEW_BUDGET_MIN` (15) · `ORCH_CHECK_TIMEOUT_MIN` (30) · `ORCH_COOLDOWN_MIN` (60) · `ORCH_MAX_TASKS` (unset: no limit) · `ORCH_GONE_COOLDOWN_MIN` (10) · `ORCH_SEND_RETRY_S` (120) · `ORCH_HERDR_TIMEOUT_S` (30) · `ORCH_MAX_LOST` (4) · `ORCH_UNREACHABLE_MIN` (30) · `ORCH_CONFIRM_S` (30) · `ORCH_RISK_MAX_LINES` (1500) · `ORCH_LEAD_WAIT_MIN` (15: ready work the lead hasn't dispatched starts by itself) · `ORCH_LEAD_CONFIRM_S` (30: a wake-up the lead did not pick up is sent again, doubling) · `ORCH_LEAD_REWAKE_S` (300) · `ORCH_LEAD_MAX_WAKES` (3) · `ORCH_LEAD_IDLE_MAX_MIN` (720: how long the event manager waits for an answer) · `ORCH_NO_AUTOSTART=1` (the lead's commands never start the event manager)
279
+ Tunables: `ORCH_CODER_BUDGET_MIN` (45) · `ORCH_REVIEW_BUDGET_MIN` (15) · `ORCH_CHECK_TIMEOUT_MIN` (30) · `ORCH_COOLDOWN_MIN` (60) · `ORCH_MAX_TASKS` (unset: no limit) · `ORCH_GONE_COOLDOWN_MIN` (10) · `ORCH_SEND_RETRY_S` (120) · `ORCH_HERDR_TIMEOUT_S` (30) · `ORCH_MAX_LOST` (4) · `ORCH_UNREACHABLE_MIN` (30) · `ORCH_CONFIRM_S` (30) · `ORCH_DOWN_MIN_S` (120: an event manager silent for longer was down, and that time is not counted) · `ORCH_RISK_MAX_LINES` (1500) · `ORCH_LEAD_WAIT_MIN` (15: ready work the lead hasn't dispatched starts by itself) · `ORCH_LEAD_CONFIRM_S` (30: a wake-up the lead did not pick up is sent again, doubling) · `ORCH_LEAD_REWAKE_S` (300) · `ORCH_LEAD_MAX_WAKES` (3) · `ORCH_LEAD_IDLE_MAX_MIN` (720: how long the event manager waits for an answer) · `ORCH_NO_AUTOSTART=1` (the lead's commands never start the event manager)
259
280
 
260
281
  ## Develop and release
261
282
 
package/VERSION CHANGED
@@ -1 +1 @@
1
- 5.4.0
1
+ 5.5.0
Binary file
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,6 +4449,8 @@ 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
@@ -4041,7 +4494,7 @@ USAGE = """usage: orch <command> [args]
4041
4494
  Exit codes: 2 error · 3 needs you / busy / cap · 4 merge conflict · 5 prompt not delivered (retried later) ·
4042
4495
  6 check fails on the feature branch (nothing committed) · 7 held for approval · 10 poll wait
4043
4496
  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).
4497
+ (status, ready, pick, report, approve, fix, resume and the lead's events / dispatch / answer still work).
4045
4498
  """
4046
4499
 
4047
4500
  # Env vars a Herdr pane carries. Agents whose tools run in a separate background process (Hermes runs
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-orchestra",
3
- "version": "5.4.0",
3
+ "version": "5.5.0",
4
4
  "description": "Orchestrate AI coding agents (Claude Code, Codex, OpenCode, Amp) as one team in Herdr: a lead plans, coders build in parallel, a reviewer checks, you get one PR.",
5
5
  "license": "MIT",
6
6
  "bin": {
package/playbooks/run.md CHANGED
@@ -45,6 +45,7 @@ Run `orch events`. It lists the new events, the ones still open, the milestones
45
45
  | `NEEDS-ANSWER Mn` | Open questions in the plan: ask the developer, write the answers under "Notes from user", set "Open questions:" to `- none`, `orch sync`, then `orch dispatch Mn`. |
46
46
  | `ESCALATED Mn`, `AUTO-DISPATCHED Mn` | Information. Mention an escalation in the final summary. |
47
47
  | `STOPPED` / the event manager is not running | Read the last lines of `.orchestrate/autopilot.log` and tell the developer why (a red baseline, the run's budget, the branch failing its check). Your next `orch dispatch` or `orch answer` starts it again; so does `orch autopilot` in a terminal. |
48
+ | `orch status` starts with `!! EVENT MANAGER NOT RUNNING`, or the developer says the computer or herdr was restarted | Run `orch resume` once and read what it prints. It leaves the time orch was down out of every time budget, gives the agents' panes their names back, saves unsaved work, sends the tasks in progress to their agents again and starts the event manager. For each `LOST` line, give the developer the exact command it prints (`herdr agent rename <pane> <name>`, or `orch team up` for a pane with no agent in it), then run `orch resume` again. Never fix this with git by hand, and never prompt a coder yourself. |
48
49
  | `ALL_DONE` | Section 3. |
49
50
 
50
51
  If you changed plan.md by hand, run `orch sync` (it works once the event manager is idle; `orch answer` and `orch dispatch` work at any time).