herdr-orchestra 6.2.1 → 6.4.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,44 @@
2
2
 
3
3
  All notable changes. Versions follow [semantic versioning](https://semver.org).
4
4
 
5
+ ## [6.4.0] - 2026-11-21
6
+
7
+ At the end of a run, the things you should try by hand now come to you as a plain numbered list: `orch finish` prints them, and the lead posts them in its chat. Nothing else changes: the lead writes the same "Manual verification checklist" in the summary as before, and orch reads it from there.
8
+
9
+ Example: you run `orch finish` in a terminal. It ends with
10
+
11
+ ```
12
+ MANUAL TESTS: 2 to try by hand before you merge (from the summary's Manual verification checklist):
13
+ 1. Open /settings, click Save → a green "Saved" note appears
14
+ 2. Open /settings on a phone → the form fits the screen
15
+ ```
16
+
17
+ and the lead's chat shows "Try these by hand before you merge:" with the same two lines, next to the PR link.
18
+
19
+ ### Added
20
+ - **Manual tests at `orch finish`.** It reads the summary's "Manual verification checklist" (any heading level, or a bold line) and prints it as a numbered list after the push and PR lines, also with `--no-push`. It says so when the lead wrote `Nothing to check by hand: <why>`, and when the checklist is not written yet. The list is also saved in `.orchestrate/manual-tests.md`.
21
+ - **`orch manual`** prints the same list again, at any time (also while the event manager runs).
22
+ - **`FINISHED` lead event.** With a lead in the run, `orch finish` queues `FINISHED` (pushed or not, the PR link, how many manual tests) and wakes the lead. `orch events` prints the list under it, and the playbook row tells the lead to post it in its chat, numbered and word for word. When the lead ran `orch finish` itself (from its own pane), it is not woken: the output tells it to post the list. In a subagent run the output tells the lead the same.
23
+
24
+ ### Changed
25
+ - **ALL_DONE:** the lead now lists the manual checklist items themselves in its chat (it used to give only how many there are), so you can try them before you run `orch finish`. Same in subagent runs.
26
+ ## [6.3.0] - 2026-11-21
27
+
28
+ 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.
29
+
30
+ ### Fixed
31
+ - **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.
32
+ - **`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.
33
+ - **`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`.
34
+ - **`--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.
35
+ - **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>`.
36
+
37
+ ### Added
38
+ - **`orch free <worker>`**: you checked the pane and the coder that was told to stop has stopped, so it can take work again now.
39
+ - **`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`.
40
+ - **`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.
41
+ - `orch status` says `free, but herdr shows it working` for a coder with no task whose pane is busy.
42
+ - 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
43
  ## [6.2.1] - 2026-11-21
6
44
 
7
45
  Fixes `/orch-setup` and `/orch-mode` not working in Pi when an older `orch` is already on the machine.
package/README.md CHANGED
@@ -152,7 +152,7 @@ Version choice, first match wins: `--version` flag › `ORCH_VERSION` env › `.
152
152
  You can also start the event manager yourself: `orch autopilot` in a spare terminal. It is the only driver of a run: while it runs, other `orch` commands that would change the run are refused (`orch status`, `orch report`, `orch approve` and the lead's `orch events` / `orch dispatch` / `orch answer` still work).
153
153
  After each wake-up the lead says in its chat what happened and what it did, one plain line per event; `orch story` keeps the whole run as a diary, and `orch plan show` gives the plan as one short card per milestone.
154
154
  4. **If the lead is away** (its pane is closed, or it never reads its events): nothing is lost, the events wait in the queue. Ready work starts by itself after 15 minutes, you get a desktop notification, and `orch events --peek` shows what is open. With `Lead mode: off` in the plan header there is no lead in the run at all: `orch autopilot` dispatches by itself and stops (exit 3) when it needs you.
155
- 5. **When it's done:** read `.orchestrate/summary.md` and do its manual checklist. It holds only what needs your eyes or hands (how the UI looks and behaves, a real device); whatever a command or a look at the code can settle, the run and the lead have already checked and listed with the evidence. Want a change? Tell the lead (for example "the login button should be blue"). It runs `orch fix M1 "the login button should be blue"`: one small follow-up job goes straight to the coder who built M1, with the check and review as before, and no new plan. You can run `orch fix` yourself too. When you are happy, run `orch finish`. It re-runs the check (or reuses it when it already passed on exactly these files; `--recheck` runs it anyway), removes the coders' worktrees and the `../<repo>-wt` folder (a coder folder with changes no milestone has is kept and named), pushes `feature/<name>` and opens a PR into `main` (with `gh`, or prints the compare link).
155
+ 5. **When it's done:** read `.orchestrate/summary.md` and do its manual checklist. It holds only what needs your eyes or hands (how the UI looks and behaves, a real device); whatever a command or a look at the code can settle, the run and the lead have already checked and listed with the evidence. Want a change? Tell the lead (for example "the login button should be blue"). It runs `orch fix M1 "the login button should be blue"`: one small follow-up job goes straight to the coder who built M1, with the check and review as before, and no new plan. You can run `orch fix` yourself too. When you are happy, run `orch finish`. It re-runs the check (or reuses it when it already passed on exactly these files; `--recheck` runs it anyway), removes the coders' worktrees and the `../<repo>-wt` folder (a coder folder with changes no milestone has is kept and named), pushes `feature/<name>` and opens a PR into `main` (with `gh`, or prints the compare link). Last, it prints the manual tests as a numbered list (`orch manual` prints them again), and the lead posts the same list in its chat.
156
156
 
157
157
  ### Git: one branch per run, real commits, one PR
158
158
  Planning touches no git at all. `orch start` creates the plan's `Branch:` (`feature/<slug>`) and that is the only branch a run makes: coders work on detached worktrees, and a milestone's work in progress (under review, parked, waiting for a fix) lives in hidden refs under `refs/orch/`, which `git branch` doesn't list and `git push` doesn't send. Each milestone lands as **one commit whose message says what changed** (the coder's `COMMIT:` line, e.g. `feat(api): add categories endpoint`, with a `Milestone: M2` trailer). `Commits: single` in the plan header squashes the run into one commit at finish.
@@ -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.4.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", "manual"}
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 ''}"
@@ -3139,6 +3260,122 @@ def ai_credited_commits(base):
3139
3260
  return found
3140
3261
 
3141
3262
 
3263
+ # ---------------------------------------------------------------- manual tests: what the developer tries by hand
3264
+ MANUAL_HEAD_RE = re.compile(r"^\s*(#{1,6}\s+|\*\*)\s*manual (verification checklist|tests?\b)", re.I)
3265
+ MANUAL_ITEM_RE = re.compile(r"^(\s*)(?:[-*+]\s+(?:\[[ xX]\]\s*)?|\d+[.)]\s+)(.*\S)\s*$")
3266
+
3267
+
3268
+ def manual_tests(text):
3269
+ """The summary's "Manual verification checklist" (the lead writes it at ALL_DONE): (items, note). items are
3270
+ the things to try by hand, in order (a sub-bullet or a wrapped line stays with its item); note is the lead's
3271
+ `Nothing to check by hand: ...` line when there are none. (None, None): the summary has no such section yet."""
3272
+ lines, start, level = text.splitlines(), None, 0
3273
+ for i, l in enumerate(lines):
3274
+ m = MANUAL_HEAD_RE.match(l)
3275
+ if m:
3276
+ start, level = i + 1, (len(m.group(1).strip()) if m.group(1).strip().startswith("#") else 0)
3277
+ if start is None:
3278
+ return None, None
3279
+ items, note = [], None
3280
+ for l in lines[start:]:
3281
+ h = re.match(r"^(#{1,6})\s", l)
3282
+ if (h and (not level or len(h.group(1)) <= level)) or (not level and l.startswith("**")):
3283
+ break
3284
+ m = MANUAL_ITEM_RE.match(l)
3285
+ if m and not m.group(1):
3286
+ items.append(m.group(2).strip())
3287
+ elif l.strip() and items and (m or l[:1].isspace()):
3288
+ items[-1] += ("; " + m.group(2).strip()) if m else (" " + l.strip())
3289
+ elif re.search(r"nothing to (check|test) by hand", l, re.I) and not note:
3290
+ note = l.strip().strip("-*_ ")
3291
+ return items, note
3292
+
3293
+
3294
+ def manual_block(st=None):
3295
+ """The manual test list for a person, as printed by `orch finish` and `orch manual` (and saved in
3296
+ .orchestrate/manual-tests.md): numbered, word for word from the summary. Returns (lines, count or None)."""
3297
+ summary = ORCH / "summary.md"
3298
+ items, note = manual_tests(summary.read_text()) if summary.exists() else (None, None)
3299
+ if items:
3300
+ out = [f"MANUAL TESTS: {len(items)} to try by hand before you merge (from the summary's Manual "
3301
+ f"verification checklist):"] + [f" {i}. {x}" for i, x in enumerate(items, 1)]
3302
+ elif items is not None:
3303
+ out = ["MANUAL TESTS: none. " + (note or "The lead's Manual verification checklist is empty.")]
3304
+ else:
3305
+ out = ["MANUAL TESTS: not written yet. .orchestrate/summary.md has no \"Manual verification checklist\": "
3306
+ "ask the lead to finish the summary (ALL_DONE), then `orch manual` prints the list."]
3307
+ with contextlib.suppress(OSError):
3308
+ if ORCH.is_dir():
3309
+ (ORCH / "manual-tests.md").write_text(
3310
+ f"# Manual tests: {(st or {}).get('title') or (st or {}).get('branch') or 'this run'}\n\n"
3311
+ "Try these by hand. They come from the Manual verification checklist in summary.md.\n\n"
3312
+ + ("".join(f"{i}. {x}\n" for i, x in enumerate(items, 1)) if items else out[0] + "\n"))
3313
+ return out, (len(items) if items is not None else None)
3314
+
3315
+
3316
+ def cmd_manual(args):
3317
+ """orch manual -> the manual test list from the summary, numbered, for the developer (and the lead's chat)."""
3318
+ st = load() if STATE.exists() else None
3319
+ print("\n".join(manual_block(st)[0]))
3320
+
3321
+
3322
+ def tell_lead_finished(st, outcome, count):
3323
+ """After `orch finish`: queue a FINISHED event for the lead, so it posts the manual test list in its chat. When
3324
+ the lead ran `orch finish` itself (this pane is the lead's), it has the list in front of it: no wake-up."""
3325
+ if not lead_on(st):
3326
+ if run_mode(st) == "subagent":
3327
+ print("LEAD: post the MANUAL TESTS list above in your chat, numbered, word for word.")
3328
+ return
3329
+ text = outcome + ("" if count is None else f"; {count} manual test(s) to try by hand")
3330
+ with state_lock():
3331
+ s_ = load()
3332
+ lead_event(s_, "finished", None, text)
3333
+ save(s_)
3334
+ lead = st["lead"]["name"]
3335
+ pid = os.environ.get("HERDR_PANE_ID")
3336
+ if pid and pid in (st["lead"].get("pane"), agent_pane(lead)):
3337
+ print("LEAD: you ran `orch finish` yourself: post the MANUAL TESTS list above in your chat now, numbered, "
3338
+ "word for word, then run `orch events` to mark FINISHED read.")
3339
+ return
3340
+ try:
3341
+ deliver(st, lead, f"orch: `orch finish` ran on {st['branch']}. Run `orch events` and post the manual test "
3342
+ f"list it prints in your chat, then stop.")
3343
+ print(f"TOLD THE LEAD ({lead}): it posts the manual test list in its chat")
3344
+ except DeliveryError as e:
3345
+ print(f"NOTE could not tell the lead ({lead}): {e} — tell it: run `orch events`")
3346
+
3347
+
3348
+ def finish_push(st, base, title, pr_body, args):
3349
+ """Push the feature branch and open the PR. Returns one line on what happened, for the lead's FINISHED event."""
3350
+ if "--no-push" in args:
3351
+ print(f"NOT PUSHED (--no-push): push {st['branch']} and open a PR into {base} when ready")
3352
+ return f"cleaned up, not pushed (--no-push): {st['branch']} still needs a push and a PR into {base}"
3353
+ remote = git("remote", "get-url", "origin", cwd=ROOT, check=False)
3354
+ if remote.returncode != 0:
3355
+ print(f"NO REMOTE: no `origin` remote — merge {st['branch']} into {base} yourself")
3356
+ return f"no `origin` remote: {st['branch']} is to be merged into {base} by hand"
3357
+ url = remote.stdout.strip()
3358
+ git("push", "-q", "-u", "origin", st["branch"], cwd=ROOT)
3359
+ print(f"PUSHED {st['branch']} to origin")
3360
+ compare = github_compare_url(url, base, st["branch"])
3361
+ if compare and shutil.which("gh"):
3362
+ try:
3363
+ r = subprocess.run(["gh", "pr", "create", "--base", base, "--head", st["branch"], "--title", title,
3364
+ "--body-file", str(pr_body)],
3365
+ cwd=ROOT, text=True, capture_output=True, timeout=120)
3366
+ except (OSError, subprocess.TimeoutExpired) as e:
3367
+ r = subprocess.CompletedProcess([], 1, "", str(e))
3368
+ if r.returncode == 0:
3369
+ pr = r.stdout.strip().splitlines()[-1] if r.stdout.strip() else "created"
3370
+ print(f"PR {pr}")
3371
+ return f"pushed {st['branch']}, PR into {base}: {pr}"
3372
+ print(f"NOTE gh pr create failed: {(r.stdout + r.stderr).strip()}")
3373
+ print(f"OPEN A PR from {st['branch']} into {base}" + (f": {compare}" if compare else "")
3374
+ + f" — title: {title!r}, text: .orchestrate/pr-body.md (use them as they are: add no \"Generated with\" or "
3375
+ f"Co-Authored-By line)")
3376
+ return f"pushed {st['branch']}; the PR into {base} is still to open" + (f": {compare}" if compare else "")
3377
+
3378
+
3142
3379
  def cmd_finish(args):
3143
3380
  """orch finish [--no-push] [--recheck] -> final check (reused when it already passed on exactly these files;
3144
3381
  --recheck runs it anyway), drop hidden refs and worktrees, push the feature branch, open a PR."""
@@ -3190,34 +3427,25 @@ def cmd_finish(args):
3190
3427
  for ref in rescued:
3191
3428
  print(f"KEPT {ref}: unsaved files orch rescued during the run and no milestone used — look with "
3192
3429
  f"`git show --stat {ref}`, delete with `git update-ref -d {ref}`")
3193
- if "--no-push" in args:
3194
- print(f"NOT PUSHED (--no-push): push {st['branch']} and open a PR into {base} when ready")
3195
- return
3196
- remote = git("remote", "get-url", "origin", cwd=ROOT, check=False)
3197
- if remote.returncode != 0:
3198
- print(f"NO REMOTE: no `origin` remote — merge {st['branch']} into {base} yourself")
3199
- return
3200
- url = remote.stdout.strip()
3201
- git("push", "-q", "-u", "origin", st["branch"], cwd=ROOT)
3202
- print(f"PUSHED {st['branch']} to origin")
3203
- compare = github_compare_url(url, base, st["branch"])
3204
- if compare and shutil.which("gh"):
3205
- try:
3206
- r = subprocess.run(["gh", "pr", "create", "--base", base, "--head", st["branch"], "--title", title,
3207
- "--body-file", str(pr_body)],
3208
- cwd=ROOT, text=True, capture_output=True, timeout=120)
3209
- except (OSError, subprocess.TimeoutExpired) as e:
3210
- r = subprocess.CompletedProcess([], 1, "", str(e))
3211
- if r.returncode == 0:
3212
- print(f"PR {r.stdout.strip().splitlines()[-1] if r.stdout.strip() else 'created'}")
3213
- return
3214
- print(f"NOTE gh pr create failed: {(r.stdout + r.stderr).strip()}")
3215
- print(f"OPEN A PR from {st['branch']} into {base}" + (f": {compare}" if compare else "")
3216
- + f" — title: {title!r}, text: .orchestrate/pr-body.md (use them as they are: add no \"Generated with\" or "
3217
- f"Co-Authored-By line)")
3430
+ outcome = finish_push(st, base, title, pr_body, args)
3431
+ lines, count = manual_block(st)
3432
+ print("\n".join(lines))
3433
+ tell_lead_finished(st, outcome, count)
3218
3434
 
3219
3435
 
3220
3436
  # ---------------------------------------------------------------- v4: task files, nudge, autopilot
3437
+ TASK_SRC_SKIP = ("notes from user", "plain") # answers reach the coder by their own prompt; Plain is not in task.md
3438
+
3439
+
3440
+ def task_source(section, glob=""):
3441
+ """A fingerprint of what task.md is written from (the milestone's plan text + Global instructions), so `orch
3442
+ sync` can tell when plan.md changed under a coder that is already working from an older task.md."""
3443
+ _, ts = parse_plan(section)
3444
+ f = {k: v for k, v in (ts[0]["fields"] if ts else {}).items() if k not in TASK_SRC_SKIP}
3445
+ title = ts[0]["title"] if ts else section.split("\n", 1)[0]
3446
+ return hashlib.sha1(json.dumps([title, f, glob.strip()], sort_keys=True).encode()).hexdigest()[:12]
3447
+
3448
+
3221
3449
  def plan_sections():
3222
3450
  """Return ({task_id: section_text}, global_instructions_text) straight from plan.md."""
3223
3451
  text = (ORCH / "plan.md").read_text()
@@ -3324,6 +3552,8 @@ def cmd_write_task(args):
3324
3552
  out.parent.mkdir(parents=True, exist_ok=True)
3325
3553
  out.write_text("\n".join(parts))
3326
3554
  (out.parent / "task.json").write_text(json.dumps(contract, indent=2))
3555
+ t["task_src"] = task_source(secs[tid], glob)
3556
+ save(st)
3327
3557
  print(f"WROTE {out}")
3328
3558
  print(f"WROTE {out.parent / 'task.json'}")
3329
3559
 
@@ -3419,6 +3649,9 @@ def cmd_dispatch(args):
3419
3649
  if st["workers"][to].get("off"):
3420
3650
  die(f"{to} is off ({st['workers'][to]['off'].get('why')}): `orch bench {to} on` first, or pick another "
3421
3651
  f"worker")
3652
+ if still_stopping(st, to):
3653
+ print(f"NOTE {to} is still stopping {st['workers'][to]['stopping'].get('task')}: the work starts "
3654
+ f"there once herdr shows it idle (`orch status`)")
3422
3655
  here = presence_word(st, to)
3423
3656
  if here not in ("ok", "detect:off"):
3424
3657
  die(f"{to} has no agent in herdr ({here}" + (": only a plain shell is left in its pane" if here ==
@@ -3695,6 +3928,9 @@ EVENT_HELP = {
3695
3928
  "any agent it reports LOST.",
3696
3929
  "all_done": "every milestone landed. Finish .orchestrate/summary.md: the steps (section 3, ALL_DONE) are printed below.",
3697
3930
  "stopped": "the event manager stopped. Tell the developer why; they run `orch resume` (or `orch autopilot`).",
3931
+ "finished": "the developer ran `orch finish`. Post the MANUAL TESTS list printed below in your chat, numbered and "
3932
+ "word for word, under \"Try these by hand before you merge\" (or say there is nothing to try by hand). "
3933
+ "Add nothing else to the run.",
3698
3934
  }
3699
3935
 
3700
3936
 
@@ -3737,6 +3973,8 @@ def say_line(st, e):
3737
3973
  return f"Every milestone is done: {text}."
3738
3974
  if k == "stopped":
3739
3975
  return f"The event manager stopped: {text}."
3976
+ if k == "finished":
3977
+ return f"The run is finished: {text}."
3740
3978
  return f"{k} {name}: {text}".strip()
3741
3979
 
3742
3980
 
@@ -3861,6 +4099,8 @@ def cmd_events(args):
3861
4099
  print(head + (f": {e['text']}" if e.get("text") else ""))
3862
4100
  print(" -> " + EVENT_HELP.get(e["kind"], "").format(t=e.get("task") or "<Mn>"))
3863
4101
  print(" SAY: " + say_line(st, e))
4102
+ if e["kind"] == "finished":
4103
+ print("\n".join(" " + x for x in manual_block(st)[0]))
3864
4104
  print(f"EVENTS for the lead — run {st['branch']}: {len(new)} new, {len(old)} still open")
3865
4105
  for e in new:
3866
4106
  show(e)
@@ -4759,8 +4999,43 @@ def _autopilot(args):
4759
4999
  elif t["status"] == "committed":
4760
5000
  land(tid)
4761
5001
 
5002
+ def tend_stops():
5003
+ """Coders told to stop: free once herdr shows them idle; interrupted again (twice at most) if they keep going."""
5004
+ st_ = load()
5005
+ for n, w in st_["workers"].items():
5006
+ h = w.get("stopping")
5007
+ if not h:
5008
+ continue
5009
+ s = herdr_state(n) if w.get("detect", True) else None
5010
+ busy = s is not None and busy_word(s)
5011
+ if busy and h.get("idle_since"):
5012
+ h["idle_since"] = None
5013
+ patch_state(lambda s_, n=n: n in s_["workers"] and s_["workers"][n].get("stopping") is not None
5014
+ and s_["workers"][n]["stopping"].update(idle_since=None))
5015
+ elif s is not None and not busy and not h.get("idle_since"):
5016
+ h["idle_since"] = now()
5017
+ patch_state(lambda s_, n=n, t=h["idle_since"]: n in s_["workers"]
5018
+ and s_["workers"][n].get("stopping") is not None
5019
+ and s_["workers"][n]["stopping"].update(idle_since=t))
5020
+ if not still_stopping(st_, n, w):
5021
+ patch_state(lambda s_, n=n: n in s_["workers"] and s_["workers"][n].pop("stopping", None))
5022
+ say(f"STOPPED {n}: it is idle after the stop for {h.get('task')}, so it can take new work")
5023
+ continue
5024
+ if now() - h.get("last", h.get("ts", 0)) >= HALT_REPEAT_S and h.get("again", 0) < 2:
5025
+ keys = interrupt(st_, n)
5026
+ patch_state(lambda s_, n=n: n in s_["workers"] and s_["workers"][n].get("stopping") is not None
5027
+ and s_["workers"][n]["stopping"].update(again=h.get("again", 0) + 1, last=now()))
5028
+ say(f"{n} is still working {_fmt_secs(now() - h.get('ts', now()))} after it was told to stop "
5029
+ f"{h.get('task')}: " + (f"pressed {'+'.join(keys)} again" if keys else
5030
+ "the interrupt key could not be sent")
5031
+ + f". It gets no new work until it is idle; look at its pane (`orch free {n}` once it has "
5032
+ f"stopped)", h.get("again", 0) >= 1)
5033
+
4762
5034
  def dispatch(kind, tid, worker):
4763
- _, prep = run("prepare", tid, worker)
5035
+ code, prep = run("prepare", tid, worker, ok=(0, 3))
5036
+ if code == 3: # the coder is busy after all (still stopping its last milestone): next loop
5037
+ say(f"{tid}: {worker} is not free yet ({prep.splitlines()[-1][:160] if prep else 'busy'}) — tried again soon")
5038
+ return
4764
5039
  if "SETUP_NEEDED" in prep:
4765
5040
  d = load()["tasks"][tid]["dir"]
4766
5041
  say(f"installing dependencies in {d}" + (" (dependency files changed)" if "changed" in prep else ""))
@@ -4956,6 +5231,7 @@ def _autopilot(args):
4956
5231
  procs = run_processes(st)
4957
5232
  patch_state(lambda s_: (s_["run"].get("manager") or {}).update(procs))
4958
5233
  watch_herdr()
5234
+ tend_stops()
4959
5235
  # 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
4960
5236
  el, last_tick = time.time() - last_tick, time.time()
4961
5237
  asleep = slept()
@@ -5638,7 +5914,8 @@ def team_up(args):
5638
5914
  die(f"run `orch start` first: it makes each coder's folder ({', '.join(missing_dirs)} have none yet)")
5639
5915
  # after a restart: panes that only lost their name get it back, and a coder's own pane that came back as a
5640
5916
  # 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)
5917
+ lead_pane = agent_pane(st["lead"]["name"]) if (st.get("lead") or {}).get("name") else None
5918
+ empty = {} if dry else rename_lost(dict(st, lead=None), hints=False, keep_out=[lead_pane] if lead_pane else [])
5642
5919
  todo = []
5643
5920
  for name, w, d in agents:
5644
5921
  if w.get("pane"):
@@ -5681,7 +5958,9 @@ def team_up(args):
5681
5958
  failed += 1
5682
5959
  continue
5683
5960
  last = pid
5684
- ok, _, out = _herdr_json([HERDR, "pane", "run", pid, cmd])
5961
+ # `cd` first: a split can start in the folder of the pane it splits from (herdr's new-pane folder setting),
5962
+ # and the reviewer must sit in the repo, not in a coder's worktree
5963
+ ok, _, out = _herdr_json([HERDR, "pane", "run", pid, f"cd {shlex.quote(str(d))} && {cmd}"])
5685
5964
  if not ok:
5686
5965
  print(f"FAILED {name}: pane {pid} is there, but `herdr pane run` failed ({out[-120:]})")
5687
5966
  failed += 1
@@ -5777,12 +6056,14 @@ def _inside(path, folder):
5777
6056
  return a == b or a.startswith(b.rstrip("/") + "/")
5778
6057
 
5779
6058
 
5780
- def rename_lost(st, hints=True):
6059
+ def rename_lost(st, hints=True, keep_out=()):
5781
6060
  """herdr brings panes back after a restart, but not the agents' names, and orch reaches agents by name. For
5782
6061
  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
6062
  worktree is its own folder, so one pane there is its pane. The reviewer and the lead sit in the main folder,
5784
6063
  next to the developer's own panes, so there the pane must also show the agent's kind. Where that can't be
5785
6064
  decided, print the exact command (hints=False: only say what was named).
6065
+ Never gives a coder's or the reviewer's name to the pane this command runs in (that is the developer's or the
6066
+ lead's own pane), nor to a pane in keep_out (the lead's, when the lead is not renamed here).
5786
6067
  Returns {name: pane id or None} for the agents still not found; a pane id means "its pane is there (a
5787
6068
  coder's own folder), but no agent runs in it"."""
5788
6069
  plan = [(n, w, w.get("dir") or str(ROOT), st["isolation"] == "worktree" and bool(w.get("dir")))
@@ -5803,7 +6084,9 @@ def rename_lost(st, hints=True):
5803
6084
  f"open?). Find its pane with `herdr agent list` (folder {short(d)}), then: herdr agent rename <pane> {n}")
5804
6085
  return {x[0]: None for x in lost}
5805
6086
  found = {x[0] for x in plan} - {x[0] for x in lost}
5806
- taken = {agent_pane(n) for n in found} - {None}
6087
+ taken = ({agent_pane(n) for n in found} | set(keep_out)) - {None}
6088
+ me = os.environ.get("HERDR_PANE_ID")
6089
+ lead_name = (st.get("lead") or {}).get("name")
5807
6090
  reg = registry(required=False) or {}
5808
6091
  still, pending, progress, cands = {}, list(lost), True, {}
5809
6092
  while pending and progress: # a pane given to one agent can settle who gets another
@@ -5811,7 +6094,8 @@ def rename_lost(st, hints=True):
5811
6094
  for item in list(pending):
5812
6095
  n, w, d, own = item
5813
6096
  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"])]
6097
+ here = [pid for pid, p in panes.items() if pid not in taken and any(_inside(x, d) for x in p["cwds"])
6098
+ and not (me and pid == me and n != lead_name)]
5815
6099
  same = [pid for pid in here if kind and panes[pid]["kind"]
5816
6100
  and (kind in panes[pid]["kind"] or panes[pid]["kind"] in kind)]
5817
6101
  cands[n] = here
@@ -5941,12 +6225,12 @@ COMMANDS = {
5941
6225
  "send-job": cmd_send_job, "handoff": cmd_handoff, "needs-fix": cmd_needs_fix, "review-ok": cmd_review_ok,
5942
6226
  "requeue-review": cmd_requeue_review, "finish": cmd_finish, "resend": cmd_resend, "approve": cmd_approve,
5943
6227
  "report": cmd_report, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer, "defer": cmd_defer,
5944
- "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),
6228
+ "escalate": cmd_escalate, "fix": cmd_fix, "plan": cmd_plan, "story": cmd_story, "manual": cmd_manual, "team": cmd_team, "bench": cmd_bench, "stop": cmd_stop,
6229
+ "free": cmd_free, "doctor": lambda a: cmd_doctor_crash(a), "check": lambda a: cmd_check(a), "sub": lambda a: cmd_sub(a),
5946
6230
  }
5947
6231
  # they lock per step instead of for the whole command (long-running, or they start the event manager after)
5948
- UNLOCKED = {"autopilot", "poll", "merge", "events", "dispatch", "answer", "defer", "fix", "team", "resume", "bench", "stop",
5949
- "doctor", "check"}
6232
+ UNLOCKED = {"manual", "autopilot", "poll", "merge", "events", "dispatch", "answer", "defer", "fix", "team", "resume", "bench", "stop",
6233
+ "doctor", "check", "free"}
5950
6234
 
5951
6235
  USAGE = """usage: orch <command> [args]
5952
6236
  version print the installed herdr-orchestra version
@@ -5956,7 +6240,7 @@ USAGE = """usage: orch <command> [args]
5956
6240
  lead plan quick|full the rest of the plan playbook: a quick run's rules, or steps 3-10 of the full process
5957
6241
  lead run --section <EVENT|ALL_DONE|rules> one part of the run playbook (orch events prints these for you)
5958
6242
  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`
6243
+ lead whoami show the lead's own herdr pane and name it as the plan's `Lead:` (default `lead`)
5960
6244
  team <kind> [--coders N] [--models a,b] [--no-reviewer]
5961
6245
  the plan's team built from one installed tool: coders + reviewer on its catalog models
5962
6246
  team up [--dry-run] [--mode panes|subagent]
@@ -5972,6 +6256,8 @@ USAGE = """usage: orch <command> [args]
5972
6256
  resume after a restart (computer off, herdr closed): name the agents' panes again, save unsaved
5973
6257
  work, re-send the tasks that were in progress and start the event manager
5974
6258
  story the run diary in plain words: each event and what the lead did (.orchestrate/story.md)
6259
+ manual the manual tests: what to try by hand, numbered, from the summary's Manual verification
6260
+ checklist (`orch finish` prints them too, and the lead posts them in its chat)
5975
6261
  plan show the plan for a person: each milestone in plain words, who builds it, how long, the order
5976
6262
  events [--peek] (lead) what you were woken for; reading acknowledges it
5977
6263
  dispatch <Mn>... [--to <worker>] [--tier <tier>] (lead) start or restart milestones; starts the event manager
@@ -6005,9 +6291,13 @@ USAGE = """usage: orch <command> [args]
6005
6291
  park <Mn> paused|failed|pending [--lost] [reason] free the worker, keep its work in a hidden ref (refs/orch/...)
6006
6292
  cooldown <agent> <min> [reason] bench a worker or the reviewer (reason `gone`: ends once herdr sees it again)
6007
6293
  bench <worker> off [reason] | on keep a coder out of the run until you turn it back on (survives restarts)
6294
+ free <worker> a coder told to stop (`orch status`: stopping) has stopped: you checked its pane; it
6295
+ takes work again (orch otherwise waits until herdr shows it idle)
6008
6296
  stop [--now] stop the event manager cleanly (it finishes its current step); `orch resume` starts it again
6009
6297
  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)
