herdr-orchestra 6.0.0 → 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/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"}
171
+ "fix", "team", "resume", "bench", "stop", "doctor", "plan", "story", "check", "free"}
167
172
  _LEASE = None
168
173
 
169
174
 
@@ -1274,6 +1279,7 @@ def cmd_sync(args):
1274
1279
  "title": title_m.group(1) if title_m else branch,
1275
1280
  "commits": commits,
1276
1281
  "mode": mode,
1282
+ "orch_mode": old.get("orch_mode") or config_mode(), # panes (herdr) or subagent (Pi): kept for the run
1277
1283
  "quick_because": quick_because if quick else None,
1278
1284
  "green_tree": old.get("green_tree"),
1279
1285
  "integration_broken": old.get("integration_broken"),
@@ -1324,6 +1330,7 @@ def cmd_sync(args):
1324
1330
  st["workers"][name] = {"kind": kind, "task": ow.get("task"), "cooldown_until": ow.get("cooldown_until", 0),
1325
1331
  "cooldown_reason": ow.get("cooldown_reason", ""),
1326
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
1327
1334
  "dir": ow.get("dir"), "setup_done": ow.get("setup_done", False),
1328
1335
  "setup_hash": ow.get("setup_hash"), "delivery_fails": ow.get("delivery_fails", 0),
1329
1336
  "pane": pane, "detect": detect(kind, pane, "Workers"),
@@ -1374,6 +1381,14 @@ def cmd_sync(args):
1374
1381
  rb = st["tasks"].get(st["reviewer_busy"]) if st.get("reviewer_busy") else None
1375
1382
  if st.get("reviewer_busy") and (rb is None or rb["status"] != "reviewing"):
1376
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>\"`")
1377
1392
  migrate(st)
1378
1393
  save(st)
1379
1394
  for w in warns:
@@ -1527,20 +1542,85 @@ def shared_fold(st, tid):
1527
1542
  f"are kept in {keep} (`git stash show -p {new[:12]}` to look); {tid} keeps its earlier saved work")
1528
1543
 
1529
1544
 
1530
- def stop_note(st, agent, tid, status, reason):
1531
- """Tell a coder whose milestone was just paused or failed to stop. Only when it is (or may be) still working;
1532
- whatever it writes anyway is saved the next time the milestone or its folder is used."""
1533
- 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:
1534
1577
  s = herdr_state(agent)
1535
- if s is None or not word(s, "working"):
1536
- 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)
1537
1592
  why = " ".join((reason or status).split())[:160]
1538
1593
  try:
1539
- deliver(st, agent, f"STOP: {tid} is {status} ({why}). Stop working on it now and do not change any more "
1540
- 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
1541
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):
1542
1609
  return False
1543
- 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)")
1544
1624
 
1545
1625
 
1546
1626
  def commit_message(st, tid):
@@ -1933,6 +2013,7 @@ def cmd_ready(args):
1933
2013
  slots = 1 # shared mode: a queued fix job IS the active milestone, and it needs a coder
1934
2014
  # only coders herdr can see count as free: a coder with no agent can't take work, whatever its task field says
1935
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)
1936
2017
  and (not w.get("detect", True) or w.get("pane") or herdr_state(n) is not None)]
1937
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)
1938
2019
  and not w.get("pane") and herdr_state(n) is None]
@@ -1958,7 +2039,7 @@ def cooling(name, info):
1958
2039
 
1959
2040
 
1960
2041
  def worker_free(st, name, w):
1961
- 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):
1962
2043
  return False
1963
2044
  if not w.get("detect", True): # herdr can't watch it: no task + no cooldown = free
1964
2045
  return True
@@ -1997,6 +2078,12 @@ def cmd_prepare(args):
1997
2078
  die(f"{tid} is {t['status']}, expected pending/paused/needs-fix/conflict")
1998
2079
  if w.get("task") and w["task"] != tid:
1999
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)
2000
2087
  if not holds(st, tid) and free_slots(st) <= 0 and not (st["isolation"] == "shared" and t["status"] in ("conflict", "needs-fix")):
2001
2088
  die("no free slot (max parallel reached)")
2002
2089
  d = Path(w["dir"] or ROOT)
@@ -2848,8 +2935,24 @@ def _park(st, tid, status, reason, force=False):
2848
2935
  move(st, tid, status, reason, force=force)
2849
2936
  t["wait"] = None
2850
2937
  save(st)
2851
- if note_to and stop_note(st, note_to, tid, status, reason):
2852
- 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")
2853
2956
 
2854
2957
 
2855
2958
  def cmd_park(args):
@@ -2919,6 +3022,22 @@ def cmd_bench(args):
2919
3022
  print("WARN every coder is off now: nothing new starts until one is back on")
2920
3023
 
2921
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
+
2922
3041
  def cmd_stop(args):
