herdr-orchestra 6.2.1 → 6.3.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,23 @@
2
2
 
3
3
  All notable changes. Versions follow [semantic versioning](https://semver.org).
4
4
 
5
+ ## [6.3.0] - 2026-11-21
6
+
7
+ Moving a milestone away from a coder now really stops that coder. Before, `orch set M7 paused` only typed a STOP note into the coder's pane and marked the coder free at once. An agent in the middle of a step (agy, for example) only reads a typed message after that step, so it kept editing files while `orch status` showed it as free, and it could be handed the next milestone.
8
+
9
+ ### Fixed
10
+ - **A paused or moved milestone's coder is interrupted, and stays busy until it has stopped.** orch first presses the agent's interrupt key (Esc, like you would), waits a few seconds for it to go idle, then types the STOP note. Until herdr shows the coder idle (and it stays idle for 10 seconds), `orch status` shows `state=stopping M7 (told to stop 0m40s ago ...)`, it is not picked for new work, and `orch prepare` refuses it (`BUSY rs-agy-1 is still stopping M7`). If it is still working 90 seconds later, the event manager presses the key again (twice at most) and says so in the log. Example: `orch set M7 paused` prints `STOP_NOTE M7 -> rs-agy-1: interrupted (esc) and told to stop ...` and `STOPPING rs-agy-1: herdr still shows it working; it stays busy ...`. For an agent herdr can't watch, orch says to look at its pane before giving it new work.
11
+ - **`orch team up` no longer renames the lead's pane.** When the reviewer's pane was missing, team up looked for a pane of the same kind in the repo folder and could pick the lead's own pane, name it `rs-reviewer`, and then `orch start` refused with NO LEAD. The lead's pane, and the pane you run `orch team up` in, are never given a coder's or the reviewer's name now.
12
+ - **`orch lead whoami` and `orch lead run` keep the plan's lead name.** `whoami` always named the pane `lead`; `lead run` used the name from the last `orch sync`. Both now use `Lead:` from plan.md (then the run's state, then `lead`), so `Lead: rs-lead` stays `rs-lead`.
13
+ - **`--help` never runs the command.** `orch team up --help` used to open panes. Now `orch <command> --help` (or `-h`) prints that command's help and exits; `orch --help` exits 0.
14
+ - **The reviewer starts in the repo folder.** herdr can start a split pane in the folder of the pane it splits from (a coder's worktree), so team up now starts each agent with `cd <its folder> && <launch command>`.
15
+
16
+ ### Added
17
+ - **`orch free <worker>`**: you checked the pane and the coder that was told to stop has stopped, so it can take work again now.
18
+ - **`interrupt_keys` in the agent registry**, per kind, as herdr names keys: `["esc"]` for Claude Code, Codex, agy, Amp and Hermes, `["esc", "esc"]` for OpenCode, and `["esc"]` for Pi and for any kind that does not set it. Override it in `~/.config/herdr-orchestra/agents.toml`.
19
+ - **`orch sync` warns when plan.md changed under a running milestone.** A coder works from the task.md it got, which is not rewritten mid-work, so an edit to that milestone's plan text does not reach it by itself. sync now says, for example, `WARN: M7 changed in plan.md, but rs-claude-1 is already working from its old task.md ... orch set M7 paused, then orch dispatch M7`. Answers (`Notes from user`) still reach the coder as before and give no warning.
20
+ - `orch status` says `free, but herdr shows it working` for a coder with no task whose pane is busy.
21
+ - Tests (section 49): the interrupt key before the STOP note; the stopping coder is not free in status, pick, prepare or ready; the event manager presses the key again; it is free once idle; `orch free`; the interrupt keys per kind; team up leaves the lead's pane and its own pane alone; the reviewer starts with `cd` into the repo; whoami and lead run use the plan's lead name; `--help` and `-h` run nothing; the plan-changed warning. Section 44's whoami test now expects the plan's lead name instead of `lead`.
5
22
  ## [6.2.1] - 2026-11-21
6
23
 
7
24
  Fixes `/orch-setup` and `/orch-mode` not working in Pi when an older `orch` is already on the machine.
package/README.md CHANGED
@@ -305,7 +305,9 @@ A subagent run: `/orch-plan` as usual (the plan's team is `Workers: coder (pi)`,
305
305
  | Attempts keep getting lost (unreachable, gone, rate-limited) | after 4 (`ORCH_MAX_LOST`) the task fails with the history instead of looping |
306
306
  | 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 |
307
307
  | 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)) |
308
- | 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 |
308
+ | A milestone is paused or moved while its coder still works | orch presses the agent's interrupt key (Esc; set per agent kind as `interrupt_keys` in the registry), then types the STOP note. The coder shows as `stopping M7` in `orch status` and gets no new work until herdr shows it idle; the event manager presses the key again if it keeps going. `orch free <worker>` frees it once you have checked its pane |
309
+ | A paused coder keeps writing files | 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 |
310
+ | plan.md changed while a coder works on that milestone | its task.md is not rewritten mid-work; `orch sync` warns and says how to send the new text (`orch set Mn paused`, then `orch dispatch Mn`) |
309
311
  | Lockfiles changed since a folder was set up | the setup command runs again there (and in your main folder before the merge check) |
310
312
  | 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 |
311
313
  | 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 |
package/VERSION CHANGED
@@ -1 +1 @@
1
- 6.2.1
1
+ 6.3.0
@@ -6,6 +6,9 @@
6
6
  # model_flag the launch option that picks the model (`orch agents launch <kind> --model <id>`); leave it
7
7
  # out when the tool has none or it is unverified, and choose the model inside the tool
8
8
  # herdr_detect herdr can tell idle / working / blocked for it (false: orch relies on the done file only)
9
+ # interrupt_keys the keys that stop its current step, as `herdr agent send-keys` names them (default ["esc"]).
10
+ # orch presses them when a milestone is paused or moved while the coder still works, before the
11
+ # STOP note: a typed message is only read after the current step (agy queues it)
9
12
  # roles any of "lead", "coder", "reviewer"