6298
+ set <Mn> <status> [reason] [--force] manual override: pending/paused/failed/skipped (others need --force);
6299
+ a coder still working on a paused/failed Mn gets the interrupt key (Esc) and a STOP note,
6300
+ and stays busy ("stopping") until herdr shows it idle
6011
6301
  approve <Mn> let a milestone held for risky changes land (works while autopilot runs)
6012
6302
  cleanup remove clean worker worktrees
6013
6303
  finish [--no-push] [--recheck] final check (reused if it passed on these exact files), remove the <repo>-wt
@@ -6174,7 +6464,7 @@ def plan_playbook_part(text, part):
6174
6464
  EVENT_ROWS = {"ready": "READY", "merged": "MERGED", "paused": "PAUSED", "failed": "FAILED", "held": "HELD",
6175
6465
  "worker-lost": "WORKER-LOST", "herdr-restart": "HERDR-RESTART", "needs-answer": "NEEDS-ANSWER",
6176
6466
  "escalated": "ESCALATED", "auto-dispatched": "AUTO-DISPATCHED", "stopped": "STOPPED",
6177
- "all_done": "ALL_DONE"}
6467
+ "all_done": "ALL_DONE", "finished": "FINISHED"}
6178
6468
 
6179
6469
 
6180
6470
  def run_playbook_part(text, name):