2923
3042
  """orch stop [--now] -> stop the event manager cleanly: it finishes the step it is on (a check, a merge) and
2924
3043
  exits; every event and all work are kept. Then change the run (plan.md + `orch sync`, `orch team up`) and
@@ -3002,7 +3121,10 @@ def cmd_status(args):
3002
3121
  h = here[n]
3003
3122
  state = ("OFF (" + (w["off"].get("why") or "developer") + ")" if w.get("off") else
3004
3123
  f"coding {w['task']}" if w.get("task") else
3124
+ stopping_line(st, n, w) if still_stopping(st, n, w) else
3005
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"
3006
3128
  print(f" worker {n:<12} {w['kind']:<8} task={w.get('task') or '-':<5} "
3007
3129
  + (f"model={w['model']} ({w.get('tier') or 'unrated'}) " if w.get("model") else "")
3008
3130
  + f"{'cooldown ' + str(cd // 60) + 'm' if cd else ''}"
@@ -3217,6 +3339,18 @@ def cmd_finish(args):
3217
3339
 
3218
3340
 
3219
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
+
3220
3354
  def plan_sections():
3221
3355
  """Return ({task_id: section_text}, global_instructions_text) straight from plan.md."""
3222
3356
  text = (ORCH / "plan.md").read_text()
@@ -3323,6 +3457,8 @@ def cmd_write_task(args):
3323
3457
  out.parent.mkdir(parents=True, exist_ok=True)
3324
3458
  out.write_text("\n".join(parts))
3325
3459
  (out.parent / "task.json").write_text(json.dumps(contract, indent=2))
3460
+ t["task_src"] = task_source(secs[tid], glob)
3461
+ save(st)
3326
3462
  print(f"WROTE {out}")
3327
3463
  print(f"WROTE {out.parent / 'task.json'}")
3328
3464
 
@@ -3363,6 +3499,9 @@ def start_manager():
3363
3499
  detached from this shell, when none is running. Says what happened."""
3364
3500
  if driver_alive():
3365
3501
  return f"the event manager is running ({driver_line(driver_info())})"
3502
+ with contextlib.suppress(OSError, ValueError):
3503
+ if STATE.exists() and run_mode(json.loads(STATE.read_text())) == "subagent":
3504
+ return "subagent mode: no event manager (the lead drives the run with `orch sub next`)"
3366
3505
  if os.environ.get("ORCH_NO_AUTOSTART") == "1":
3367
3506
  return "the event manager is NOT running — ask the developer to run `orch autopilot` in a terminal"