10
13
  # skills_dirs global SKILL.md folders the installer may put the thin orch-plan / orch-run skills into
11
14
  # (first = preferred)
@@ -31,6 +34,7 @@ binary = "claude"
31
34
  launch = "claude --permission-mode acceptEdits"
32
35
  model_flag = "--model"
33
36
  herdr_detect = true
37
+ interrupt_keys = ["esc"]
34
38
  roles = ["lead", "coder", "reviewer"]
35
39
  skills_dirs = ["~/.claude/skills"]
36
40
  skills_one_wins = true
@@ -44,6 +48,7 @@ binary = "codex"
44
48
  launch = "codex --approve-for-me"
45
49
  model_flag = "--model"
46
50
  herdr_detect = true
51
+ interrupt_keys = ["esc"]
47
52
  roles = ["lead", "coder", "reviewer"]
48
53
  skills_dirs = ["~/.agents/skills", "~/.codex/skills"]
49
54
  skills_reads = ["~/.agents/skills", "~/.codex/skills"]
@@ -55,6 +60,7 @@ notes = "codex-cli 0.167: --full-auto is gone; --approve-for-me routes approvals
55
60
  binary = "amp"
56
61
  launch = "amp"
57
62
  herdr_detect = true
63
+ interrupt_keys = ["esc"]
58
64
  roles = ["lead", "coder", "reviewer"]
59
65
  skills_dirs = ["~/.config/agents/skills", "~/.agents/skills"]
60
66
  skills_reads = ["~/.config/agents/skills", "~/.agents/skills"]
@@ -68,6 +74,7 @@ binary = "opencode"
68
74
  launch = "opencode"
69
75
  model_flag = "--model"
70
76
  herdr_detect = true
77
+ interrupt_keys = ["esc", "esc"]
71
78
  roles = ["lead", "coder", "reviewer"]
72
79
  skills_dirs = []
73
80
  skills_reads = ["~/.agents/skills", "~/.claude/skills"]
@@ -83,6 +90,7 @@ notes = "Reads ~/.agents/skills and ~/.claude/skills, so only its slash commands
83
90
  binary = "hermes"
84
91
  launch = "hermes"
85
92
  herdr_detect = true
93
+ interrupt_keys = ["esc"]
86
94
  roles = ["lead", "coder", "reviewer"]
87
95
  skills_dirs = ["~/.hermes/skills"]
88
96
  invoke = "use the orch-plan skill: <feature>"
@@ -93,6 +101,7 @@ notes = "Not installed on the machine this was written on: launch flag and skill
93
101
  binary = "agy"
94
102
  launch = "agy --mode accept-edits"
95
103
  herdr_detect = true
104
+ interrupt_keys = ["esc"]
96
105
  roles = ["lead", "coder", "reviewer"]
97
106
  skills_dirs = ["~/.gemini/config/skills"]
98
107
  invoke = "use the orch-plan skill: <feature>"
@@ -104,6 +113,7 @@ binary = "pi"
104
113
  launch = "pi"
105
114
  model_flag = "--model"
106
115
  herdr_detect = false
116
+ interrupt_keys = ["esc"]
107
117
  roles = ["lead", "coder", "reviewer"]
108
118
  skills_dirs = ["~/.agents/skills"]
109
119
  skills_reads = ["~/.pi/agent/skills", "~/.agents/skills"]
package/bin/orch CHANGED
@@ -36,6 +36,11 @@ LEAD_WAIT_S = int(os.environ.get("ORCH_LEAD_WAIT_MIN", "15")) * 60 # ready wor
36
36
  LEAD_IDLE_MAX_S = int(os.environ.get("ORCH_LEAD_IDLE_MAX_MIN", "720")) * 60 # give up waiting for answers after this
37
37
  DOWN_MIN_S = int(os.environ.get("ORCH_DOWN_MIN_S", "120")) # the event manager silent for longer than this was down
38
38
  STOP_WAIT_S = float(os.environ.get("ORCH_STOP_WAIT_S", "60")) # `orch stop` waits this long for the step it is on
39
+ # a coder whose milestone is paused or moved away while it works: it gets the interrupt key, and stays busy
40
+ # ("stopping") until herdr shows it idle for this long, so nobody hands it new work while it still edits files
41
+ HALT_WAIT_S = float(os.environ.get("ORCH_HALT_WAIT_S", "5")) # `orch set/park` waits this long for it to go idle
42
+ HALT_SETTLE_S = float(os.environ.get("ORCH_HALT_SETTLE_S", "10")) # idle at least this long after the stop note
43
+ HALT_REPEAT_S = float(os.environ.get("ORCH_HALT_REPEAT_S", "90")) # still working after this: interrupt it again
39
44
  TEAM_CONFIRM_S = float(os.environ.get("ORCH_TEAM_CONFIRM_S", "5")) # `team up` looks again after this: still running?
40
45
  LOG_MAX_B = int(float(os.environ.get("ORCH_LOG_MAX_MB", "2")) * 1024 * 1024) # autopilot.log; one old copy is kept
41
46
  CRASH_KEEP = int(os.environ.get("ORCH_CRASH_KEEP", "20")) # saved agent screens in .orchestrate/crash/
@@ -163,7 +168,7 @@ def state_lock():
163
168
 
164
169
  # usable while autopilot drives: reads, and the lead's requests (the event manager carries them out)
165
170
  LEASE_FREE = {"status", "ready", "pick", "report", "approve", "autopilot", "events", "dispatch", "answer", "defer",
166
- "fix", "team", "resume", "bench", "stop", "doctor", "plan", "story", "check"}
171
+ "fix", "team", "resume", "bench", "stop", "doctor", "plan", "story", "check", "free"}
167
172
  _LEASE = None
168
173
 
169
174
 