@@ -6195,20 +6485,29 @@ def run_playbook_part(text, name):
6195
6485
  return "\n".join(rows) + ("\n" if rows else "")
6196
6486
 
6197
6487
 
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"
6488
+ def lead_name_here():
6489
+ """(state or None, the lead's name) for the repo this runs in: plan.md's `Lead:` first (it is what the developer
6490
+ wrote, even before `orch sync`), then the run's state.json, else `lead`. Never fails."""
6491
+ st, name = None, None
6202
6492
  with contextlib.suppress(Exception):
6203
6493
  r = git("rev-parse", "--path-format=absolute", "--git-common-dir", check=False)
6204
6494
  if r.returncode == 0:
6205
6495
  o = Path(r.stdout.strip()).parent / ".orchestrate"
6206
6496
  if (o / "state.json").exists():
6207
6497
  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
6498
+ if (o / "plan.md").exists():
6499
+ m = re.search(r"(?mi)^Lead:[ \t]*([\w.-]+)", (o / "plan.md").read_text())
6500
+ if m and m.group(1).lower() != "none":
6501
+ name = m.group(1)
6502
+ if not name and st:
6503
+ name = (st.get("lead") or {}).get("name")
6504
+ return st, name or "lead"
6505
+
6506
+
6507
+ def lead_self_name():
6508
+ """`orch lead plan` / `orch lead run` (not a wake-up's --section): name the pane they run in as the lead. The
6509
+ name is the plan's `Lead:` (plan.md, else state.json), else `lead`. Prints one line; never fails."""
6510
+ st, name = lead_name_here()
6212
6511
  if not os.environ.get("HERDR_PANE_ID"):