3368
3507
  _rotate(ORCH / "manager.out", LOG_MAX_B // 2)
@@ -3404,6 +3543,9 @@ def cmd_dispatch(args):
3404
3543
  need(args, 1, "dispatch <Mn> [Mn...] [--to <worker>] [--tier small|medium|high]")
3405
3544
  with state_lock():
3406
3545
  st = load()
3546
+ if run_mode(st) == "subagent":
3547
+ die("this run is in subagent mode: the lead starts milestones with `orch sub next` (no event manager); "
3548
+ "`orch mode panes` switches back while nothing is in progress")
3407
3549
  require_lead(st, "orch dispatch")
3408
3550
  if opts.get("--to") and opts["--to"] not in st["workers"]:
3409
3551
  die(f"unknown worker {opts['--to']!r} — workers: {', '.join(st['workers'])}")
@@ -3412,6 +3554,9 @@ def cmd_dispatch(args):
3412
3554
  if st["workers"][to].get("off"):
3413
3555
  die(f"{to} is off ({st['workers'][to]['off'].get('why')}): `orch bench {to} on` first, or pick another "
3414
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`)")
3415
3560
  here = presence_word(st, to)
3416
3561
  if here not in ("ok", "detect:off"):
3417
3562
  die(f"{to} has no agent in herdr ({here}" + (": only a plain shell is left in its pane" if here ==
@@ -4045,6 +4190,9 @@ def cmd_autopilot(args):
4045
4190
  """The event manager (see _autopilot). This wrapper records how it ends: every stop writes a last line to
4046
4191
  autopilot.log, a Python error writes the traceback, and a manager that was killed without a word (memory guard,
4047
4192
  a crash of the whole terminal) is found by the next one, which looks up why in the computer's own log."""
4193
+ with contextlib.suppress(OSError, ValueError):
4194
+ if STATE.exists() and run_mode(json.loads(STATE.read_text())) == "subagent":
4195
+ die("this run is in subagent mode: there is no event manager; the lead drives it with `orch sub next`")
4048
4196
  take_lease()
4049
4197
  if STATE.exists():
4050
4198
  manager_begin()
@@ -4749,8 +4897,43 @@ def _autopilot(args):
4749
4897
  elif t["status"] == "committed":
4750
4898
  land(tid)
4751
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
+
4752
4932
  def dispatch(kind, tid, worker):
4753
- _, 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
4754
4937
  if "SETUP_NEEDED" in prep:
4755
4938
  d = load()["tasks"][tid]["dir"]
4756
4939
  say(f"installing dependencies in {d}" + (" (dependency files changed)" if "changed" in prep else ""))
@@ -4946,6 +5129,7 @@ def _autopilot(args):
4946
5129
  procs = run_processes(st)
4947
5130
  patch_state(lambda s_: (s_["run"].get("manager") or {}).update(procs))
4948
5131
  watch_herdr()
5132
+ tend_stops()
4949
5133
  # 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
4950
5134
  el, last_tick = time.time() - last_tick, time.time()
4951
5135
  asleep = slept()
@@ -5608,8 +5792,17 @@ def _herdr_json(cmd):
5608
5792
  def team_up(args):
5609
5793
  """Open a pane for every worker and the reviewer in the plan that herdr can't find: split from this pane, cd
5610
5794
  into the agent's folder (its worktree, or the repo), start it on its plan model, and give it its plan name."""
5795
+ args = list(args)
5796
+ flag = mode_flag(args, "usage: orch team up [--dry-run] [--mode panes|subagent]")
5611
5797
  dry = "--dry-run" in args
5798
+ if flag and not dry:
5799
+ set_mode(flag, hint=False)
5612
5800
  st = load()
5801
+ if (flag or run_mode(st)) == "subagent":
5802
+ print("mode subagent: no panes to open; the coder and the reviewer are Pi subagents")
5803
+ if dry:
5804
+ return
5805
+ sys.exit(1 if pi_setup() else 0)
5613
5806
  reg = registry(required=False) or {}
5614
5807
  agents = [(n, w, w.get("dir")) for n, w in st["workers"].items()]
5615
5808
  if st.get("reviewer"):
@@ -5619,7 +5812,8 @@ def team_up(args):
5619
5812
  die(f"run `orch start` first: it makes each coder's folder ({', '.join(missing_dirs)} have none yet)")
5620
5813
  # after a restart: panes that only lost their name get it back, and a coder's own pane that came back as a
5621
5814
  # plain shell gets its agent started again, instead of a second pane next to it
5622
- 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 [])
5623
5817
  todo = []
5624
5818
  for name, w, d in agents:
5625
5819
  if w.get("pane"):
@@ -5662,7 +5856,9 @@ def team_up(args):
5662
5856
  failed += 1
5663
5857
  continue
5664
5858
  last = pid
5665
- 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}"])
5666
5862
  if not ok:
5667
5863
  print(f"FAILED {name}: pane {pid} is there, but `herdr pane run` failed ({out[-120:]})")
5668
5864
  failed += 1
@@ -5758,12 +5954,14 @@ def _inside(path, folder):
5758
5954
  return a == b or a.startswith(b.rstrip("/") + "/")
5759
5955
 
5760
5956
 
5761
- def rename_lost(st, hints=True):
5957
+ def rename_lost(st, hints=True, keep_out=()):
5762
5958
  """herdr brings panes back after a restart, but not the agents' names, and orch reaches agents by name. For
5763
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
5764
5960
  worktree is its own folder, so one pane there is its pane. The reviewer and the lead sit in the main folder,
5765
5961
  next to the developer's own panes, so there the pane must also show the agent's kind. Where that can't be
5766
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).
5767
5965
  Returns {name: pane id or None} for the agents still not found; a pane id means "its pane is there (a
5768
5966
  coder's own folder), but no agent runs in it"."""
5769
5967
  plan = [(n, w, w.get("dir") or str(ROOT), st["isolation"] == "worktree" and bool(w.get("dir")))
@@ -5784,7 +5982,9 @@ def rename_lost(st, hints=True):
5784
5982
  f"open?). Find its pane with `herdr agent list` (folder {short(d)}), then: herdr agent rename <pane> {n}")
5785
5983
  return {x[0]: None for x in lost}
5786
5984
  found = {x[0] for x in plan} - {x[0] for x in lost}
5787
- 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")
5788
5988
  reg = registry(required=False) or {}
5789
5989
  still, pending, progress, cands = {}, list(lost), True, {}
5790
5990
  while pending and progress: # a pane given to one agent can settle who gets another
@@ -5792,7 +5992,8 @@ def rename_lost(st, hints=True):
5792
5992
  for item in list(pending):
5793
5993
  n, w, d, own = item
5794
5994
  kind = (w.get("kind") or "").lower()
5795
- 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)]
5796
5997
  same = [pid for pid in here if kind and panes[pid]["kind"]
5797
5998
  and (kind in panes[pid]["kind"] or panes[pid]["kind"] in kind)]
5798
5999
  cands[n] = here
@@ -5923,11 +6124,11 @@ COMMANDS = {
5923
6124
  "requeue-review": cmd_requeue_review, "finish": cmd_finish, "resend": cmd_resend, "approve": cmd_approve,
5924
6125
  "report": cmd_report, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer, "defer": cmd_defer,
5925
6126
  "escalate": cmd_escalate, "fix": cmd_fix, "plan": cmd_plan, "story": cmd_story, "team": cmd_team, "bench": cmd_bench, "stop": cmd_stop,
5926
- "doctor": lambda a: cmd_doctor_crash(a),
6127
+ "free": cmd_free, "doctor": lambda a: cmd_doctor_crash(a), "check": lambda a: cmd_check(a), "sub": lambda a: cmd_sub(a),
5927
6128
  }
5928
6129
  # they lock per step instead of for the whole command (long-running, or they start the event manager after)
5929
6130
  UNLOCKED = {"autopilot", "poll", "merge", "events", "dispatch", "answer", "defer", "fix", "team", "resume", "bench", "stop",
5930
- "doctor"}
6131
+ "doctor", "check", "free"}
5931
6132
 
5932
6133
  USAGE = """usage: orch <command> [args]
5933
6134
  version print the installed herdr-orchestra version
@@ -5937,10 +6138,15 @@ USAGE = """usage: orch <command> [args]
5937
6138
  lead plan quick|full the rest of the plan playbook: a quick run's rules, or steps 3-10 of the full process
5938
6139
  lead run --section <EVENT|ALL_DONE|rules> one part of the run playbook (orch events prints these for you)
5939
6140
  lead check preflight: is this agent in a Herdr pane / can it reach herdr?
5940
- 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`)
5941
6142
  team <kind> [--coders N] [--models a,b] [--no-reviewer]
5942
6143
  the plan's team built from one installed tool: coders + reviewer on its catalog models
5943
- team up [--dry-run] open a herdr pane for every agent in the plan herdr can't find, in its folder, and name it
6144
+ team up [--dry-run] [--mode panes|subagent]
6145
+ open a herdr pane for every agent in the plan herdr can't find, in its folder, and name it
6146
+ (subagent mode: no panes; sets up the Pi coder/reviewer subagents instead)
6147
+ mode [panes|subagent] which mode runs use: panes (herdr panes, the default) or subagent (one Pi window)
6148
+ setup [--mode panes|subagent] get this machine ready for a mode; subagent: write ~/.pi/agent/agents/coder.md and
6149
+ reviewer.md from ~/.config/herdr-orchestra/config.json and install pi-subagents
5944
6150
  agents the agent registry: kinds, installed?, roles, herdr detection, launch commands
5945
6151
  agents launch <kind> [--model <id>] print the command that starts <kind> in a pane (auto-approve edits)
5946
6152
  models the model catalog: tiers (small / medium / high), ratings, and what policy forbids
@@ -5951,6 +6157,8 @@ USAGE = """usage: orch <command> [args]
5951
6157
  plan show the plan for a person: each milestone in plain words, who builds it, how long, the order
5952
6158
  events [--peek] (lead) what you were woken for; reading acknowledges it
5953
6159
  dispatch <Mn>... [--to <worker>] [--tier <tier>] (lead) start or restart milestones; starts the event manager
6160
+ check [Mn] run the plan's check command in the main folder: CHECK PASS, or CHECK FAIL (exit 1)
6161
+ sub next | sub done <Mn> (lead, subagent mode) the next milestone and its task file | save a finished milestone
5954
6162
  answer <Mn> [--defer AC2,AC3] <text> (lead) the developer's answer: into plan.md, and back to the same coder;
5955
6163
  --defer records that the developer approved leaving those criteria undone
5956
6164
  defer <Mn> <AC2,AC3> <reason> (lead, only with the developer's yes) these criteria stay undone in Mn: no fix
@@ -5979,9 +6187,13 @@ USAGE = """usage: orch <command> [args]
5979
6187
  park <Mn> paused|failed|pending [--lost] [reason] free the worker, keep its work in a hidden ref (refs/orch/...)
5980
6188
  cooldown <agent> <min> [reason] bench a worker or the reviewer (reason `gone`: ends once herdr sees it again)
5981
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)
5982
6192
  stop [--now] stop the event manager cleanly (it finishes its current step); `orch resume` starts it again