@@ -1325,6 +1330,7 @@ def cmd_sync(args):
1325
1330
  st["workers"][name] = {"kind": kind, "task": ow.get("task"), "cooldown_until": ow.get("cooldown_until", 0),
1326
1331
  "cooldown_reason": ow.get("cooldown_reason", ""),
1327
1332
  **({"off": ow["off"]} if ow.get("off") else {}), # kept until `orch bench <w> on`
1333
+ **({"stopping": ow["stopping"]} if ow.get("stopping") else {}), # told to stop
1328
1334
  "dir": ow.get("dir"), "setup_done": ow.get("setup_done", False),
1329
1335
  "setup_hash": ow.get("setup_hash"), "delivery_fails": ow.get("delivery_fails", 0),
1330
1336
  "pane": pane, "detect": detect(kind, pane, "Workers"),
@@ -1375,6 +1381,14 @@ def cmd_sync(args):
1375
1381
  rb = st["tasks"].get(st["reviewer_busy"]) if st.get("reviewer_busy") else None
1376
1382
  if st.get("reviewer_busy") and (rb is None or rb["status"] != "reviewing"):
1377
1383
  st["reviewer_busy"] = None
1384
+ # a coder works from the task.md it got; a plan.md edit made meanwhile does not reach it by itself
1385
+ secs_, glob_ = plan_sections()
1386
+ for tid, t in st["tasks"].items():
1387
+ if t.get("task_src") and holds(st, tid) and tid in secs_ and task_source(secs_[tid], glob_) != t["task_src"]:
1388
+ warns.append(f"{tid} changed in plan.md, but {t['worker']} is already working from its old task.md, which "
1389
+ f"is not rewritten while it works. To give it the new text: `orch set {tid} paused`, then "
1390
+ f"`orch dispatch {tid}` (its work so far is kept). Or let it finish and send the change "
1391
+ f"after it lands: `orch fix {tid} \"<the change>\"`")
1378
1392
  migrate(st)
1379
1393
  save(st)
1380
1394
  for w in warns:
@@ -1528,20 +1542,85 @@ def shared_fold(st, tid):
1528
1542
  f"are kept in {keep} (`git stash show -p {new[:12]}` to look); {tid} keeps its earlier saved work")
1529
1543
 
1530
1544
 
1531
- def stop_note(st, agent, tid, status, reason):
1532
- """Tell a coder whose milestone was just paused or failed to stop. Only when it is (or may be) still working;
1533
- whatever it writes anyway is saved the next time the milestone or its folder is used."""
1534
- if watched(st, agent):
1545
+ def interrupt_keys(kind):
1546
+ """The keys that stop the agent's current step (a registry setting per kind, `interrupt_keys`); default Esc."""
1547
+ v = (registry(required=False) or {}).get(kind) or {}
1548
+ keys = v.get("interrupt_keys")
1549
+ return [str(k) for k in keys] if isinstance(keys, list) and keys else ["esc"]
1550
+
1551
+
1552
+ def interrupt(st, agent):
1553
+ """Press the agent's interrupt key(s) in its pane, like a person pressing Esc. A typed message is not a stop:
1554
+ an agent busy with a step only reads it after that step (agy queues it), so the key comes first.
1555
+ Returns the keys sent, or None when herdr could not send them."""
1556
+ info = agent_info(st, agent)
1557
+ keys = interrupt_keys(info.get("kind"))
1558
+ pane = info.get("pane")
1559
+ try:
1560
+ _herdr_run([HERDR, "pane", "send-keys", pane, *keys] if pane else [HERDR, "agent", "send-keys", agent, *keys])
1561
+ except DeliveryError:
1562
+ return None
1563
+ return keys
1564
+
1565
+
1566
+ def busy_word(s):
1567
+ return word(s, "working", "blocked")
1568
+
1569
+
1570
+ def stop_coder(st, agent, tid, status, reason):
1571
+ """Stop a coder whose milestone was just paused or failed (or moved to another coder). Only when it is (or may
1572
+ be) still working. It gets the interrupt key first, then the STOP note; whatever it writes anyway is saved the
1573
+ next time the milestone or its folder is used. Returns None (nothing to stop) or
1574
+ {"keys": [...] or None, "idle": bool, "note": bool, "watched": bool}."""
1575
+ watch = watched(st, agent)
1576
+ if watch:
1535
1577
  s = herdr_state(agent)
1536
- if s is None or not word(s, "working"):
1537
- return False
1578
+ if s is None or not busy_word(s):
1579
+ return None
1580
+ keys = interrupt(st, agent)
1581
+ idle = False
1582
+ if watch:
1583
+ end = time.time() + (0 if os.environ.get("ORCH_DRIVER") else HALT_WAIT_S) # the event manager never waits
1584
+ while True:
1585
+ s = herdr_state(agent)
1586
+ if s is None or not busy_word(s):
1587
+ idle = True
1588
+ break
1589
+ if time.time() >= end:
1590
+ break
1591
+ time.sleep(0.5)
1538
1592
  why = " ".join((reason or status).split())[:160]
1539
1593
  try:
1540
- deliver(st, agent, f"STOP: {tid} is {status} ({why}). Stop working on it now and do not change any more "
1541
- f"files. What you did so far is saved. You get a new prompt if it continues.")
1594
+ deliver(st, agent, f"STOP: {tid} is {status} ({why}). orch interrupted you: stop working on it now and do "
1595
+ f"not change any more files. What you did so far is saved. You get a new prompt if it "
1596
+ f"continues.")
1597
+ note = True
1542
1598
  except DeliveryError:
1599
+ note = False
1600
+ return {"keys": keys, "idle": idle, "note": note, "watched": watch}
1601
+
1602
+
1603
+ def still_stopping(st, name, w=None):
1604
+ """True while a coder that was told to stop may still be working: herdr shows it working (or blocked), or it
1605
+ went idle less than ORCH_HALT_SETTLE_S after the stop. Such a coder is busy: it gets no new work."""
1606
+ w = w if w is not None else st["workers"].get(name) or {}
1607
+ h = w.get("stopping")
1608
+ if not h or not w.get("detect", True):
1543
1609
  return False