6213
6512
  pid, _ = herdr_current_pane()
6214
6513
  if pid:
@@ -6269,12 +6568,13 @@ def cmd_lead(args):
6269
6568
  pid = (re.search(r'"?pane_id"?\s*[:=]\s*"?([\w:.-]+)', out) or [None, None])[1]
6270
6569
  print(out)
6271
6570
  named = False
6571
+ st, name = lead_name_here()
6272
6572
  if os.environ.get("HERDR_PANE_ID"):
6273
- named, line = name_lead("lead")
6573
+ named, line = name_lead(name, st)
6274
6574
  print(line)
6275
6575
  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.")
6576
+ print(f"This pane is YOU (the lead). Name it: herdr agent rename {pid or '<pane id>'} {name}")
6577
+ print(f"Write `Lead: {name} (<your kind>)` in the plan header, and never prompt this pane.")
6278
6578
  return
6279
6579
  die("usage: orch lead plan | run | check | whoami")
6280
6580
 
@@ -7407,7 +7707,31 @@ def auto_update_at_plan():
7407
7707
  update_log(f"auto-update error: {e!r}")
7408
7708
 
7409
7709
 
7710
+ def command_help(words):
7711
+ """The USAGE lines of one command (`orch team up --help` -> the `team up` lines), or of all its forms."""
7712
+ blocks, cur = [], None
7713
+ for line in USAGE.splitlines()[1:]:
7714
+ if line.startswith(" ") and not line.startswith(" ") and line.strip():
7715
+ cur = [line]
7716
+ blocks.append(cur)
7717
+ elif cur is not None and line.startswith(" ") and line.strip():
7718
+ cur.append(line)
7719
+ else:
7720
+ cur = None
7721
+ mine = [b for b in blocks if b[0].split()[0] == words[0]]
7722
+ if len(words) > 1:
7723
+ 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])]
7724
+ mine = sub or mine
7725
+ return "\n".join("\n".join(b) for b in mine)
7726
+
7727
+
7410
7728
  if __name__ == "__main__":