5983
6193
  doctor --crash (in a repo) why the event manager last stopped, and the last crash / lost notes
5984
- 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
5985
6197
  approve <Mn> let a milestone held for risky changes land (works while autopilot runs)
5986
6198
  cleanup remove clean worker worktrees
5987
6199
  finish [--no-push] [--recheck] final check (reused if it passed on these exact files), remove the <repo>-wt
@@ -6169,20 +6381,29 @@ def run_playbook_part(text, name):
6169
6381
  return "\n".join(rows) + ("\n" if rows else "")
6170
6382
 
6171
6383
 
6172
- def lead_self_name():
6173
- """`orch lead plan` / `orch lead run` (not a wake-up's --section): name the pane they run in as the lead. The
6174
- name is the run's `Lead:` (from state.json, else plan.md), else `lead`. Prints one line; never fails."""
6175
- 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
6176
6388
  with contextlib.suppress(Exception):
6177
6389
  r = git("rev-parse", "--path-format=absolute", "--git-common-dir", check=False)
6178
6390
  if r.returncode == 0:
6179
6391
  o = Path(r.stdout.strip()).parent / ".orchestrate"
6180
6392
  if (o / "state.json").exists():
6181
6393
  st = json.loads((o / "state.json").read_text())
6182
- name = (st.get("lead") or {}).get("name") or name
6183
- elif (o / "plan.md").exists():
6184
- m = re.search(r"(?mi)^Lead:\s*([\w.-]+)", (o / "plan.md").read_text())
6185
- 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()
6186
6407
  if not os.environ.get("HERDR_PANE_ID"):
6187
6408
  pid, _ = herdr_current_pane()
6188
6409
  if pid:
@@ -6209,9 +6430,15 @@ def cmd_lead(args):
6209
6430
  print(run_playbook_part(pb.read_text(), args[2] if len(args) > 2 else ""), end="")
6210
6431
  return
6211
6432
  label = f"{sub} ({part})" if part else sub
6433
+ subagent = current_mode()[0] == "subagent"
6434
+ if subagent and sub == "run":
6435
+ pb = asset("playbooks/subagent.md") or die("playbooks/subagent.md not found next to orch or in the install")
6436
+ label = "run (subagent mode)"
6212
6437
  print(f"herdr-orchestra {installed_version()} — lead playbook: {label}\n")
6213
- if not part:
6438
+ if not part and not subagent:
6214
6439
  lead_self_name()
6440
+ if subagent and sub == "plan":
6441
+ print(SUBAGENT_PLAN_NOTE, end="")
6215
6442
  print(plan_playbook_part(pb.read_text(), part) if sub == "plan" else pb.read_text(), end="")
6216
6443
  return
6217
6444
  if sub == "check":
@@ -6237,12 +6464,13 @@ def cmd_lead(args):
6237
6464
  pid = (re.search(r'"?pane_id"?\s*[:=]\s*"?([\w:.-]+)', out) or [None, None])[1]
6238
6465
  print(out)
6239
6466
  named = False
6467
+ st, name = lead_name_here()
6240
6468
  if os.environ.get("HERDR_PANE_ID"):
6241
- named, line = name_lead("lead")
6469
+ named, line = name_lead(name, st)
6242
6470
  print(line)
6243
6471
  if not named:
6244
- print(f"This pane is YOU (the lead). Name it: herdr agent rename {pid or '<pane id>'} lead")
6245
- 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.")
6246
6474
  return
6247
6475
  die("usage: orch lead plan | run | check | whoami")
6248
6476
 
@@ -6942,6 +7170,361 @@ def cmd_update(args):
6942
7170
  print(f"Go back any time: orch update --version v{cur}")
6943
7171
 
6944
7172
 
7173
+ # ---------------------------------------------------------------- run modes: panes (herdr) or subagent (one Pi window)
7174
+ # `panes` is today's workflow and the default: coders and the reviewer are agents in herdr panes, the event manager
7175
+ # drives them. `subagent` is for Pi (https://pi.dev) with the @tintinweb/pi-subagents extension: the lead stays in one
7176
+ # window and starts the coder and the reviewer as Pi subagents, one milestone at a time. Nothing about panes mode
7177
+ # changes when nobody picks subagent.
7178
+ ORCH_MODES = ("panes", "subagent")
7179
+ PI_SUBAGENTS = "npm:@tintinweb/pi-subagents"
7180
+ PI_AGENT_MARK = "<!-- written by `orch setup` (herdr-orchestra). orch rewrites this file; delete this line to keep your own edits. -->"
7181
+
7182
+
7183
+ def user_config_file():
7184
+ return Path(os.environ.get("ORCH_CONFIG_FILE") or Path.home() / ".config/herdr-orchestra/config.json")
7185
+
7186
+
7187
+ def config_load():
7188
+ try:
7189
+ data = json.loads(user_config_file().read_text())
7190
+ return data if isinstance(data, dict) else {}
7191
+ except (OSError, ValueError):
7192
+ return {}
7193
+
7194
+
7195
+ def config_save(data):
7196
+ p = user_config_file()
7197
+ p.parent.mkdir(parents=True, exist_ok=True)
7198
+ tmp = p.with_suffix(".json.tmp")
7199
+ tmp.write_text(json.dumps(data, indent=2) + "\n")
7200
+ os.replace(tmp, p)
7201
+
7202
+
7203
+ def config_mode():
7204
+ m = str(config_load().get("mode") or "panes").lower()
7205
+ return m if m in ORCH_MODES else "panes"
7206
+
7207
+
7208
+ def run_mode(st):
7209
+ """A run keeps the mode it was planned in. Runs from before 6.2.0 have no `orch_mode`: they are panes runs."""
7210
+ m = (st or {}).get("orch_mode") or "panes"
7211
+ return m if m in ORCH_MODES else "panes"
7212
+
7213
+
7214
+ def _repo_state_path():
7215
+ """.orchestrate/state.json of the repo this shell is in, or None (outside a repo, or no run yet)."""
7216
+ r = git("rev-parse", "--path-format=absolute", "--git-common-dir", check=False)
7217
+ if r.returncode != 0:
7218
+ return None
7219
+ p = Path(r.stdout.strip()).parent / ".orchestrate" / "state.json"
7220
+ return p if p.exists() else None
7221
+
7222
+
7223
+ def current_mode():
7224
+ """(mode, where it comes from): this repo's run, else the machine's config, else panes."""
7225
+ with contextlib.suppress(Exception):
7226
+ p = _repo_state_path()
7227
+ if p:
7228
+ return run_mode(json.loads(p.read_text())), "this repo's run"
7229
+ if "mode" in config_load():
7230
+ return config_mode(), short(user_config_file())
7231
+ return "panes", "default"
7232
+
7233
+
7234
+ def mode_flag(args, usage):
7235
+ """Take `--mode <panes|subagent>` (or `--mode=...`) out of args; returns the mode or None."""
7236
+ for i, a in enumerate(list(args)):
7237
+ if a == "--mode" or a.startswith("--mode="):
7238
+ val = a.split("=", 1)[1] if "=" in a else (args[i + 1] if len(args) > i + 1 else "")
7239
+ del args[i:i + (1 if "=" in a else 2)]
7240
+ val = val.lower()
7241
+ if val not in ORCH_MODES:
7242
+ die(f"--mode must be panes or subagent, got {val!r} — {usage}")
7243
+ return val
7244
+ return None
7245
+
7246
+
7247
+ def pi_bin():
7248
+ return os.environ.get("ORCH_PI") or "pi"
7249
+
7250
+
7251
+ def pi_agents_dir():
7252
+ return Path(os.environ.get("PI_CODING_AGENT_DIR") or Path.home() / ".pi/agent") / "agents"
7253
+
7254
+
7255
+ PI_CODER_BODY = """You are a coder in a herdr-orchestra run. The lead gives you one milestone at a time: the path of its task file
7256
+ is in your prompt. Read it and build what it asks. The task says what and why; you decide how.
7257
+
7258
+ - Work only in this folder, on the branch that is checked out. Never commit, push, stash, reset or switch branches:
7259
+ orch saves your work when the milestone is done.
7260
+ - Never weaken, skip or delete tests to make the check pass.
7261
+ - Before you finish, run the check command named in the task file and fix what fails.
7262
+ - If something only the developer can decide blocks you, stop and reply `QUESTION: <the question>` with 2 or 3
7263
+ concrete options. Don't guess.
7264
+ - When the lead sends you a failing check or review findings, fix exactly those and run the check again.
7265
+
7266
+ End every reply with: the files you changed, the check result (PASS or FAIL), and one line per acceptance criterion:
7267
+ `AC<n>: met|not met - <evidence: a test, a command, or file:line>`.
7268
+ """
7269
+
7270
+ PI_REVIEWER_BODY = """You are the reviewer in a herdr-orchestra run. The lead sends you one milestone: its task file and what changed.
7271
+ You never edit files. Read the task file, then the change (`git diff HEAD` and `git status --short` for new files),
7272
+ and the code around it.
7273
+
7274
+ Reply with one line per finding, most serious first:
7275
+ - `BLOCKER: <file:line> - <problem> - <why it matters> (AC<n> when it breaks a criterion)` for a bug, a broken or
7276
+ missing acceptance criterion, a missing test for new behaviour, or a security problem.
7277
+ - `SUGGESTION: <file:line> - <idea>` for something nice to have.
7278
+ - `NO FINDINGS` when there is nothing to report.
7279
+ Then one line per acceptance criterion: `AC<n>: met|not met - <evidence>`.
7280
+ """
7281
+
7282
+
7283
+ def pi_agent_text(role, conf):
7284
+ """coder.md / reviewer.md for pi-subagents: front matter from the config, then the role's instructions."""
7285
+ model, thinking = (conf or {}).get("model"), (conf or {}).get("thinking")
7286
+ desc = ("herdr-orchestra coder: builds one milestone from its task file" if role == "coder" else
7287
+ "herdr-orchestra reviewer: reviews one milestone, never edits files")
7288
+ fm = [f"name: {role}", f"description: {desc}"]
7289
+ if role == "reviewer":
7290
+ fm.append("tools: read, bash, grep, find, ls")
7291
+ if model:
7292
+ fm.append(f"model: {model}")
7293
+ if thinking:
7294
+ fm.append(f"thinking: {thinking}")
7295
+ fm += ["prompt_mode: append", "skills: false", "run_in_background: false"]
7296
+ body = PI_CODER_BODY if role == "coder" else PI_REVIEWER_BODY
7297
+ return "---\n" + "\n".join(fm) + "\n---\n\n" + PI_AGENT_MARK + "\n\n" + body
7298
+
7299
+
7300
+ def pi_setup():
7301
+ """Subagent mode: write ~/.pi/agent/agents/coder.md and reviewer.md from the config, and install pi-subagents.
7302
+ Returns the number of problems (0 = ready)."""
7303
+ conf = config_load().get("subagent") or {}
7304
+ if not isinstance(conf, dict):
7305
+ conf = {}
7306
+ cat = models_catalog()
7307
+ problems = 0
7308
+ for role in ("coder", "reviewer"):
7309
+ rc = conf.get(role) if isinstance(conf.get(role), dict) else {}
7310
+ why = model_denied(cat, str(rc.get("model") or "").lower() or None)
7311
+ if why:
7312
+ print(f"REFUSED {role}: model {rc['model']!r} is not allowed in runs (pattern {why!r}) — pick another "
7313
+ f"in {short(user_config_file())}")
7314
+ problems += 1
7315
+ continue
7316
+ p = pi_agents_dir() / f"{role}.md"
7317
+ text = pi_agent_text(role, rc)
7318
+ if p.exists() and PI_AGENT_MARK not in p.read_text():
7319
+ print(f"KEPT {short(p)}: you edited it (no orch line in it), so orch leaves it alone")
7320
+ continue
7321
+ if p.exists() and p.read_text() == text:
7322
+ print(f"ok {short(p)}")
7323
+ continue
7324
+ p.parent.mkdir(parents=True, exist_ok=True)
7325
+ p.write_text(text)
7326
+ print(f"WROTE {short(p)} (model: {rc.get('model') or 'the same as the lead'}"
7327
+ + (f", thinking: {rc['thinking']}" if rc.get("thinking") else "") + ")")
7328
+ pi = shutil.which(pi_bin())
7329
+ if not pi:
7330
+ print(f"NO PI `{pi_bin()}` is not on PATH. Install Pi (npm install -g @earendil-works/pi-coding-agent), "
7331
+ f"then run `orch setup --mode subagent` again to add pi-subagents")
7332
+ return problems + 1
7333
+ try:
7334
+ listed = subprocess.run([pi, "list"], text=True, capture_output=True, timeout=60)
7335
+ have = "@tintinweb/pi-subagents" in (listed.stdout + listed.stderr)
7336
+ except (OSError, subprocess.TimeoutExpired):
7337
+ have = False
7338
+ if have:
7339
+ print(f"ok {PI_SUBAGENTS} is installed")
7340
+ return problems
7341
+ print(f"INSTALL {PI_SUBAGENTS} (pi install)")
7342
+ try:
7343
+ r = subprocess.run([pi, "install", PI_SUBAGENTS], text=True, capture_output=True, timeout=600)
7344
+ ok = r.returncode == 0
7345
+ out = (r.stdout + r.stderr).strip()
7346
+ except (OSError, subprocess.TimeoutExpired) as e:
7347
+ ok, out = False, str(e)
7348
+ if ok:
7349
+ print(f"INSTALLED {PI_SUBAGENTS}: restart Pi (or /reload) so it loads the Agent tool")
7350
+ return problems
7351
+ print(f"FAILED pi install {PI_SUBAGENTS}:\n" + "\n".join(out.splitlines()[-10:])
7352
+ + f"\n run it yourself: pi install {PI_SUBAGENTS}")
7353
+ return problems + 1
7354
+
7355
+
7356
+ def cmd_setup(args):
7357
+ """orch setup [--mode panes|subagent] -> get this machine ready for a mode (and save it with --mode)."""
7358
+ usage = "usage: orch setup [--mode panes|subagent]"
7359
+ args = list(args)
7360
+ flag = mode_flag(args, usage)
7361
+ if args:
7362
+ die(usage)
7363
+ if flag:
7364
+ set_mode(flag, hint=False)
7365
+ mode = flag or current_mode()[0]
7366
+ if mode == "panes":
7367
+ print("mode panes: nothing to set up here. Coders and the reviewer run in herdr panes; `orch team up` opens "
7368
+ "them when a run starts.")
7369
+ return
7370
+ sys.exit(1 if pi_setup() else 0)
7371
+
7372
+
7373
+ def cmd_mode(args):
7374
+ """orch mode -> which mode is active and where it comes from; orch mode panes|subagent -> switch."""
7375
+ if not args:
7376
+ mode, src = current_mode()
7377
+ print(f"mode: {mode} ({src})")
7378
+ return
7379
+ if len(args) != 1 or args[0].lower() not in ORCH_MODES:
7380
+ die("usage: orch mode [panes|subagent]")
7381
+ set_mode(args[0].lower())
7382
+
7383
+
7384
+ def set_mode(mode, hint=True):
7385
+ """Save the machine's mode, and switch this repo's run too when nothing in it is in progress."""
7386
+ c = config_load()
7387
+ c["mode"] = mode
7388
+ config_save(c)
7389
+ print(f"mode: {mode} (saved in {short(user_config_file())})")
7390
+ p = None
7391
+ with contextlib.suppress(Exception):
7392
+ p = _repo_state_path()
7393
+ if p:
7394
+ global ROOT, ORCH, STATE
7395
+ ROOT, ORCH, STATE = p.parent.parent, p.parent, p
7396
+ with state_lock():
7397
+ st = load()
7398
+ busy = [k for k, v in st["tasks"].items() if v["status"] in ACTIVE]
7399
+ if run_mode(st) != mode and (driver_alive() or busy):
7400
+ print(f"NOT CHANGED this repo's run stays {run_mode(st)}: "
7401
+ + (f"{', '.join(busy)} in progress" if busy else "the event manager is running")
7402
+ + ". Switch when nothing is in progress.")
7403
+ elif run_mode(st) != mode:
7404
+ st["orch_mode"] = mode
7405
+ save(st)
7406
+ print(f"this repo's run: {mode}")
7407
+ if mode == "subagent" and hint:
7408
+ missing = [r for r in ("coder", "reviewer") if not (pi_agents_dir() / f"{r}.md").exists()]
7409
+ if missing:
7410
+ print(f"NEXT run `orch setup --mode subagent`: it writes the {' and '.join(missing)} agent file(s) "
7411
+ f"and installs pi-subagents")
7412
+
7413
+
7414
+ SUBAGENT_PLAN_NOTE = """SUBAGENT MODE (Pi, one window). This replaces every herdr step below:
7415
+ - Skip `orch lead check` and `herdr agent ...`: no panes are used. Skip step 3 (Discover the team) and `orch team`.
7416
+ - Write the team exactly like this in the plan header:
7417
+ Lead: lead (pi)
7418
+ Lead mode: off
7419
+ Workers: coder (pi)
7420
+ Reviewer: reviewer (pi)
7421
+ Isolation: shared
7422
+ `coder` and `reviewer` are the Pi subagents `orch setup --mode subagent` made (~/.pi/agent/agents). They run on
7423
+ the models in ~/.config/herdr-orchestra/config.json, so keep each milestone's Tier and Model why as usual, and
7424
+ ignore `orch sync` WARNs that Workers names no model.
7425
+ - One milestone runs at a time (one folder). Everything else in this playbook applies.
7426
+
7427
+ """
7428
+
7429
+
7430
+ def subagent_ready_or_die(st):
7431
+ if run_mode(st) != "subagent":
7432
+ die("this run is in panes mode — `orch sub` is for subagent mode (`orch mode subagent`); "
7433
+ "in panes mode use `orch dispatch`")
7434
+ if st["isolation"] != "shared":
7435
+ die("subagent mode works in one folder: put `Isolation: shared` in the plan header, then `orch sync`")
7436
+ if git("rev-parse", "--abbrev-ref", "HEAD", cwd=ROOT).stdout.strip() != st["branch"]:
7437
+ die(f"not on {st['branch']} — run `orch start` first")
7438
+
7439
+
7440
+ def cmd_check(args):
7441
+ """orch check [Mn] -> run the plan's check command in the main folder: CHECK PASS / CHECK FAIL (exit 1)."""
7442
+ if len(args) > 1:
7443
+ die("usage: orch check [Mn]")
7444
+ st = load()
7445
+ if args:
7446
+ task(st, args[0])
7447
+ if not st.get("check"):
7448
+ print("CHECK NONE: the plan has no `Check command`")
7449
+ return
7450
+ ok, tail, secs = run_check(st, ROOT)
7451
+ if not driver_alive():
7452
+ with state_lock():
7453
+ st = load()
7454
+ note_green(st, ROOT, ok) # `orch finish` reuses a pass on exactly these files
7455
+ save(st)
7456
+ label = f" {args[0]}" if args else ""
7457
+ if ok:
7458
+ print(f"CHECK PASS{label} ({secs}s): {st['check']}")
7459
+ return
7460
+ print(f"CHECK FAIL{label} ({secs}s): {st['check']}\n" + "\n".join(tail.splitlines()[-30:]))
7461
+ sys.exit(1)
7462
+
7463
+
7464
+ def cmd_sub(args):
7465
+ """orch sub next | done <Mn> -> subagent mode: the next milestone and its task file; save a finished one."""
7466
+ usage = "usage: orch sub next | orch sub done <Mn>"
7467
+ sub = args[0] if args else die(usage)
7468
+ st = load()
7469
+ subagent_ready_or_die(st)
7470
+ coder = next(iter(st["workers"]), None) or die("the plan has no Workers line")
7471
+ if sub == "next":
7472
+ cur = [k for k in st["order"] if st["tasks"][k]["status"] in ("coding", "verifying")]
7473
+ if cur:
7474
+ tid = cur[0]
7475
+ t = st["tasks"][tid]
7476
+ print(f"CURRENT {tid}: {t['title']} (not saved yet: finish it, then `orch sub done {tid}`)")
7477
+ print(f"TASK {Path(t['dir']) / TASK_DIR / tid / 'task.md'}")
7478
+ print(f"REVIEW {'yes' if t.get('review') else 'no'}")
7479
+ return
7480
+ held = [k for k in st["order"] if st["tasks"][k]["status"] == "held"]
7481
+ ready = [k for k in st["order"] if st["tasks"][k]["status"] == "pending" and deps_met(st, st["tasks"][k])]
7482
+ if not ready:
7483
+ left = {k: v["status"] for k, v in st["tasks"].items() if v["status"] not in ("merged", "skipped")}
7484
+ if not left:
7485
+ print(f"ALL_DONE every milestone is saved on {st['branch']}")
7486
+ return
7487
+ if held:
7488
+ print("HELD " + ", ".join(held) + ": risky changes wait for the developer (`orch status` shows why; "
7489
+ "they run `orch approve <Mn>`, then `orch sub done <Mn>`)")
7490
+ print("WAITING " + ", ".join(f"{k} ({s})" for k, s in left.items() if k not in held)
7491
+ + " — nothing is ready to start")
7492
+ sys.exit(3)
7493
+ tid = ready[0]
7494
+ if is_dirty(ROOT):
7495
+ die("the folder has uncommitted changes that no milestone owns — commit, stash or discard them first")
7496
+ cmd_prepare([tid, coder])
7497
+ cmd_write_task([tid])
7498
+ st = load()
7499
+ t = st["tasks"][tid]
7500
+ print(f"NEXT {tid}: {t['title']}")
7501
+ print(f"TASK {Path(t['dir']) / TASK_DIR / tid / 'task.md'}")
7502
+ print(f"REVIEW {'yes' if t.get('review') else 'no'}")
7503
+ return
7504
+ if sub == "done":
7505
+ need(args, 2, "sub done <Mn>")
7506
+ tid = args[1]
7507
+ t = task(st, tid)
7508
+ if t["status"] == "merged":
7509
+ print(f"MERGED {tid} (already saved)")
7510
+ return
7511
+ if t["status"] == "coding":
7512
+ move(st, tid, "verifying")
7513
+ save(st)
7514
+ elif t["status"] not in ("verifying", "committed"):
7515
+ die(f"{tid} is {t['status']}: only a milestone from `orch sub next` can be saved"
7516
+ + (" (the developer runs `orch approve` first)" if t["status"] == "held" else ""))
7517
+ story_note(st, f"{tid} saved by the subagent run")
7518
+ save(st)
7519
+ cmd_commit([tid])
7520
+ st = load()
7521
+ left = [k for k, v in st["tasks"].items() if v["status"] not in ("merged", "skipped")]
7522
+ print("ALL_DONE every milestone is saved; write the summary, then the developer runs `orch finish`"
7523
+ if not left else "NEXT run `orch sub next`")
7524
+ return
7525
+ die(usage)
7526
+
7527
+
6945
7528
  def cmd_config(args):