1544
- return True
1610
+ s = herdr_state(name)
1611
+ if s is None: # no agent left in herdr: nothing is running there
1612
+ return False
1613
+ if busy_word(s):
1614
+ return True
1615
+ # idle now: free once it has stayed idle long enough. The event manager records since when it has seen it idle
1616
+ # (a working reading in between starts the count again), so one idle blink between two steps does not free it
1617
+ return now() - (h.get("idle_since") or h.get("ts", 0)) < HALT_SETTLE_S
1618
+
1619
+
1620
+ def stopping_line(st, name, w):
1621
+ h = w.get("stopping") or {}
1622
+ return (f"stopping {h.get('task') or '?'} (told to stop {_fmt_secs(now() - h.get('ts', now()))} ago; "
1623
+ f"it gets no new work until herdr shows it idle — `orch free {name}` if you checked its pane)")
1545
1624
 
1546
1625
 
1547
1626
  def commit_message(st, tid):
@@ -1934,6 +2013,7 @@ def cmd_ready(args):
1934
2013
  slots = 1 # shared mode: a queued fix job IS the active milestone, and it needs a coder
1935
2014
  # only coders herdr can see count as free: a coder with no agent can't take work, whatever its task field says
1936
2015
  present = [n for n, w in st["workers"].items() if not w.get("task") and not w.get("off") and not cooling(n, w)
2016
+ and not still_stopping(st, n, w)
1937
2017
  and (not w.get("detect", True) or w.get("pane") or herdr_state(n) is not None)]
1938
2018
  gone = [n for n, w in st["workers"].items() if not w.get("task") and not w.get("off") and w.get("detect", True)
1939
2019
  and not w.get("pane") and herdr_state(n) is None]
@@ -1959,7 +2039,7 @@ def cooling(name, info):
1959
2039
 
1960
2040
 
1961
2041
  def worker_free(st, name, w):
1962
- if w.get("task") or w.get("off") or cooling(name, w):
2042
+ if w.get("task") or w.get("off") or cooling(name, w) or still_stopping(st, name, w):
1963
2043
  return False
1964
2044
  if not w.get("detect", True): # herdr can't watch it: no task + no cooldown = free
1965
2045
  return True
@@ -1998,6 +2078,12 @@ def cmd_prepare(args):
1998
2078
  die(f"{tid} is {t['status']}, expected pending/paused/needs-fix/conflict")
1999
2079
  if w.get("task") and w["task"] != tid:
2000
2080
  die(f"{worker} is busy with {w['task']}")
2081
+ if still_stopping(st, worker, w):
2082
+ print(f"BUSY {worker} is still stopping {w['stopping'].get('task')}: herdr shows it working, or it stopped "
2083
+ f"less than {int(HALT_SETTLE_S)}s ago. Try again when `orch status` shows it free "
2084
+ f"(or `orch free {worker}` after you checked its pane)")
2085
+ sys.exit(3)
2086
+ w.pop("stopping", None)
2001
2087
  if not holds(st, tid) and free_slots(st) <= 0 and not (st["isolation"] == "shared" and t["status"] in ("conflict", "needs-fix")):
2002
2088
  die("no free slot (max parallel reached)")
2003
2089
  d = Path(w["dir"] or ROOT)
@@ -2849,8 +2935,24 @@ def _park(st, tid, status, reason, force=False):
2849
2935
  move(st, tid, status, reason, force=force)
2850
2936
  t["wait"] = None
2851
2937
  save(st)
2852
- if note_to and stop_note(st, note_to, tid, status, reason):
2853
- print(f"STOP_NOTE {tid} -> {note_to}: told to stop and not change more files")
2938
+ if note_to:
2939
+ res = stop_coder(st, note_to, tid, status, reason)
2940
+ if res:
2941
+ keys = "+".join(res["keys"]) if res["keys"] else None
2942
+ if res["note"]:
2943
+ print(f"STOP_NOTE {tid} -> {note_to}: " + (f"interrupted ({keys}) and " if keys else "")
2944
+ + "told to stop and not change more files")
2945
+ if res["watched"]:
2946
+ st["workers"][note_to]["stopping"] = {"task": tid, "ts": now(), "keys": res["keys"] or [],
2947
+ "again": 0}
2948
+ save(st)
2949
+ print(f"STOPPING {note_to}: " + ("herdr shows it idle now; " if res["idle"] else
2950
+ "herdr still shows it working; ") + f"it stays busy (no new work) until it has been idle "
2951
+ f"{int(HALT_SETTLE_S)}s. `orch status` says when it is free"
2952
+ + ("" if keys else f" — the interrupt key could not be sent: press Esc in its pane"))
2953
+ else:
2954
+ print(f"CHECK {note_to}: herdr can't watch {agent_info(st, note_to).get('kind')}, so orch can't "
2955
+ f"tell when it has stopped: look at its pane before you give it new work")
2854
2956
 
2855
2957
 
2856
2958
  def cmd_park(args):
@@ -2920,6 +3022,22 @@ def cmd_bench(args):
2920
3022
  print("WARN every coder is off now: nothing new starts until one is back on")
2921
3023
 
2922
3024
 
3025
+ def cmd_free(args):
3026
+ """orch free <worker> -> you looked at its pane: the coder that was told to stop HAS stopped, so it can take work
3027
+ again now (orch otherwise waits until herdr shows it idle)."""
3028
+ need(args, 1, "free <worker>")
3029
+ name = args[0]
3030
+ with state_lock():
3031
+ st = load()
3032
+ w = st["workers"].get(name) or die(f"unknown worker {name!r} — workers: {', '.join(st['workers'])}")
3033
+ if w.get("task"):
3034
+ die(f"{name} holds {w['task']}: to take it away, `orch set {w['task']} paused` (it is then told to stop)")
3035
+ h = w.pop("stopping", None)
3036
+ save(st)
3037
+ print(f"FREE {name}: " + (f"no longer waits to stop {h.get('task')}; it can take new work" if h else
3038
+ "it was not stopping anything"))
3039
+
3040
+
2923
3041
  def cmd_stop(args):