7729
+ if len(sys.argv) >= 3 and any(a in ("--help", "-h") for a in sys.argv[2:]): # never run the command itself
7730
+ words = [sys.argv[1]] + [a for a in sys.argv[2:sys.argv.index("--help") if "--help" in sys.argv[2:]
7731
+ else sys.argv.index("-h")] if not a.startswith("-")][:1]
7732
+ text = command_help(words)
7733
+ print("usage: orch <command> [args]\n" + text if text else USAGE)
7734
+ sys.exit(0)
7411
7735
  if len(sys.argv) >= 2 and sys.argv[1] in ("version", "--version", "-v"):
7412
7736
  print(f"herdr-orchestra {installed_version()}")
7413
7737
  update_notice()
@@ -7426,7 +7750,7 @@ if __name__ == "__main__":
7426
7750
  sys.exit(0)
7427
7751
  if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS:
7428
7752
  print(USAGE)
7429
- sys.exit(0 if len(sys.argv) < 2 else 2)
7753
+ sys.exit(0 if len(sys.argv) < 2 or sys.argv[1] in ("--help", "-h", "help") else 2)
7430
7754
  ROOT = main_root()
7431
7755
  ORCH = ROOT / ".orchestrate"
7432
7756
  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.4.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
@@ -48,6 +48,7 @@ Run `orch events`. It lists the new events, the ones still open, the milestones
48
48
  | `HELD Mn` | Risky changes (deleted files, migrations, CI config, secrets files, unlisted dependency changes, a very large diff) wait for the developer. Show the reasons from `orch status`, and tell the developer to look and run `orch approve Mn` (or `orch set Mn paused`). |