6946
7529
  """orch config -> this machine's settings; orch config auto-update on|off."""
6947
7530
  if args[:1] == ["auto-update"] and args[1:2] and args[1].lower() in ("on", "off"):
@@ -7020,13 +7603,38 @@ def auto_update_at_plan():
7020
7603
  update_log(f"auto-update error: {e!r}")
7021
7604
 
7022
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
+
7023
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)
7024
7631
  if len(sys.argv) >= 2 and sys.argv[1] in ("version", "--version", "-v"):
7025
7632
  print(f"herdr-orchestra {installed_version()}")
7026
7633
  update_notice()
7027
7634
  sys.exit(0)
7028
7635
  NO_REPO_COMMANDS = {"lead": cmd_lead, "agents": cmd_agents, "doctor": cmd_doctor, "models": cmd_models,
7029
- "team": cmd_team, "update": cmd_update, "config": cmd_config}
7636
+ "team": cmd_team, "update": cmd_update, "config": cmd_config, "mode": cmd_mode,
7637
+ "setup": cmd_setup}
7030
7638
  if (len(sys.argv) >= 2 and sys.argv[1] in NO_REPO_COMMANDS # work outside a git repo
7031
7639
  and sys.argv[2:3] != ["up"] and sys.argv[2:3] != ["--crash"]): # (`orch team up` reads the run's state)
7032
7640
  try:
@@ -7038,7 +7646,7 @@ if __name__ == "__main__":
7038
7646
  sys.exit(0)
7039
7647
  if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS:
7040
7648
  print(USAGE)
7041
- 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)
7042
7650
  ROOT = main_root()
7043
7651
  ORCH = ROOT / ".orchestrate"
7044
7652
  ORCH.mkdir(exist_ok=True)