2924
3042
  """orch stop [--now] -> stop the event manager cleanly: it finishes the step it is on (a check, a merge) and
2925
3043
  exits; every event and all work are kept. Then change the run (plan.md + `orch sync`, `orch team up`) and
@@ -3003,7 +3121,10 @@ def cmd_status(args):
3003
3121
  h = here[n]
3004
3122
  state = ("OFF (" + (w["off"].get("why") or "developer") + ")" if w.get("off") else
3005
3123
  f"coding {w['task']}" if w.get("task") else
3124
+ stopping_line(st, n, w) if still_stopping(st, n, w) else
3006
3125
  f"benched {cd // 60}m ({w.get('cooldown_reason') or 'cooldown'})" if cd else "free")
3126
+ if state == "free" and h == "ok" and w.get("detect", True) and busy_word(herdr_state(n)):
3127
+ state = "free, but herdr shows it working: look at its pane before it gets new work"
3007
3128
  print(f" worker {n:<12} {w['kind']:<8} task={w.get('task') or '-':<5} "
3008
3129
  + (f"model={w['model']} ({w.get('tier') or 'unrated'}) " if w.get("model") else "")
3009
3130
  + f"{'cooldown ' + str(cd // 60) + 'm' if cd else ''}"
@@ -3218,6 +3339,18 @@ def cmd_finish(args):
3218
3339
 
3219
3340
 
3220
3341
  # ---------------------------------------------------------------- v4: task files, nudge, autopilot
3342
+ TASK_SRC_SKIP = ("notes from user", "plain") # answers reach the coder by their own prompt; Plain is not in task.md
3343
+
3344
+
3345
+ def task_source(section, glob=""):
3346
+ """A fingerprint of what task.md is written from (the milestone's plan text + Global instructions), so `orch
3347
+ sync` can tell when plan.md changed under a coder that is already working from an older task.md."""
3348
+ _, ts = parse_plan(section)
3349
+ f = {k: v for k, v in (ts[0]["fields"] if ts else {}).items() if k not in TASK_SRC_SKIP}
3350
+ title = ts[0]["title"] if ts else section.split("\n", 1)[0]
3351
+ return hashlib.sha1(json.dumps([title, f, glob.strip()], sort_keys=True).encode()).hexdigest()[:12]
3352
+
3353
+
3221
3354
  def plan_sections():
3222
3355
  """Return ({task_id: section_text}, global_instructions_text) straight from plan.md."""
3223
3356
  text = (ORCH / "plan.md").read_text()
@@ -3324,6 +3457,8 @@ def cmd_write_task(args):
3324
3457
  out.parent.mkdir(parents=True, exist_ok=True)
3325
3458
  out.write_text("\n".join(parts))
3326
3459
  (out.parent / "task.json").write_text(json.dumps(contract, indent=2))
3460
+ t["task_src"] = task_source(secs[tid], glob)
3461
+ save(st)
3327
3462
  print(f"WROTE {out}")
3328
3463
  print(f"WROTE {out.parent / 'task.json'}")
3329
3464
 
@@ -3419,6 +3554,9 @@ def cmd_dispatch(args):
3419
3554
  if st["workers"][to].get("off"):
3420
3555
  die(f"{to} is off ({st['workers'][to]['off'].get('why')}): `orch bench {to} on` first, or pick another "
3421
3556
  f"worker")
3557
+ if still_stopping(st, to):
3558
+ print(f"NOTE {to} is still stopping {st['workers'][to]['stopping'].get('task')}: the work starts "
3559
+ f"there once herdr shows it idle (`orch status`)")
3422
3560
  here = presence_word(st, to)
3423
3561
  if here not in ("ok", "detect:off"):
3424
3562
  die(f"{to} has no agent in herdr ({here}" + (": only a plain shell is left in its pane" if here ==
@@ -4759,8 +4897,43 @@ def _autopilot(args):
4759
4897
  elif t["status"] == "committed":
4760
4898
  land(tid)
4761
4899
 
4900
+ def tend_stops():
4901
+ """Coders told to stop: free once herdr shows them idle; interrupted again (twice at most) if they keep going."""
4902
+ st_ = load()
4903
+ for n, w in st_["workers"].items():
4904
+ h = w.get("stopping")
4905
+ if not h:
4906
+ continue
4907
+ s = herdr_state(n) if w.get("detect", True) else None
4908
+ busy = s is not None and busy_word(s)
4909
+ if busy and h.get("idle_since"):
4910
+ h["idle_since"] = None
4911
+ patch_state(lambda s_, n=n: n in s_["workers"] and s_["workers"][n].get("stopping") is not None
4912
+ and s_["workers"][n]["stopping"].update(idle_since=None))
4913
+ elif s is not None and not busy and not h.get("idle_since"):
4914
+ h["idle_since"] = now()
4915
+ patch_state(lambda s_, n=n, t=h["idle_since"]: n in s_["workers"]
4916
+ and s_["workers"][n].get("stopping") is not None
4917
+ and s_["workers"][n]["stopping"].update(idle_since=t))
4918
+ if not still_stopping(st_, n, w):
4919
+ patch_state(lambda s_, n=n: n in s_["workers"] and s_["workers"][n].pop("stopping", None))
4920
+ say(f"STOPPED {n}: it is idle after the stop for {h.get('task')}, so it can take new work")
4921
+ continue
4922
+ if now() - h.get("last", h.get("ts", 0)) >= HALT_REPEAT_S and h.get("again", 0) < 2:
4923
+ keys = interrupt(st_, n)
4924
+ patch_state(lambda s_, n=n: n in s_["workers"] and s_["workers"][n].get("stopping") is not None
4925
+ and s_["workers"][n]["stopping"].update(again=h.get("again", 0) + 1, last=now()))
4926
+ say(f"{n} is still working {_fmt_secs(now() - h.get('ts', now()))} after it was told to stop "
4927
+ f"{h.get('task')}: " + (f"pressed {'+'.join(keys)} again" if keys else
4928
+ "the interrupt key could not be sent")
4929
+ + f". It gets no new work until it is idle; look at its pane (`orch free {n}` once it has "
4930
+ f"stopped)", h.get("again", 0) >= 1)
4931
+
4762
4932
  def dispatch(kind, tid, worker):
4763
- _, prep = run("prepare", tid, worker)
4933
+ code, prep = run("prepare", tid, worker, ok=(0, 3))
4934
+ if code == 3: # the coder is busy after all (still stopping its last milestone): next loop
4935
+ say(f"{tid}: {worker} is not free yet ({prep.splitlines()[-1][:160] if prep else 'busy'}) — tried again soon")
4936
+ return
4764
4937
  if "SETUP_NEEDED" in prep:
4765
4938
  d = load()["tasks"][tid]["dir"]
4766
4939
  say(f"installing dependencies in {d}" + (" (dependency files changed)" if "changed" in prep else ""))
@@ -4956,6 +5129,7 @@ def _autopilot(args):
4956
5129
  procs = run_processes(st)
4957
5130
  patch_state(lambda s_: (s_["run"].get("manager") or {}).update(procs))
4958
5131
  watch_herdr()
5132
+ tend_stops()
4959
5133
  # 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
4960
5134
  el, last_tick = time.time() - last_tick, time.time()
4961
5135
  asleep = slept()
@@ -5638,7 +5812,8 @@ def team_up(args):
5638
5812
  die(f"run `orch start` first: it makes each coder's folder ({', '.join(missing_dirs)} have none yet)")
5639
5813
  # after a restart: panes that only lost their name get it back, and a coder's own pane that came back as a
5640
5814
  # plain shell gets its agent started again, instead of a second pane next to it
5641
- empty = {} if dry else rename_lost(dict(st, lead=None), hints=False)
5815
+ lead_pane = agent_pane(st["lead"]["name"]) if (st.get("lead") or {}).get("name") else None
5816
+ empty = {} if dry else rename_lost(dict(st, lead=None), hints=False, keep_out=[lead_pane] if lead_pane else [])
5642
5817
  todo = []
5643
5818
  for name, w, d in agents:
5644
5819
  if w.get("pane"):
@@ -5681,7 +5856,9 @@ def team_up(args):
5681
5856
  failed += 1
5682
5857
  continue
5683
5858
  last = pid
5684
- ok, _, out = _herdr_json([HERDR, "pane", "run", pid, cmd])
5859
+ # `cd` first: a split can start in the folder of the pane it splits from (herdr's new-pane folder setting),
5860
+ # and the reviewer must sit in the repo, not in a coder's worktree
5861
+ ok, _, out = _herdr_json([HERDR, "pane", "run", pid, f"cd {shlex.quote(str(d))} && {cmd}"])
5685
5862
  if not ok:
5686
5863
  print(f"FAILED {name}: pane {pid} is there, but `herdr pane run` failed ({out[-120:]})")
5687
5864
  failed += 1
@@ -5777,12 +5954,14 @@ def _inside(path, folder):
5777
5954
  return a == b or a.startswith(b.rstrip("/") + "/")
5778
5955
 
5779
5956
 
5780
- def rename_lost(st, hints=True):
5957
+ def rename_lost(st, hints=True, keep_out=()):
5781
5958
  """herdr brings panes back after a restart, but not the agents' names, and orch reaches agents by name. For
5782
5959
  every agent in the plan that herdr can't find, look for its pane by folder and give the name back. A coder's
5783
5960
  worktree is its own folder, so one pane there is its pane. The reviewer and the lead sit in the main folder,
5784
5961
  next to the developer's own panes, so there the pane must also show the agent's kind. Where that can't be
5785
5962
  decided, print the exact command (hints=False: only say what was named).
5963
+ Never gives a coder's or the reviewer's name to the pane this command runs in (that is the developer's or the
5964
+ lead's own pane), nor to a pane in keep_out (the lead's, when the lead is not renamed here).
5786
5965
  Returns {name: pane id or None} for the agents still not found; a pane id means "its pane is there (a
5787
5966
  coder's own folder), but no agent runs in it"."""
5788
5967
  plan = [(n, w, w.get("dir") or str(ROOT), st["isolation"] == "worktree" and bool(w.get("dir")))
@@ -5803,7 +5982,9 @@ def rename_lost(st, hints=True):
5803
5982
  f"open?). Find its pane with `herdr agent list` (folder {short(d)}), then: herdr agent rename <pane> {n}")
5804
5983
  return {x[0]: None for x in lost}
5805
5984
  found = {x[0] for x in plan} - {x[0] for x in lost}
5806
- taken = {agent_pane(n) for n in found} - {None}
5985
+ taken = ({agent_pane(n) for n in found} | set(keep_out)) - {None}
5986
+ me = os.environ.get("HERDR_PANE_ID")
5987
+ lead_name = (st.get("lead") or {}).get("name")
5807
5988
  reg = registry(required=False) or {}
5808
5989
  still, pending, progress, cands = {}, list(lost), True, {}
5809
5990
  while pending and progress: # a pane given to one agent can settle who gets another
@@ -5811,7 +5992,8 @@ def rename_lost(st, hints=True):
5811
5992
  for item in list(pending):
5812
5993
  n, w, d, own = item
5813
5994
  kind = (w.get("kind") or "").lower()
5814
- here = [pid for pid, p in panes.items() if pid not in taken and any(_inside(x, d) for x in p["cwds"])]
5995
+ here = [pid for pid, p in panes.items() if pid not in taken and any(_inside(x, d) for x in p["cwds"])
5996
+ and not (me and pid == me and n != lead_name)]
5815
5997
  same = [pid for pid in here if kind and panes[pid]["kind"]
5816
5998
  and (kind in panes[pid]["kind"] or panes[pid]["kind"] in kind)]
5817
5999
  cands[n] = here
@@ -5942,11 +6124,11 @@ COMMANDS = {
5942
6124
  "requeue-review": cmd_requeue_review, "finish": cmd_finish, "resend": cmd_resend, "approve": cmd_approve,
5943
6125
  "report": cmd_report, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer, "defer": cmd_defer,
5944
6126
  "escalate": cmd_escalate, "fix": cmd_fix, "plan": cmd_plan, "story": cmd_story, "team": cmd_team, "bench": cmd_bench, "stop": cmd_stop,
5945
- "doctor": lambda a: cmd_doctor_crash(a), "check": lambda a: cmd_check(a), "sub": lambda a: cmd_sub(a),
6127
+ "free": cmd_free, "doctor": lambda a: cmd_doctor_crash(a), "check": lambda a: cmd_check(a), "sub": lambda a: cmd_sub(a),
5946
6128
  }
5947
6129
  # they lock per step instead of for the whole command (long-running, or they start the event manager after)
5948
6130
  UNLOCKED = {"autopilot", "poll", "merge", "events", "dispatch", "answer", "defer", "fix", "team", "resume", "bench", "stop",
5949
- "doctor", "check"}
6131
+ "doctor", "check", "free"}
5950
6132
 
5951
6133
  USAGE = """usage: orch <command> [args]
5952
6134
  version print the installed herdr-orchestra version
@@ -5956,7 +6138,7 @@ USAGE = """usage: orch <command> [args]
5956
6138
  lead plan quick|full the rest of the plan playbook: a quick run's rules, or steps 3-10 of the full process
5957
6139
  lead run --section <EVENT|ALL_DONE|rules> one part of the run playbook (orch events prints these for you)
5958
6140
  lead check preflight: is this agent in a Herdr pane / can it reach herdr?
5959
- lead whoami show the lead's own herdr pane and how to name it `lead`
6141
+ lead whoami show the lead's own herdr pane and name it as the plan's `Lead:` (default `lead`)
5960
6142
  team <kind> [--coders N] [--models a,b] [--no-reviewer]
5961
6143
  the plan's team built from one installed tool: coders + reviewer on its catalog models
5962
6144
  team up [--dry-run] [--mode panes|subagent]
@@ -6005,9 +6187,13 @@ USAGE = """usage: orch <command> [args]
6005
6187
  park <Mn> paused|failed|pending [--lost] [reason] free the worker, keep its work in a hidden ref (refs/orch/...)
6006
6188
  cooldown <agent> <min> [reason] bench a worker or the reviewer (reason `gone`: ends once herdr sees it again)
6007
6189
  bench <worker> off [reason] | on keep a coder out of the run until you turn it back on (survives restarts)
6190
+ free <worker> a coder told to stop (`orch status`: stopping) has stopped: you checked its pane; it
6191
+ takes work again (orch otherwise waits until herdr shows it idle)
6008
6192
  stop [--now] stop the event manager cleanly (it finishes its current step); `orch resume` starts it again
6009
6193
  doctor --crash (in a repo) why the event manager last stopped, and the last crash / lost notes
6010
- set <Mn> <status> [reason] [--force] manual override: pending/paused/failed/skipped (others need --force)
6194
+ set <Mn> <status> [reason] [--force] manual override: pending/paused/failed/skipped (others need --force);
6195
+ a coder still working on a paused/failed Mn gets the interrupt key (Esc) and a STOP note,
6196
+ and stays busy ("stopping") until herdr shows it idle
6011
6197
  approve <Mn> let a milestone held for risky changes land (works while autopilot runs)
6012
6198
  cleanup remove clean worker worktrees
6013
6199
  finish [--no-push] [--recheck] final check (reused if it passed on these exact files), remove the <repo>-wt
@@ -6195,20 +6381,29 @@ def run_playbook_part(text, name):
6195
6381
  return "\n".join(rows) + ("\n" if rows else "")
6196
6382
 
6197
6383
 
6198
- def lead_self_name():
6199
- """`orch lead plan` / `orch lead run` (not a wake-up's --section): name the pane they run in as the lead. The
6200
- name is the run's `Lead:` (from state.json, else plan.md), else `lead`. Prints one line; never fails."""
6201
- st, name = None, "lead"
6384
+ def lead_name_here():
6385
+ """(state or None, the lead's name) for the repo this runs in: plan.md's `Lead:` first (it is what the developer
6386
+ wrote, even before `orch sync`), then the run's state.json, else `lead`. Never fails."""
6387
+ st, name = None, None
6202
6388
  with contextlib.suppress(Exception):
6203
6389
  r = git("rev-parse", "--path-format=absolute", "--git-common-dir", check=False)
6204
6390
  if r.returncode == 0:
6205
6391
  o = Path(r.stdout.strip()).parent / ".orchestrate"
6206
6392
  if (o / "state.json").exists():
6207
6393
  st = json.loads((o / "state.json").read_text())
6208
- name = (st.get("lead") or {}).get("name") or name
6209
- elif (o / "plan.md").exists():
6210
- m = re.search(r"(?mi)^Lead:\s*([\w.-]+)", (o / "plan.md").read_text())
6211
- name = m.group(1) if m and m.group(1).lower() != "none" else name
6394
+ if (o / "plan.md").exists():
6395
+ m = re.search(r"(?mi)^Lead:[ \t]*([\w.-]+)", (o / "plan.md").read_text())
6396
+ if m and m.group(1).lower() != "none":
6397
+ name = m.group(1)
6398
+ if not name and st:
6399
+ name = (st.get("lead") or {}).get("name")
6400
+ return st, name or "lead"
6401
+
6402
+
6403
+ def lead_self_name():
6404
+ """`orch lead plan` / `orch lead run` (not a wake-up's --section): name the pane they run in as the lead. The
6405
+ name is the plan's `Lead:` (plan.md, else state.json), else `lead`. Prints one line; never fails."""
6406
+ st, name = lead_name_here()
6212
6407
  if not os.environ.get("HERDR_PANE_ID"):
6213
6408
  pid, _ = herdr_current_pane()
6214
6409
  if pid:
@@ -6269,12 +6464,13 @@ def cmd_lead(args):
6269
6464
  pid = (re.search(r'"?pane_id"?\s*[:=]\s*"?([\w:.-]+)', out) or [None, None])[1]
6270
6465
  print(out)
6271
6466
  named = False
6467
+ st, name = lead_name_here()
6272
6468
  if os.environ.get("HERDR_PANE_ID"):
6273
- named, line = name_lead("lead")
6469
+ named, line = name_lead(name, st)
6274
6470
  print(line)
6275
6471
  if not named:
6276
- print(f"This pane is YOU (the lead). Name it: herdr agent rename {pid or '<pane id>'} lead")
6277
- print("Write `Lead: lead (<your kind>)` in the plan header, and never prompt this pane.")
6472
+ print(f"This pane is YOU (the lead). Name it: herdr agent rename {pid or '<pane id>'} {name}")
6473
+ print(f"Write `Lead: {name} (<your kind>)` in the plan header, and never prompt this pane.")
6278
6474
  return
6279
6475
  die("usage: orch lead plan | run | check | whoami")
6280
6476
 
@@ -7407,7 +7603,31 @@ def auto_update_at_plan():
7407
7603
  update_log(f"auto-update error: {e!r}")
7408
7604
 
7409
7605
 
7606
+ def command_help(words):
7607
+ """The USAGE lines of one command (`orch team up --help` -> the `team up` lines), or of all its forms."""
7608
+ blocks, cur = [], None
7609
+ for line in USAGE.splitlines()[1:]:
7610
+ if line.startswith(" ") and not line.startswith(" ") and line.strip():
7611
+ cur = [line]
7612
+ blocks.append(cur)
7613
+ elif cur is not None and line.startswith(" ") and line.strip():
7614
+ cur.append(line)
7615
+ else:
7616
+ cur = None
7617
+ mine = [b for b in blocks if b[0].split()[0] == words[0]]
7618
+ if len(words) > 1:
7619
+ sub = [b for b in mine if len(b[0].split()) > 1 and words[1] in re.split(r"[|\[\]\s]+", b[0].split(None, 1)[1])]
7620
+ mine = sub or mine
7621
+ return "\n".join("\n".join(b) for b in mine)
7622
+
7623
+
7410
7624
  if __name__ == "__main__":
7625
+ if len(sys.argv) >= 3 and any(a in ("--help", "-h") for a in sys.argv[2:]): # never run the command itself
7626
+ words = [sys.argv[1]] + [a for a in sys.argv[2:sys.argv.index("--help") if "--help" in sys.argv[2:]
7627
+ else sys.argv.index("-h")] if not a.startswith("-")][:1]
7628
+ text = command_help(words)
7629
+ print("usage: orch <command> [args]\n" + text if text else USAGE)
7630
+ sys.exit(0)
7411
7631
  if len(sys.argv) >= 2 and sys.argv[1] in ("version", "--version", "-v"):
7412
7632
  print(f"herdr-orchestra {installed_version()}")
7413
7633
  update_notice()
@@ -7426,7 +7646,7 @@ if __name__ == "__main__":
7426
7646
  sys.exit(0)
7427
7647
  if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS:
7428
7648
  print(USAGE)
7429
- sys.exit(0 if len(sys.argv) < 2 else 2)
7649
+ sys.exit(0 if len(sys.argv) < 2 or sys.argv[1] in ("--help", "-h", "help") else 2)
7430
7650
  ROOT = main_root()
7431
7651
  ORCH = ROOT / ".orchestrate"
7432
7652
  ORCH.mkdir(exist_ok=True)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-orchestra",
3
- "version": "6.2.1",
3
+ "version": "6.3.0",
4
4
  "description": "Orchestrate AI coding agents (Claude Code, Codex, OpenCode, Amp, Pi) as one team: a lead plans, coders build, a reviewer checks, you get one PR. Runs in Herdr panes, or in one Pi window with subagents.",
5
5
  "license": "MIT",
6
6
  "bin": {
package/playbooks/run.md CHANGED
@@ -58,6 +58,8 @@ If you changed plan.md by hand, run `orch sync` (it works once the event manager
58
58
 
59
59
  **Swap a coder** (for example, AGY instead of OpenCode): `orch stop` (the event manager finishes its current step and exits; nothing is lost), change `Workers:` in plan.md, `orch sync`, `orch team up`, check that `orch status` shows the new worker as `herdr=ok`, then `orch resume`. Never kill the event manager by hand.
60
60
 
61
+ **Move a milestone to another coder** (for example M7 from rs-agy-1 to rs-claude-1): `orch set M7 paused`, then `orch dispatch M7 --to rs-claude-1`. orch presses the old coder's interrupt key and tells it to stop. Tell the developer it has stopped only when `orch status` no longer shows it as `stopping M7`; until then it may still be editing files, and it gets no new work.
62
+
61
63
  **Before `orch dispatch --to <worker>`**, `orch status` must show that worker as `herdr=ok`. dispatch refuses a worker with no agent (`NO AGENT`, `SHELL ONLY`); do what it says (`orch team up`) and try again. If `orch team up` reports `QUIT <worker>`, the agent quit as soon as it started: show the developer the pane and the saved screen it names.
62
64
 
63
65
  **Why did the event manager stop?** `orch doctor --crash` prints the last `STOPPED` / `CRASHED` / `LOST` notes (with the reason found in the computer's own log) and the saved agent screens. Give the developer that reason in one line.