49
49
  | `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`. |
50
50
  | `ESCALATED Mn`, `AUTO-DISPATCHED Mn` | Information: nothing to dispatch. Mention an escalation in the final summary. |
51
+ | `FINISHED` | The developer ran `orch finish`. Post the MANUAL TESTS list that `orch events` prints under it in your chat, numbered and word for word, under "Try these by hand before you merge", plus the PR link from the event when there is one. If it says none, say there is nothing to try by hand and why. Nothing else to do: the run is over. |
51
52
  | `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. |
52
53
  | `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. |
53
54
  | `ALL_DONE` | Section 3. |
@@ -58,6 +59,8 @@ If you changed plan.md by hand, run `orch sync` (it works once the event manager
58
59
 
59
60
  **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
61
 
62
+ **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.
63
+
61
64
  **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
65
 
63
66
  **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.
@@ -70,7 +73,7 @@ If you changed plan.md by hand, run `orch sync` (it works once the event manager
70
73
  - **"Design decisions & study notes"** for the developer (include any milestone that needed a stronger model than planned, and what that says about the plan).
71
74
  - **"Checked by the lead"**. Go through every acceptance criterion and every behaviour the feature promised. Whatever can be settled by running a command or by reading the code, YOU settle now, and write one line each with the evidence: the command and its result, or `file:line`. This covers: a criterion "Checked automatically" marks `no evidence recorded` or `NOT met`, "the comment / doc / config says X", "the endpoint returns 400 for Y" (run its test, or read the test that covers it), "the migration adds column Z", "no leftover TODO or debug output". You may run the check command, single tests and read-only commands (`grep`, `git log`, `git diff --stat`), and open the few files you need; you still never edit application code. If a check of yours fails, it is a defect, not a checklist item: tell the developer and offer `orch fix Mn "<what is wrong>"`.
72
75
  - **"Manual verification checklist"**: ONLY what a person must see or do, because no command and no reading of code can settle it. That is: how the UI looks (layout, spacing, colours, dark mode, a small screen), how it behaves in a real browser or on a real device (click-through flows, focus, animation, how fast it feels), and anything that needs an outside account or hardware (a real email arriving, a payment in the provider's test mode, a push notification, a printer). Write each item so the developer can do it without reading code: `- [ ] <where to go and what to do> → <what they should see>`. Test for every item: "could I, or a test, have checked this?" If yes, it does not belong here: check it and move it to "Checked by the lead". Never write "review the code", "read the comments", "confirm the tests pass" or "check the function handles X" as a manual item. If nothing needs a person (a pure backend, CLI or docs change), write `Nothing to check by hand: <one line why>` instead of inventing items.
73
- 3. Tell the developer: "All tasks landed on <branch>. Review .orchestrate/summary.md. I checked <n> things myself; <m> need your eyes; <k> were deferred with your approval and are NOT done (listed as follow-ups) (the manual checklist), or: nothing needs checking by hand. Then run `orch finish`: it re-runs the check (or reuses it when it already passed on exactly these files), removes the worktrees and hidden refs, pushes <branch> and opens a PR into <base> (`orch finish --no-push` to only clean up)." Run `orch finish` yourself only when the developer says so: it pushes. It opens the PR itself when `gh` is installed; if it prints `OPEN A PR`, give the developer the link, and if they ask you to open it, use exactly the title and `.orchestrate/pr-body.md` it names. Never add a "Generated with …", `Co-Authored-By` or session line to a commit or a PR of the run: they are the developer's. **STOP.**
76
+ 3. Tell the developer: "All tasks landed on <branch>. Review .orchestrate/summary.md. I checked <n> things myself; <k> were deferred with your approval and are NOT done (listed as follow-ups). <m> need your eyes:", then the manual checklist items themselves, numbered, one per line (`orch manual` prints them as orch reads them), or: nothing needs checking by hand. Then: "Run `orch finish`: it re-runs the check (or reuses it when it already passed on exactly these files), removes the worktrees and hidden refs, pushes <branch> and opens a PR into <base> (`orch finish --no-push` to only clean up)." Run `orch finish` yourself only when the developer says so: it pushes. It opens the PR itself when `gh` is installed; if it prints `OPEN A PR`, give the developer the link, and if they ask you to open it, use exactly the title and `.orchestrate/pr-body.md` it names. Never add a "Generated with …", `Co-Authored-By` or session line to a commit or a PR of the run: they are the developer's. When you ran `orch finish` yourself, post the MANUAL TESTS list it printed in your chat, numbered and word for word, under "Try these by hand before you merge" (when the developer runs it in a terminal, you are woken with `FINISHED` and do the same). **STOP.**
74
77
  4. **The developer asks for a change after the summary** (for example "the login button should be blue"). Do not plan again. Find the milestone that built that part (the summary's Tasks list and Likely files tell you), then run `orch fix Mn "<the change, in the developer's words>"`. It adds one small follow-up milestone to `plan.md`, sends it straight to the coder who built Mn, and starts the event manager; the check and the review (when Mn had one) still run. Name another coder only when the developer asks: `--to <worker>`. Then **STOP**: you are woken with ALL_DONE again, and the new summary keeps the old one in `.orchestrate/summary.prev.md`, so carry your notes and checklist over and add what changed. Never type into a coder's pane yourself.
75
78
 
76
79
  ## Runs without a lead (`Lead mode: off`)
@@ -37,4 +37,5 @@ There is no event manager and there are no herdr panes. You drive one milestone
37
37
  - **Checked**: the final `orch check` result, each review, and one line per acceptance criterion with its evidence (a test, a command, or `file:line`). Run a command or read the code to settle anything you can.
38
38
  - **Reviewer suggestions not applied.**
39
39
  - **Manual verification checklist**: ONLY what a person must see or do (how the UI looks, a click-through in a real browser, a real email arriving). For a backend-only change write `Nothing to check by hand: <why>`.
40
- 2. Tell the developer: "All milestones are saved on <branch>. Review .orchestrate/summary.md. Then run `orch finish`: it re-runs the check (or reuses it), pushes <branch> and opens a PR (`orch finish --no-push` to only clean up)." Run `orch finish` yourself only when the developer says so: it pushes. Never add a "Generated with …", `Co-Authored-By` or session line to a commit or a PR of the run: they are the developer's. **STOP.**
40
+ 2. Tell the developer: "All milestones are saved on <branch>. Review .orchestrate/summary.md. <m> need your eyes:", then the manual checklist items, numbered, one per line (or: nothing needs checking by hand). Then: "Run `orch finish`: it re-runs the check (or reuses it), pushes <branch> and opens a PR (`orch finish --no-push` to only clean up)." Run `orch finish` yourself only when the developer says so: it pushes. Never add a "Generated with …", `Co-Authored-By` or session line to a commit or a PR of the run: they are the developer's. **STOP.**
41
+ 3. **After `orch finish`** (you ran it, or the developer tells you they did): post its MANUAL TESTS list in your chat, numbered and word for word, under "Try these by hand before you merge" (`orch manual` prints it again). If it says none, say there is nothing to try by hand. **STOP.**