herdr-orchestra 5.10.0 → 6.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/orch CHANGED
@@ -13,7 +13,7 @@ Task status flow (every change goes through move(), which checks TRANSITIONS)
13
13
  side states: needs-answer, paused, failed, conflict, needs-fix, held (waiting for `orch approve`), skipped
14
14
  Also: .orchestrate/events.jsonl (one line per transition), driver.lock (held by autopilot while it drives).
15
15
  """
16
- import contextlib, fcntl, fnmatch, hashlib, json, os, re, shlex, shutil, signal, socket, subprocess, sys, tempfile, time
16
+ import atexit, contextlib, fcntl, fnmatch, hashlib, json, os, re, shlex, shutil, signal, socket, subprocess, sys, tempfile, time
17
17
  from pathlib import Path
18
18
 
19
19
  HERDR = os.environ.get("HERDR", "herdr")
@@ -104,6 +104,7 @@ def main_root():
104
104
  ROOT = None
105
105
  ORCH = None
106
106
  STATE = None
107
+ BG_DIR = None # .orchestrate/bg: logs and exit files of the event manager's background checks and merges
107
108
 
108
109
 
109
110
  def load():
@@ -162,7 +163,7 @@ def state_lock():
162
163
 
163
164
  # usable while autopilot drives: reads, and the lead's requests (the event manager carries them out)
164
165
  LEASE_FREE = {"status", "ready", "pick", "report", "approve", "autopilot", "events", "dispatch", "answer", "defer",
165
- "fix", "team", "resume", "bench", "stop", "doctor"}
166
+ "fix", "team", "resume", "bench", "stop", "doctor", "plan", "story", "check"}
166
167
  _LEASE = None
167
168
 
168
169
 
@@ -476,7 +477,7 @@ TRANSITIONS = {
476
477
  "skipped": {"pending"},
477
478
  "coding": {"verifying", "needs-fix", "conflict"} | _PARK,
478
479
  "verifying": {"coding", "awaiting-review", "reviewing", "committed", "merged", "needs-fix", "held"} | _PARK,
479
- "awaiting-review": {"reviewing"} | _PARK,
480
+ "awaiting-review": {"reviewing", "needs-fix"} | _PARK,
480
481
  "reviewing": {"reviewed", "awaiting-review"} | _PARK,
481
482
  "reviewed": {"needs-fix", "committed", "merged", "held"} | _PARK,
482
483
  "needs-fix": {"coding"} | _PARK,
@@ -537,6 +538,12 @@ def lead_event(st, kind, tid, text):
537
538
  del st["lead_events"][:-200]
538
539
 
539
540
 
541
+ def story_note(st, text, who="lead"):
542
+ """One line for the run diary (`orch story`, .orchestrate/story.md): what the lead (or developer) did."""
543
+ st.setdefault("story", []).append({"ts": now(), "who": who, "text": text})
544
+ del st["story"][:-500]
545
+
546
+
540
547
  def event_open(st, e):
541
548
  """A blocking event is open while its task still has that status; other events are open until read."""
542
549
  if e["kind"] in LEAD_BLOCKING:
@@ -992,6 +999,18 @@ def cmd_sync(args):
992
999
  if scope not in ("warn", "strict"):
993
1000
  errors.append(f"Scope must be warn or strict, got {scope!r}")
994
1001
  risk_hold = not get("risk hold", "on").lower().startswith("off")
1002
+ try:
1003
+ par_checks = max(1, int(re.findall(r"\d+", get("parallel checks", "1"))[0]))
1004
+ except IndexError:
1005
+ errors.append(f"Parallel checks must be a number, got {get('parallel checks')!r}")
1006
+ par_checks = 1
1007
+ if isolation == "shared":
1008
+ par_checks = 1 # one folder: two checks in it at once would see each other's files
1009
+ early_review = not get("early review", "on").lower().startswith("off")
1010
+ branch_check = (get("branch check", "auto").split() or ["auto"])[0].lower()
1011
+ if branch_check not in ("auto", "always"):
1012
+ errors.append(f"Branch check must be auto or always, got {branch_check!r}")
1013
+ auto_dispatch = not get("auto dispatch", "on").lower().startswith("off")
995
1014
  budget_s = None
996
1015
  if get("budget"):
997
1016
  bm = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*(h|m|min|hours?|minutes?)?\s*", get("budget"), re.I)
@@ -1255,6 +1274,7 @@ def cmd_sync(args):
1255
1274
  "title": title_m.group(1) if title_m else branch,
1256
1275
  "commits": commits,
1257
1276
  "mode": mode,
1277
+ "orch_mode": old.get("orch_mode") or config_mode(), # panes (herdr) or subagent (Pi): kept for the run
1258
1278
  "quick_because": quick_because if quick else None,
1259
1279
  "green_tree": old.get("green_tree"),
1260
1280
  "integration_broken": old.get("integration_broken"),
@@ -1268,6 +1288,10 @@ def cmd_sync(args):
1268
1288
  "setup_inputs": [p.strip("`") for p in re.split(r"[,\s]+", get("setup inputs")) if p.strip("`")],
1269
1289
  "scope": scope,
1270
1290
  "risk_hold": risk_hold,
1291
+ "parallel_checks": par_checks,
1292
+ "early_review": early_review,
1293
+ "branch_check": branch_check,
1294
+ "auto_dispatch": auto_dispatch,
1271
1295
  "budget_s": budget_s,
1272
1296
  "estimate_s": feature_est,
1273
1297
  "check": get("check command"),
@@ -1287,6 +1311,7 @@ def cmd_sync(args):
1287
1311
  if lead else None),
1288
1312
  "lead_mode": lead_mode,
1289
1313
  "lead_events": old.get("lead_events", []),
1314
+ "story": old.get("story", []),
1290
1315
  "lead_seq": old.get("lead_seq", 0),
1291
1316
  "lead_wake": old.get("lead_wake"),
1292
1317
  "lead_ready_told": old.get("lead_ready_told"),
@@ -1330,6 +1355,8 @@ def cmd_sync(args):
1330
1355
  "parallel": field(t, "parallel", "").lower().startswith("allow"),
1331
1356
  "tier": tiers[tid], "needs": needs[tid], "model_why": field(t, "model why"), "role": field(t, "role"),
1332
1357
  "estimate_s": estimates[tid],
1358
+ # for the developer (`orch plan show`): the milestone in plain words, and the plan's own reasons
1359
+ "plain": field(t, "plain"), "why_sep": field(t, "why separate"), "deps_text": field(t, "depends on"),
1333
1360
  }
1334
1361
  if status != st["tasks"][tid]["status"]:
1335
1362
  move(st, tid, status, {"skipped": "unticked in plan.md", "needs-answer": "open questions in plan.md"}
@@ -1781,6 +1808,7 @@ def default_base(st):
1781
1808
 
1782
1809
  def cmd_start(args):
1783
1810
  st = load()
1811
+ require_lead(st, "orch start")
1784
1812
  ensure_excluded()
1785
1813
  cur = git("rev-parse", "--abbrev-ref", "HEAD", cwd=ROOT).stdout.strip()
1786
1814
  if st.get("base") == st["branch"]:
@@ -1839,6 +1867,10 @@ def cmd_start(args):
1839
1867
  herdr = "found" if herdr_state(name) is not None else "NOT FOUND"
1840
1868
  lost = lost or herdr == "NOT FOUND"
1841
1869
  print(f"{label} {name} kind={w.get('kind')}{where} herdr={herdr}")
1870
+ if lead_on(st) and not os.environ.get("ORCH_DRIVER"):
1871
+ ld = st["lead"] # require_lead above made sure herdr can wake it
1872
+ print(f"LEAD {ld['name']} kind={ld.get('kind')} herdr="
1873
+ + (f"pane {ld['pane']}" if ld.get("pane") else "found" if ld.get("detect", True) else "detect:off"))
1842
1874
  if lost:
1843
1875
  print("HINT an agent herdr can't find: after a herdr or computer restart the panes come back without their "
1844
1876
  "names — `orch resume` names them again; `orch team up` opens the ones that are really gone")
@@ -2506,6 +2538,8 @@ def cmd_poll(args):
2506
2538
  events.append(f"IDLE {tid} agent={agent} (no sentinel after {age}s)")
2507
2539
  elif age > budget:
2508
2540
  events.append(f"TIMEOUT {tid} agent={agent} after {age // 60} min")
2541
+ if BG_DIR.is_dir() and any(BG_DIR.glob("*.exit")):
2542
+ events.append("BG_DONE - (a background check or merge of the event manager ended)")
2509
2543
  if events or changed:
2510
2544
  save(st)
2511
2545
  if not any(t.get("wait") for t in st["tasks"].values()):
@@ -2584,9 +2618,62 @@ def _finish(st, tid):
2584
2618
  save(st)
2585
2619
 
2586
2620
 
2621
+ def merge_check_needed(st, tid):
2622
+ """Whether landing Mn must run the check again on the feature branch. Not when the branch would hold exactly the
2623
+ files whose check already passed in the coder's folder: nothing else landed since the coder started (the branch
2624
+ head is part of its saved work) and its saved work is the very tree that was checked. Then a second check would
2625
+ run on the same files and can only say the same thing."""
2626
+ t = st["tasks"][tid]
2627
+ chk = t.get("chk") or {}
2628
+ if st["isolation"] != "worktree" or not st.get("check") or not chk.get("ok") or not chk.get("tree"):
2629
+ return True
2630
+ if st.get("branch_check") == "always": # the check depends on more than the files (the folder, the branch)
2631
+ return True
2632
+ src = work_ref(st, tid)
2633
+ if not src:
2634
+ return True
2635
+ tree = git("rev-parse", f"{src}^{{tree}}", cwd=ROOT, check=False).stdout.strip()
2636
+ if tree != chk["tree"]:
2637
+ return True # the work changed after its check (or the check left files behind)
2638
+ return git("merge-base", "--is-ancestor", st["branch"], src, cwd=ROOT, check=False).returncode != 0
2639
+
2640
+
2587
2641
  def cmd_merge(args):
2642
+ """orch merge Mn -> land a committed milestone on the feature branch, checked first so nothing red lands.
2643
+ The state lock is held only while the run's state or the main folder change, not while the check runs, so the
2644
+ event manager and the lead keep working meanwhile (the `merging` journal covers a crash in between)."""
2588
2645
  need(args, 1, "merge <Mn>")
2589
2646
  tid = args[0]
2647
+ with state_lock():
2648
+ st, need_check = _merge_start(tid)
2649
+ if need_check is None:
2650
+ return
2651
+ ok, tail = ensure_root_setup(st)
2652
+ secs = 0
2653
+ if ok:
2654
+ ok, tail, secs = run_check(st, ROOT)
2655
+ with state_lock():
2656
+ st2 = load()
2657
+ t = st2["tasks"][tid]
2658
+ if st.get("root_setup_hash") != st2.get("root_setup_hash"):
2659
+ st2["root_setup_hash"] = st["root_setup_hash"]
2660
+ t.setdefault("checks", []).append({"where": "branch", "ok": ok, "secs": secs, "ts": now()})
2661
+ fault("after-check")
2662
+ if not ok:
2663
+ git("reset", "--hard", "-q", "HEAD", cwd=ROOT)
2664
+ st2["merging"] = None
2665
+ _integration_failed(st2, tid, tail)
2666
+ git("commit", "-q", "-m", commit_message(st2, tid), cwd=ROOT)
2667
+ note_green(st2, ROOT, True)
2668
+ fault("after-merge-commit")
2669
+ git("update-ref", "-d", task_ref(st2, tid), cwd=ROOT, check=False)
2670
+ _finish(st2, tid)
2671
+ print(f"MERGED {tid} into {st2['branch']}")
2672
+
2673
+
2674
+ def _merge_start(tid):
2675
+ """cmd_merge's first part, under the state lock: squash Mn into the main folder. Returns (state, need_check):
2676
+ need_check None means it is done already (no changes, or no second check needed: committed and merged)."""
2590
2677
  st = load()
2591
2678
  t = task(st, tid)
2592
2679
  if st["isolation"] == "shared":
@@ -2628,23 +2715,23 @@ def cmd_merge(args):
2628
2715
  sys.exit(4)
2629
2716
  if git("diff", "--cached", "--quiet", cwd=ROOT, check=False).returncode == 0:
2630
2717
  print(f"NOTE {tid} had no changes to merge")
2718
+ elif merge_check_needed(st, tid):
2719
+ save(st)
2720
+ return st, True
2631
2721
  else:
2632
- # check BEFORE committing: nothing red ever lands on the feature branch
2633
- ok, tail = ensure_root_setup(st)
2634
- if ok:
2635
- ok, tail, secs = run_check(st, ROOT)
2636
- t.setdefault("checks", []).append({"where": "branch", "ok": ok, "secs": secs, "ts": now()})
2637
- fault("after-check")
2722
+ ok, tail = ensure_root_setup(st) # keep the main folder's dependencies current all the same
2638
2723
  if not ok:
2639
- git("reset", "--hard", "-q", "HEAD", cwd=ROOT)
2640
- st["merging"] = None
2641
- _integration_failed(st, tid, tail)
2724
+ print(f"WARN {tail.splitlines()[0] if tail else 'setup failed in the main folder'}")
2725
+ print(f"SKIPPED_CHECK {tid}: the branch gets exactly the files whose check passed in the coder's folder "
2726
+ f"(nothing else landed meanwhile), so the check was not run again")
2727
+ fault("after-check")
2642
2728
  git("commit", "-q", "-m", commit_message(st, tid), cwd=ROOT)
2643
2729
  note_green(st, ROOT, True)
2644
2730
  fault("after-merge-commit")
2645
2731
  git("update-ref", "-d", task_ref(st, tid), cwd=ROOT, check=False)
2646
2732
  _finish(st, tid)
2647
2733
  print(f"MERGED {tid} into {st['branch']}")
2734
+ return st, None
2648
2735
 
2649
2736
 
2650
2737
  def _hold(st, tid, risks):
@@ -2931,13 +3018,24 @@ def cmd_status(args):
2931
3018
  + (f"tier={t['tier'] if rank(t.get('min_tier')) <= rank(t.get('tier')) else t['min_tier'] + '^'} "
2932
3019
  if need_rank(t) else "") + t["title"]
2933
3020
  + (f" [{t['reason']}]" if t.get("reason") else "")
3021
+ + (f" [check running {_fmt_secs(now() - c['since'])} in "
3022
+ f"{'the main folder (before landing)' if c['where'] == 'branch' else 'its folder'}]"
3023
+ if (c := t.get("checking")) else "")
3024
+ + (f" [waiting {_fmt_secs(now() - w['since'])} for {w.get('behind') or w['what']}]"
3025
+ if (w := t.get("waiting")) else "")
2934
3026
  + (f" !! but {t['worker']} has no agent in herdr ({here[t['worker']]}): nothing is working on it — "
2935
3027
  f"`orch resume`" if t["status"] in ("coding", "conflict") and here.get(t.get("worker"))
2936
3028
  in ("NO AGENT", "SHELL ONLY") else ""))
2937
3029
  if lead_on(st):
2938
3030
  ev = [e for e in st["lead_events"] if event_open(st, e)]
2939
3031
  hold = undispatched(st)
3032
+ gone = lead_missing(st)
3033
+ if gone:
3034
+ print(f"!! LEAD NOT FOUND: the event manager can't wake the lead `{st['lead']['name']}` ({gone}). In the "
3035
+ f"lead's pane: herdr agent rename <its pane id> {st['lead']['name']} (`orch lead whoami` there "
3036
+ f"shows the id)")
2940
3037
  print(f" lead {st['lead']['name']}: {len(unread_events(st))} unread event(s), {len(ev)} open"
3038
+ + (" !! LEAD NOT FOUND" if gone else "")
2941
3039
  + (f"; waiting for `orch dispatch`: {', '.join(hold)}" if hold else "")
2942
3040
  + (f"; wake-up sent {lw['n']}x (last {_fmt_secs(now() - lw.get('ts', now()))} ago), not picked up yet"
2943
3041
  if unread_events(st) and (lw := st.get("lead_wake") or {}).get("n") else "")
@@ -3012,6 +3110,35 @@ def github_compare_url(remote, base, branch):
3012
3110
  return f"https://github.com/{m.group(1)}/compare/{base}...{branch}?expand=1" if m else None
3013
3111
 
3014
3112
 
3113
+ # AI tools sign their own commits and PRs ("Co-Authored-By: Claude ...", "Generated with Claude Code"). A run's
3114
+ # commits and PR are the developer's: orch never adds such lines, and keeps them out of what it publishes.
3115
+ AI_CREDIT_RE = re.compile(
3116
+ r"(?im)^[ \t]*(?:co-authored-by:[^\n]*(?:claude|anthropic|openai|codex|copilot|gemini|cursor|aider|devin|"
3117
+ r"opencode|antigravity|noreply@anthropic|noreply@openai)[^\n]*|claude-session:[^\n]*|(?:🤖\s*)?generated (?:with|by) \[?(?:claude|codex|"
3118
+ r"copilot|gemini|cursor|aider|opencode|antigravity)[^\n]*|https?://claude\.ai/code/session_\S*)[ \t]*\n?")
3119
+ AI_AUTHOR_RE = re.compile(r"(?i)noreply@anthropic\.com|noreply@openai\.com|^(?:claude|copilot|codex)\s*<")
3120
+
3121
+
3122
+ def strip_ai_credit(text):
3123
+ """The text without lines that credit an AI tool, and without the blank lines they leave at the end."""
3124
+ return AI_CREDIT_RE.sub("", text).rstrip() + "\n"
3125
+
3126
+
3127
+ def ai_credited_commits(base):
3128
+ """Commits on the run's branch that credit an AI tool (as author, or with a Co-Authored-By line). orch never
3129
+ makes them: a coder or the lead committed by itself."""
3130
+ mb = git("merge-base", base, "HEAD", cwd=ROOT, check=False).stdout.strip()
3131
+ if not mb:
3132
+ return []
3133
+ out = git("log", "--format=%h%x1f%an <%ae>%x1f%B%x1e", f"{mb}..HEAD", cwd=ROOT, check=False).stdout
3134
+ found = []
3135
+ for rec in out.split("\x1e"):
3136
+ parts = rec.strip("\n").split("\x1f")
3137
+ if len(parts) == 3 and (AI_AUTHOR_RE.search(parts[1]) or AI_CREDIT_RE.search(parts[2] + "\n")):
3138
+ found.append(f"{parts[0]} {parts[2].strip().splitlines()[0] if parts[2].strip() else ''}")
3139
+ return found
3140
+
3141
+
3015
3142
  def cmd_finish(args):
3016
3143
  """orch finish [--no-push] [--recheck] -> final check (reused when it already passed on exactly these files;
3017
3144
  --recheck runs it anyway), drop hidden refs and worktrees, push the feature branch, open a PR."""
@@ -3051,6 +3178,15 @@ def cmd_finish(args):
3051
3178
  if branch_exists(f"{st['branch']}-{tid}"):
3052
3179
  git("branch", "-D", "-q", f"{st['branch']}-{tid}", cwd=ROOT, check=False)
3053
3180
  print(f"CLEAN {st['branch']} is the only branch this run made ({len(refs)} hidden ref(s) removed)")
3181
+ credited = ai_credited_commits(base)
3182
+ if credited:
3183
+ print(f"WARN {len(credited)} commit(s) on {st['branch']} credit an AI tool (a Claude author or a "
3184
+ f"Co-Authored-By line). orch did not make them: an agent committed by itself. They go into the PR as "
3185
+ f"they are; to drop the credit, reword them before you push: " + "; ".join(credited[:5]))
3186
+ summary = ORCH / "summary.md"
3187
+ pr_body = ORCH / "pr-body.md" # the PR text: the summary, without any AI tool's credit line
3188
+ pr_body.write_text(strip_ai_credit(summary.read_text()) if summary.exists() else
3189
+ f"Built by herdr-orchestra from .orchestrate/plan.md ({len(st['order'])} milestones).\n")
3054
3190
  for ref in rescued:
3055
3191
  print(f"KEPT {ref}: unsaved files orch rescued during the run and no milestone used — look with "
3056
3192
  f"`git show --stat {ref}`, delete with `git update-ref -d {ref}`")
@@ -3066,11 +3202,9 @@ def cmd_finish(args):
3066
3202
  print(f"PUSHED {st['branch']} to origin")
3067
3203
  compare = github_compare_url(url, base, st["branch"])
3068
3204
  if compare and shutil.which("gh"):
3069
- summary = ORCH / "summary.md"
3070
- body = (["--body-file", str(summary)] if summary.exists() else
3071
- ["--body", f"Built by herdr-orchestra from .orchestrate/plan.md ({len(st['order'])} milestones)."])
3072
3205
  try:
3073
- r = subprocess.run(["gh", "pr", "create", "--base", base, "--head", st["branch"], "--title", title, *body],
3206
+ r = subprocess.run(["gh", "pr", "create", "--base", base, "--head", st["branch"], "--title", title,
3207
+ "--body-file", str(pr_body)],
3074
3208
  cwd=ROOT, text=True, capture_output=True, timeout=120)
3075
3209
  except (OSError, subprocess.TimeoutExpired) as e:
3076
3210
  r = subprocess.CompletedProcess([], 1, "", str(e))
@@ -3078,7 +3212,9 @@ def cmd_finish(args):
3078
3212
  print(f"PR {r.stdout.strip().splitlines()[-1] if r.stdout.strip() else 'created'}")
3079
3213
  return
3080
3214
  print(f"NOTE gh pr create failed: {(r.stdout + r.stderr).strip()}")
3081
- print(f"OPEN A PR from {st['branch']} into {base}" + (f": {compare}" if compare else ""))
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)")
3082
3218
 
3083
3219
 
3084
3220
  # ---------------------------------------------------------------- v4: task files, nudge, autopilot
@@ -3122,7 +3258,7 @@ WORKER_RULES = """## Rules for you (the coder)
3122
3258
 
3123
3259
  # plan.md lines that are for the lead and orch, not the coder: they stay in plan.md and task.json
3124
3260
  LEAD_ONLY_FIELDS = {"depends on", "why separate", "prefer", "tier", "needs", "model why", "estimate", "role",
3125
- "review", "parallel"}
3261
+ "review", "parallel", "plain"}
3126
3262
 
3127
3263
 
3128
3264
  def coder_section(text, drop_criteria):
@@ -3228,6 +3364,9 @@ def start_manager():
3228
3364
  detached from this shell, when none is running. Says what happened."""
3229
3365
  if driver_alive():
3230
3366
  return f"the event manager is running ({driver_line(driver_info())})"
3367
+ with contextlib.suppress(OSError, ValueError):
3368
+ if STATE.exists() and run_mode(json.loads(STATE.read_text())) == "subagent":
3369
+ return "subagent mode: no event manager (the lead drives the run with `orch sub next`)"
3231
3370
  if os.environ.get("ORCH_NO_AUTOSTART") == "1":
3232
3371
  return "the event manager is NOT running — ask the developer to run `orch autopilot` in a terminal"
3233
3372
  _rotate(ORCH / "manager.out", LOG_MAX_B // 2)
@@ -3269,6 +3408,10 @@ def cmd_dispatch(args):
3269
3408
  need(args, 1, "dispatch <Mn> [Mn...] [--to <worker>] [--tier small|medium|high]")
3270
3409
  with state_lock():
3271
3410
  st = load()
3411
+ if run_mode(st) == "subagent":
3412
+ die("this run is in subagent mode: the lead starts milestones with `orch sub next` (no event manager); "
3413
+ "`orch mode panes` switches back while nothing is in progress")
3414
+ require_lead(st, "orch dispatch")
3272
3415
  if opts.get("--to") and opts["--to"] not in st["workers"]:
3273
3416
  die(f"unknown worker {opts['--to']!r} — workers: {', '.join(st['workers'])}")
3274
3417
  if opts.get("--to"):
@@ -3292,7 +3435,11 @@ def cmd_dispatch(args):
3292
3435
  t = st["tasks"][tid]
3293
3436
  t["go"] = True
3294
3437
  t["go_ts"] = now()
3295
- t.pop("ready_ts", None)
3438
+ rt = t.pop("ready_ts", None)
3439
+ if rt and t["status"] == "pending": # it was ready and waited for this dispatch
3440
+ ws = t.setdefault("waits", {})
3441
+ ws["lead"] = ws.get("lead", 0) + max(0, now() - rt)
3442
+ t["lead_wait_s"] = max(0, now() - rt)
3296
3443
  if opts.get("--to"):
3297
3444
  t["assign"] = opts["--to"]
3298
3445
  if opts.get("--tier"):
@@ -3305,6 +3452,9 @@ def cmd_dispatch(args):
3305
3452
  print(f"DISPATCH {tid} -> {' or '.join(who) or 'nobody (every coder is off)'}"
3306
3453
  + (f" (tier {TIERS[need_rank(t) - 1]})" if need_rank(t) else "")
3307
3454
  + (f" — starts when {', '.join(waits)} merged" if waits else ""))
3455
+ story_note(st, f"{tid} ({t['title']}) was sent to start" + (f" on {opts['--to']}" if opts.get("--to") else "")
3456
+ + (f", on a {opts['--tier']} model" if opts.get("--tier") else "")
3457
+ + (f"; it starts when {', '.join(waits)} has landed" if waits else ""))
3308
3458
  if who and not opts.get("--to"):
3309
3459
  missing = [n for n in who if presence_word(st, n) not in ("ok", "detect:off")]
3310
3460
  if len(missing) == len(who):
@@ -3406,6 +3556,7 @@ def cmd_defer(args):
3406
3556
  ids = parse_defer_ids(tid, raw)
3407
3557
  record_deferral(t, tid, ids, reason)
3408
3558
  add_plan_note(tid, defer_note(t, ids, reason))
3559
+ story_note(st, f"{tid} ({t['title']}): {', '.join(ids)} left undone, as you approved ({reason[:200]})")
3409
3560
  save(st)
3410
3561
  print(f"DEFERRED {tid} {','.join(ids)}: no fix rounds for them; the summary lists them as not done "
3411
3562
  f"(follow-up). Why: {reason}")
@@ -3443,7 +3594,9 @@ def cmd_answer(args):
3443
3594
  if last in st["workers"]:
3444
3595
  t["assign"] = last
3445
3596
  t.setdefault("answers", []).append({"ts": now(), "text": text, **({"deferred": ids} if ids else {})})
3446
- _park(st, tid, "pending", f"answered: {text[:200]}")
3597
+ story_note(st, f"{tid} ({t['title']}) got the answer \"{text[:200]}\" and goes back to "
3598
+ f"{last or 'the next free coder'}" + (f"; {', '.join(ids)} left undone, as you approved" if ids else ""))
3599
+ _park(st, tid, "pending", f"answered: {text[:200]}") # saves the state
3447
3600
  print(f"ANSWERED {tid}: written to plan.md; it goes back to {last or 'the next free coder'} with its work so far")
3448
3601
  if ids:
3449
3602
  print(f"DEFERRED {tid} {','.join(ids)}: no fix rounds for them; the summary lists them as not done (follow-up)")
@@ -3508,6 +3661,7 @@ def cmd_fix(args):
3508
3661
  }
3509
3662
  if who:
3510
3663
  st["tasks"][new]["assign"] = who
3664
+ story_note(st, f"{new} added: a follow-up to {tid} (\"{text[:200]}\"), sent to {who or 'the next free coder'}")
3511
3665
  save(st)
3512
3666
  print(f"FIX {new} \"{title}\" -> {who or 'the next free coder (nobody on the team built ' + tid + ')'}; "
3513
3667
  f"added to plan.md, the check" + (" and the review" if st["tasks"][new]["review"] else "") + " still run")
@@ -3528,7 +3682,7 @@ EVENT_HELP = {
3528
3682
  "merged": "landed on the feature branch. Nothing to do unless it unlocked work listed under READY.",
3529
3683
  "ready": "milestones are ready for you: `orch dispatch <Mn>...`.",
3530
3684
  "escalated": "moved to a stronger model after its rounds ran out. Nothing to do.",
3531
- "auto-dispatched": "started without you because you did not dispatch it in time. Nothing to do.",
3685
+ "auto-dispatched": "already started by the event manager (the reason is on the line above). Nothing to do.",
3532
3686
  "reviewer-lost": "the reviewer can't be reached, so the milestone waits for review (its work is kept). Tell the "
3533
3687
  "developer the fix in the event text (usually: rename the reviewer's new pane). Review resumes "
3534
3688
  "by itself once herdr finds the reviewer again.",
@@ -3544,6 +3698,152 @@ EVENT_HELP = {
3544
3698
  }
3545
3699
 
3546
3700
 
3701
+ def say_line(st, e):
3702
+ """The event in plain words, for the developer: the lead says it in its chat, and `orch story` keeps it."""
3703
+ tid, text = e.get("task"), (e.get("text") or "").strip()
3704
+ t = st["tasks"].get(tid or "", {})
3705
+ name = f"{tid} ({t.get('title', '')})" if tid else ""
3706
+ k = e["kind"]
3707
+ if k == "merged":
3708
+ how = "its check passed" + (" and the reviewer approved it" if t.get("review") else "")
3709
+ return f"{name} is done: {how}, and it is on {st['branch']}."
3710
+ if k == "ready":
3711
+ ids = re.findall(r"M\d+", text)
3712
+ return ("Ready to start: " + ", ".join(f"{i} ({st['tasks'][i]['title']})" if i in st["tasks"] else i
3713
+ for i in ids) + ".")
3714
+ if k == "auto-dispatched":
3715
+ m = re.search(r"as soon as (.+?) landed", text)
3716
+ return (f"{name} has started by itself, because {m.group(1)} landed." if m else
3717
+ f"{name} has started by itself: {text}.")
3718
+ if k == "paused":
3719
+ if "?" in text and not text.startswith(("orch error", "result file", "review output")):
3720
+ return f"{name} is paused: the coder asks: {text}"
3721
+ return f"{name} is paused: {text}."
3722
+ if k == "failed":
3723
+ return f"{name} failed: {text}."
3724
+ if k == "held":
3725
+ return f"{name} is finished but waits for your OK, because it has a risky change: {text}."
3726
+ if k == "needs-answer":
3727
+ return f"{name} can't start yet: the plan has open questions only you can answer."
3728
+ if k == "escalated":
3729
+ return f"{name} moved to a stronger model: {text}."
3730
+ if k == "reviewer-lost":
3731
+ return f"The reviewer can't be reached, so {name} waits for its review: {text}"
3732
+ if k == "worker-lost":
3733
+ return f"A coder disappeared while working on {name}: {text}"
3734
+ if k == "herdr-restart":
3735
+ return f"Most agents disappeared at once (herdr was probably restarted): {text}"
3736
+ if k == "all_done":
3737
+ return f"Every milestone is done: {text}."
3738
+ if k == "stopped":
3739
+ return f"The event manager stopped: {text}."
3740
+ return f"{k} {name}: {text}".strip()
3741
+
3742
+
3743
+ def story_lines(st):
3744
+ """The run diary: every event in plain words, and what the lead did, in time order."""
3745
+ items = [(e["ts"], "event", say_line(st, e)) for e in st.get("lead_events", [])]
3746
+ items += [(n["ts"], n.get("who", "lead"), n["text"]) for n in st.get("story", [])]
3747
+ return [f"{time.strftime('%H:%M', time.localtime(ts))} {'what happened' if who == 'event' else 'the ' + who + ' did'}: {txt}"
3748
+ for ts, who, txt in sorted(items, key=lambda x: x[0])]
3749
+
3750
+
3751
+ def write_story(st):
3752
+ lines = story_lines(st)
3753
+ with contextlib.suppress(OSError):
3754
+ (ORCH / "story.md").write_text(f"# Run diary: {st.get('title') or st['branch']} ({st['branch']})\n\n"
3755
+ "What happened, in plain words, and what the lead did about it. "
3756
+ "`orch story` prints it; the detail is in autopilot.log.\n\n"
3757
+ + "".join(f"- {l}\n" for l in lines))
3758
+ return lines
3759
+
3760
+
3761
+ def cmd_story(args):
3762
+ """orch story -> the run diary in plain words (also saved as .orchestrate/story.md)."""
3763
+ st = load()
3764
+ lines = write_story(st)
3765
+ print(f"RUN DIARY: {st.get('title') or st['branch']} ({st['branch']})")
3766
+ print("\n".join(lines) if lines else "Nothing yet: the diary fills as the run goes (events go to the lead only "
3767
+ "with a `Lead:` line in the plan).")
3768
+
3769
+
3770
+ def _short_dur(s):
3771
+ s = int(s or 0)
3772
+ return (f"{s // 3600}h{s % 3600 // 60:02d}m" if s % 3600 // 60 else f"{s // 3600}h") if s >= 3600 else f"{max(1, s // 60)}m"
3773
+
3774
+
3775
+ def plan_steps(st, tids):
3776
+ """The plan's shape for a person: which milestones start together, step by step (a milestone starts once
3777
+ everything it depends on has landed). Milestones that already landed count as done."""
3778
+ level = {}
3779
+
3780
+ def lv(tid, seen=()):
3781
+ if tid not in level:
3782
+ deps = [d for d in st["tasks"][tid]["deps"] if d in tids and d not in seen]
3783
+ level[tid] = 1 + max((lv(d, seen + (tid,)) for d in deps), default=0)
3784
+ return level[tid]
3785
+ for tid in tids:
3786
+ lv(tid)
3787
+ return [[t for t in tids if level[t] == n] for n in range(1, max(level.values(), default=0) + 1)]
3788
+
3789
+
3790
+ def cmd_plan(args):
3791
+ """orch plan show -> the plan for a person: one short card per milestone in plain words (from each milestone's
3792
+ `Plain:` line), what it waits for and why, who builds it on which model, how long it should take, and which
3793
+ milestones run together. plan.md keeps every detail; this is the part a developer reads."""
3794
+ if args[:1] != ["show"]:
3795
+ die("usage: orch plan show")
3796
+ st = load()
3797
+ tids = [t for t in st["order"] if st["tasks"][t]["status"] != "skipped"]
3798
+ print(f"PLAN in plain words: {st.get('title') or st['branch']} — {len(tids)} milestone(s) on {st['branch']}"
3799
+ + (f", about {_short_dur(st['estimate_s'])} in all" if st.get("estimate_s") else ""))
3800
+ missing = []
3801
+ for tid in tids:
3802
+ t = st["tasks"][tid]
3803
+ plain = (t.get("plain") or "").strip()
3804
+ if not plain:
3805
+ missing.append(tid)
3806
+ print(f"\n{tid} {t['title']}" + (f" — {plain}" if plain else ""))
3807
+ if t.get("why_sep") and len(tids) > 1:
3808
+ print(f" Why its own step: {t['why_sep']}")
3809
+ deps = [d for d in t["deps"]]
3810
+ if deps:
3811
+ why = re.sub(r"^(M\d+[\s,]*)+", "", t.get("deps_text") or "").strip(" ()") if len(deps) == 1 else ""
3812
+ m = re.findall(r"M\d+\s*\(([^)]*)\)", t.get("deps_text") or "")
3813
+ why = "; ".join(m) or why
3814
+ print(f" Waits for: {', '.join(deps)}" + (f" ({why})" if why else ""))
3815
+ else:
3816
+ print(" Waits for: nothing, it can start first")
3817
+ who = []
3818
+ for n in eligible_workers(st, t):
3819
+ w = st["workers"][n]
3820
+ who.append(f"{n} ({w['model']})" if w.get("model") else n)
3821
+ bits = [f"Built by: {' or '.join(who) if who else 'the next free coder'}"]
3822
+ if t.get("tier"):
3823
+ bits.append(f"{t['tier']} model")
3824
+ if t.get("estimate_s"):
3825
+ bits.append(f"about {_short_dur(t['estimate_s'])}")
3826
+ bits.append(f"reviewed by {st['reviewer']}" if t.get("review") and st.get("reviewer") else "no review")
3827
+ print(" " + " · ".join(bits))
3828
+ if t["status"] != "pending":
3829
+ now_ = {"merged": "done, on the branch", "coding": "being built", "verifying": "being checked",
3830
+ "awaiting-review": "waiting for the reviewer", "reviewing": "being reviewed",
3831
+ "reviewed": "reviewed, landing next", "committed": "landing", "needs-fix": "being fixed",
3832
+ "paused": "paused", "failed": "failed", "held": "waiting for your OK",
3833
+ "needs-answer": "waiting for your answer"}.get(t["status"], t["status"])
3834
+ print(f" Now: {now_}" + (f" ({t['reason']})" if t.get("reason") and t["status"] != "merged" else ""))
3835
+ steps = plan_steps(st, tids)
3836
+ if len(tids) > 1:
3837
+ print("\nOrder:")
3838
+ for i, g in enumerate(steps, 1):
3839
+ print(f" {i}. {' and '.join(g)}" + (" at the same time" if len(g) > 1 else "")
3840
+ + ("" if i == 1 else f" (after {' and '.join(steps[i - 2])})"))
3841
+ if missing:
3842
+ print(f"\nWARN no `Plain:` line for {', '.join(missing)}: add one sentence in plain words to each "
3843
+ f"(what the developer will get, no code words), then `orch sync`.")
3844
+ print("\nEvery detail (files, criteria, models, notes) stays in .orchestrate/plan.md.")
3845
+
3846
+
3547
3847
  def cmd_events(args):
3548
3848
  """orch events [--peek] -> what the lead was woken for. Reading the events acknowledges them (not with --peek)."""
3549
3849
  peek = "--peek" in args
@@ -3560,6 +3860,7 @@ def cmd_events(args):
3560
3860
  head = f"#{e['id']} {e['kind'].upper()}" + (f" {e['task']} \"{tt.get('title', '')}\"" if e.get("task") else "")
3561
3861
  print(head + (f": {e['text']}" if e.get("text") else ""))
3562
3862
  print(" -> " + EVENT_HELP.get(e["kind"], "").format(t=e.get("task") or "<Mn>"))
3863
+ print(" SAY: " + say_line(st, e))
3563
3864
  print(f"EVENTS for the lead — run {st['branch']}: {len(new)} new, {len(old)} still open")
3564
3865
  for e in new:
3565
3866
  show(e)
@@ -3596,12 +3897,16 @@ def cmd_events(args):
3596
3897
  print("\n" + run_playbook_part(text, "ALL_DONE"), end="")
3597
3898
  print("Handle each event above, then STOP: you are woken again when something else happens. Never prompt a "
3598
3899
  "coder yourself and never poll.")
3900
+ if new or old:
3901
+ print("BEFORE YOU STOP, tell the developer in your chat, one short line per event: its SAY line, then what "
3902
+ "you did about it (or \"nothing for me to do\"). Never end a wake-up without saying it.")
3599
3903
  if not peek and new:
3600
3904
  for e in new:
3601
3905
  e["read"] = now()
3602
3906
  if st.get("lead_wake"):
3603
3907
  st["lead_wake"]["read_ts"] = now() # for the event manager's timing line
3604
3908
  save(st)
3909
+ write_story(st)
3605
3910
 
3606
3911
 
3607
3912
  def cmd_escalate(args):
@@ -3747,6 +4052,9 @@ def cmd_autopilot(args):
3747
4052
  """The event manager (see _autopilot). This wrapper records how it ends: every stop writes a last line to
3748
4053
  autopilot.log, a Python error writes the traceback, and a manager that was killed without a word (memory guard,
3749
4054
  a crash of the whole terminal) is found by the next one, which looks up why in the computer's own log."""
4055
+ with contextlib.suppress(OSError, ValueError):
4056
+ if STATE.exists() and run_mode(json.loads(STATE.read_text())) == "subagent":
4057
+ die("this run is in subagent mode: there is no event manager; the lead drives it with `orch sub next`")
3750
4058
  take_lease()
3751
4059
  if STATE.exists():
3752
4060
  manager_begin()
@@ -3781,8 +4089,15 @@ def cmd_autopilot(args):
3781
4089
  sys.exit(0)
3782
4090
  except SystemExit as e:
3783
4091
  code = e.code if isinstance(e.code, int) else (0 if e.code is None else 1)
3784
- ended("exit", f"exit {code}")
3785
- log_line(f"{tag} STOPPED: the event manager exited (code {code}); the line above says why")
4092
+ unwoken = ""
4093
+ with contextlib.suppress(BaseException):
4094
+ unwoken = lead_unwoken(load()) if STATE.exists() else ""
4095
+ ended("exit", f"exit {code}" + (f"; {unwoken}" if unwoken else ""))
4096
+ log_line(f"{tag} STOPPED: " + ("the event manager finished the run (exit 0)" if code == 0 else
4097
+ f"the event manager exited (code {code}); the line above says why")
4098
+ + (f" — but {unwoken}" if unwoken else ""))
4099
+ if unwoken and shutil.which("notify-send"):
4100
+ subprocess.run(["notify-send", "orch autopilot", f"{tag} {unwoken}"], capture_output=True)
3786
4101
  raise
3787
4102
  except KeyboardInterrupt:
3788
4103
  ended("stopped", "Ctrl-C")
@@ -3801,6 +4116,24 @@ def cmd_autopilot(args):
3801
4116
  raise
3802
4117
 
3803
4118
 
4119
+ def lead_unwoken(st):
4120
+ """The event manager is leaving: if the lead still has unread events, one line that says so and why (it was never
4121
+ woken because herdr can't find it, or it did not read the wake-ups), with what to do. "" when all is read."""
4122
+ if not lead_on(st):
4123
+ return ""
4124
+ un = unread_events(st)
4125
+ if not un:
4126
+ return ""
4127
+ name, lw = st["lead"]["name"], st.get("lead_wake") or {}
4128
+ gone = lead_missing(st) if lw.get("gone") or not lw.get("n") else None
4129
+ what = ", ".join(dict.fromkeys(e["kind"].upper() + (f" {e['task']}" if e.get("task") else "") for e in un[:6]))
4130
+ if gone or lw.get("gone"):
4131
+ return (f"the lead `{name}` was never woken ({gone or 'herdr could not find it'}): {len(un)} event(s) wait "
4132
+ f"for it ({what}). Name the lead's pane (herdr agent rename <its pane id> {name}), then `orch resume` "
4133
+ f"wakes it; `orch events --peek` shows them")
4134
+ return (f"the lead `{name}` has not read {len(un)} event(s) ({what}) — tell it: run `orch events`")
4135
+
4136
+
3804
4137
  def manager_begin():
3805
4138
  """The event manager starting: report a predecessor that died without a word, then record this one (pid, host,
3806
4139
  this run's processes) so the next one can do the same for it. Safe to call twice."""
@@ -3930,7 +4263,9 @@ def _autopilot(args):
3930
4263
  deliver(s_, lead, text)
3931
4264
  except DeliveryError as e:
3932
4265
  say(f"could not wake the lead ({lead}): {e} — will retry; the events are kept")
3933
- patch_state(lambda s2: s2.update(lead_wake={"upto": newest, "ts": now(), "n": n, "wait": SEND_RETRY_S}))
4266
+ gone = bool(lw.get("gone")) or "not_found" in str(e) or "not found" in str(e) # herdr has no such agent
4267
+ patch_state(lambda s2: s2.update(lead_wake={"upto": newest, "ts": now(), "n": n, "wait": SEND_RETRY_S,
4268
+ **({"gone": True} if gone else {})}))
3934
4269
  return
3935
4270
  wait = min(LEAD_REWAKE_S, LEAD_CONFIRM_S * 2 ** n) if watch else LEAD_REWAKE_S
3936
4271
  oldest = min(e["ts"] for e in un)
@@ -3952,21 +4287,31 @@ def _autopilot(args):
3952
4287
  hold = undispatched(s_)
3953
4288
  if not hold:
3954
4289
  return
3955
- late = [k for k in hold if now() - s_["tasks"][k].get("ready_ts", now()) > LEAD_WAIT_S]
4290
+ # `Auto dispatch: on` (the default): a milestone that a landing unlocked starts at once; the lead hears of
4291
+ # it (AUTO-DISPATCHED) instead of being asked. The plan already says what it is and who may take it.
4292
+ auto = [k for k in hold if s_.get("auto_dispatch", True) and s_["tasks"][k]["deps"]
4293
+ and s_["run"].get("started")]
4294
+ late = [k for k in hold if k not in auto and now() - s_["tasks"][k].get("ready_ts", now()) > LEAD_WAIT_S]
3956
4295
 
3957
4296
  def upd(s2):
3958
4297
  for k in hold:
3959
4298
  s2["tasks"][k].setdefault("ready_ts", now())
4299
+ for k in auto:
4300
+ s2["tasks"][k]["go"] = True
4301
+ lead_event(s2, "auto-dispatched", k, f"started by the event manager as soon as "
4302
+ f"{', '.join(s2['tasks'][k]['deps'])} landed (`Auto dispatch: on` in plan.md)")
3960
4303
  for k in late:
3961
4304
  s2["tasks"][k]["go"] = True
3962
4305
  lead_event(s2, "auto-dispatched", k, f"not dispatched by the lead within {LEAD_WAIT_S // 60} min")
3963
- rest = [k for k in hold if k not in late]
4306
+ rest = [k for k in hold if k not in late and k not in auto]
3964
4307
  if rest and rest != s2.get("lead_ready_told"): # once per set, not once per loop
3965
4308
  lead_event(s2, "ready", None, ", ".join(rest))
3966
4309
  s2["lead_ready_told"] = rest
3967
4310
  patch_state(upd)
3968
4311
  for k in late:
3969
4312
  say(f"{k}: the lead did not dispatch it within {LEAD_WAIT_S // 60} min -> started without it", True)
4313
+ for k in auto:
4314
+ say(f"{k}: {', '.join(s_['tasks'][k]['deps'])} landed, so it starts now (auto dispatch); the lead is told")
3970
4315
 
3971
4316
  def guarded(tid, fn):
3972
4317
  """One task's orch error never stops the run: that task is paused with the error, the rest carry on."""
@@ -4011,45 +4356,299 @@ def _autopilot(args):
4011
4356
  say(f"{tid} is HELD for your approval: {out.splitlines()[0].split('—', 1)[-1].strip()}. "
4012
4357
  f"Look at it, then run `orch approve {tid}`; autopilot keeps going with the rest", True)
4013
4358
 
4359
+ # ---- background jobs: a check or a merge runs beside the event loop, and its end is one more event (like a
4360
+ # browser's fetch: the work happens elsewhere, the callback is queued). Nothing waits for a check to finish.
4361
+ bg = {}
4362
+
4363
+ def check_slots():
4364
+ return max(1, load().get("parallel_checks", 1)) - sum(1 for j in bg.values() if j["uses_check"])
4365
+
4366
+ def checking(tid):
4367
+ return any(j["tid"] == tid and j["kind"] == "check" for j in bg.values())
4368
+
4369
+ def bg_start(name, tid, kind, shell_cmd, cwd, uses_check, on_done, timeout=None):
4370
+ log, ex = BG_DIR / f"{name}.log", BG_DIR / f"{name}.exit"
4371
+ ex.unlink(missing_ok=True)
4372
+ q = shlex.quote
4373
+ wrapped = (f"( {shell_cmd}\n) > {q(str(log))} 2>&1; echo $? > {q(str(ex))}.tmp; "
4374
+ f"mv {q(str(ex))}.tmp {q(str(ex))}")
4375
+ p = subprocess.Popen(["/bin/sh", "-c", wrapped], cwd=cwd, stdin=subprocess.DEVNULL,
4376
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
4377
+ bg[name] = {"p": p, "tid": tid, "kind": kind, "t0": time.time(), "log": log, "exit": ex,
4378
+ "uses_check": uses_check, "on_done": on_done, "timeout": timeout}
4379
+
4380
+ def bg_reap():
4381
+ """Collect the background jobs that ended and run what each one's end means."""
4382
+ for name, j in list(bg.items()):
4383
+ secs = round(time.time() - j["t0"], 1)
4384
+ timed_out = False
4385
+ if j["p"].poll() is None and j["exit"].exists():
4386
+ with contextlib.suppress(subprocess.TimeoutExpired):
4387
+ j["p"].wait(timeout=5) # it wrote its exit code: it is leaving
4388
+ if j["p"].poll() is None:
4389
+ if not (j["timeout"] and secs > j["timeout"]):
4390
+ continue
4391
+ timed_out = True
4392
+ with contextlib.suppress(OSError):
4393
+ os.killpg(j["p"].pid, signal.SIGTERM)
4394
+ with contextlib.suppress(subprocess.TimeoutExpired):
4395
+ j["p"].wait(timeout=30)
4396
+ try:
4397
+ code = int(j["exit"].read_text().strip())
4398
+ except (OSError, ValueError):
4399
+ code = 124 if timed_out else (j["p"].returncode or 1)
4400
+ try:
4401
+ out = j["log"].read_text(errors="replace")
4402
+ except OSError:
4403
+ out = ""
4404
+ if timed_out:
4405
+ code, out = 124, out + f"\ncheck command timed out after {j['timeout'] // 60} min"
4406
+ del bg[name]
4407
+ for f in (j["log"], j["exit"]):
4408
+ f.unlink(missing_ok=True)
4409
+ guarded(j["tid"], lambda: j["on_done"](code, out, secs))
4410
+
4411
+ def bg_stop():
4412
+ """The event manager is leaving: stop the checks it started (a merge is left to finish: it is journaled)."""
4413
+ for j in bg.values():
4414
+ if j["kind"] == "check" and j["p"].poll() is None:
4415
+ with contextlib.suppress(OSError):
4416
+ os.killpg(j["p"].pid, signal.SIGTERM)
4417
+
4418
+ # ---- waits: time a finished or ready milestone sat still because something else had to happen first
4419
+ def start_wait(tid, what, behind):
4420
+ s_ = load()
4421
+ if (s_["tasks"][tid].get("waiting") or {}).get("what") == what:
4422
+ return
4423
+ patch_state(lambda s2: s2["tasks"][tid].update(waiting={"what": what, "since": now(), "behind": behind}))
4424
+
4425
+ def end_wait(tid, what):
4426
+ """Close Mn's wait for `what`: add it to the milestone's waits (summary) and log it. Returns the seconds."""
4427
+ w = load()["tasks"][tid].get("waiting") or {}
4428
+ if w.get("what") != what:
4429
+ return 0
4430
+ secs = max(0, now() - w["since"])
4431
+
4432
+ def upd(s2):
4433
+ t2 = s2["tasks"][tid]
4434
+ t2.pop("waiting", None)
4435
+ ws = t2.setdefault("waits", {})
4436
+ ws[what] = ws.get(what, 0) + secs
4437
+ patch_state(upd)
4438
+ if secs and what != "reviewer": # the reviewer wait is said with the review it waited for
4439
+ say(f"{tid} waited {_fmt_secs(secs)} for {w.get('behind') or what}")
4440
+ return secs
4441
+
4442
+ def start_check(tid, d):
4443
+ """Start Mn's check in its folder, in the background. False when every check slot is busy (it waits)."""
4444
+ s_ = load()
4445
+ t_ = s_["tasks"][tid]
4446
+ k = t_["attempt"]
4447
+ if not s_.get("check"):
4448
+ check_done(tid, k, d, None, 0, "", 0)
4449
+ return True
4450
+ if check_slots() <= 0:
4451
+ busy = [j["tid"] for j in bg.values() if j["uses_check"]]
4452
+ start_wait(tid, "check slot", f"{', '.join(busy)}'s check" if busy else "a free check slot")
4453
+ return False
4454
+ end_wait(tid, "check slot")
4455
+ tree0 = tree_of(d)
4456
+ patch_state(lambda s2: s2["tasks"][tid].update(checking={"since": now(), "where": "worktree"}))
4457
+ bg_start(f"check-{tid}-{k}", tid, "check", s_["check"], d, True,
4458
+ lambda code, out, secs: check_done(tid, k, d, tree0, code, out, secs), CHECK_TIMEOUT_S)
4459
+ return True
4460
+
4461
+ def check_done(tid, k, d, tree0, code, out, secs):
4462
+ ok = code == 0
4463
+ tail = "\n".join(out.splitlines()[-60:])
4464
+ tree = tree_of(d) if ok and tree0 else None
4465
+
4466
+ def upd(s2):
4467
+ t2 = s2["tasks"][tid]
4468
+ t2.pop("checking", None)
4469
+ if s2.get("check"):
4470
+ t2.setdefault("checks", []).append({"where": "worktree", "ok": ok, "secs": secs, "ts": now()})
4471
+ # the tree is kept only when the check left the files as it found them: then a branch that gets exactly
4472
+ # these files needs no second check (merge_check_needed)
4473
+ t2["chk"] = {"attempt": k, "ok": ok, "tail": tail, "tree": tree if tree and tree == tree0 else None,
4474
+ "used": False}
4475
+ note_green(s2, d, ok)
4476
+ patch_state(upd)
4477
+ if s_check := load().get("check"):
4478
+ say(f"{tid} check {'passed' if ok else 'FAILED'} in {_fmt_secs(secs)} ({s_check})")
4479
+
4480
+ def early_review_ok(tid, t):
4481
+ s_ = load()
4482
+ return (s_.get("early_review", True) and bool(s_.get("check")) and bool(s_.get("reviewer"))
4483
+ and t["review"] and not t.get("review_ok") and not t.get("pre_conflict") and holds(s_, tid))
4484
+
4485
+ def check_fix(tid, tail, blockers=()):
4486
+ """The check failed: one fix round for the coder that holds Mn, with the reviewer's blockers if there are."""
4487
+ code, _ = run("bump", tid, "fix", ok=(0, 3))
4488
+ if code == 3:
4489
+ fail(tid, f"checks still failing after {MAX_FIX} fix rounds")
4490
+ return
4491
+ n = load()["tasks"][tid]["fix"]
4492
+ say(f"{tid} checks failed -> fix round {n}" + (f" (with the reviewer's {len(blockers)} blocker(s))"
4493
+ if blockers else ""))
4494
+ write_and_send(tid, f"fix-{n}.md",
4495
+ f"# Checks failing for {tid} (round {n})\n\nThe check command `{st['check']}` "
4496
+ f"failed. Diagnose the cause and fix it; you decide how. Don't change unrelated "
4497
+ f"code, and don't weaken or skip tests to make them pass.\n\n"
4498
+ f"```\n{tail}\n```\n"
4499
+ + ("\nThe reviewer also found these problems in the same version (it reviewed it while the "
4500
+ "check ran). Investigate each one too; if you think one is wrong, say why in your report:\n"
4501
+ + "\n".join(blockers) + "\n" if blockers else ""))
4502
+
4503
+ def early_followup(tid, t):
4504
+ """Mn's review was sent alongside its check (`Early review: on`). Match the two up. True when handle()
4505
+ has nothing more to do for Mn now."""
4506
+ if t.get("early") != t.get("attempt"):
4507
+ return False
4508
+ if checking(tid):
4509
+ return t["status"] == "reviewed" # the review is back first: it waits for the check
4510
+ chk = t.get("chk") if (t.get("chk") or {}).get("attempt") == t["attempt"] else None
4511
+ if chk is None: # the event manager restarted while the check ran: run it again
4512
+ start_check(tid, t["dir"])
4513
+ return t["status"] == "reviewed"
4514
+ if chk["ok"]:
4515
+ if not chk.get("used"):
4516
+ patch_state(lambda s_: s_["tasks"][tid]["chk"].update(used=True))
4517
+ if holds(load(), tid):
4518
+ _, hout = run("handoff", tid)
4519
+ if hout.startswith("HANDED_OFF"):
4520
+ say(f"{tid} passed its check while being reviewed; {t['worker']} is free for other work")
4521
+ return False
4522
+ if t["status"] == "reviewing":
4523
+ return True # check failed: wait for the review, then one fix round for both
4524
+ blockers = []
4525
+ if t["status"] == "reviewed":
4526
+ blockers, _, _ = review_findings(tid, t["review_round"])
4527
+ why = "the check failed" + (" while it was being reviewed" if t["status"] == "reviewed" else "")
4528
+
4529
+ def upd(s_):
4530
+ t2 = s_["tasks"][tid]
4531
+ t2["chk"]["used"] = True
4532
+ t2["early"] = None
4533
+ t2["review_ok"] = False
4534
+ if t["status"] == "reviewed": # that review round looked at a version that fails its check:
4535
+ t2["review_base"] = t2.get("review_base", 0) + 1 # it does not count against the review cap
4536
+ move(s_, tid, "needs-fix", why)
4537
+ patch_state(upd)
4538
+ check_fix(tid, chk["tail"], blockers)
4539
+ return True
4540
+
4014
4541
  def land(tid):
4542
+ """Land a milestone: commit it, then merge it onto the feature branch in the background (the merge runs the
4543
+ check there unless the files are the ones already checked). One merge at a time: they all go through the
4544
+ main folder. Waits are counted (see add_wait)."""
4015
4545
  st_ = load()
4016
- code, out = run("commit", tid, ok=(0, 7))
4017
- if code == 7:
4018
- held(tid, out)
4019
- return False
4546
+ t_ = st_["tasks"][tid]
4020
4547
  if st_["isolation"] == "shared":
4548
+ if any(j["kind"] == "check" for j in bg.values()):
4549
+ return False # a commit in the shared folder waits for a check running in it
4550
+ code, out = run("commit", tid, ok=(0, 7))
4551
+ if code == 7:
4552
+ held(tid, out)
4553
+ return False
4021
4554
  say(f"{tid} landed on {st_['branch']}")
4022
4555
  return True
4023
- code, out = run("merge", tid, ok=(0, 3, 4, 6, 7))
4556
+ if any(j["kind"] == "merge" and j["tid"] == tid for j in bg.values()):
4557
+ return None # its merge is running
4558
+ if t_["status"] != "committed":
4559
+ code, out = run("commit", tid, ok=(0, 7))
4560
+ if code == 7:
4561
+ held(tid, out)
4562
+ return False
4563
+ st_ = load()
4564
+ uses = merge_check_needed(st_, tid)
4565
+ other = next((j["tid"] for j in bg.values() if j["kind"] == "merge"), None)
4566
+ if other or (uses and check_slots() <= 0):
4567
+ start_wait(tid, "merge", f"the merge of {other}" if other else "a free check slot")
4568
+ return None
4569
+ end_wait(tid, "merge")
4570
+ if uses:
4571
+ patch_state(lambda s_: s_["tasks"][tid].update(checking={"since": now(), "where": "branch"}))
4572
+ bg_start(f"merge-{tid}", tid, "merge", shlex.join([sys.executable, os.path.abspath(__file__), "merge", tid]),
4573
+ ROOT, uses, lambda code, out, secs: merge_done(tid, code, out))
4574
+ return None
4575
+
4576
+ def merge_done(tid, code, out):
4577
+ patch_state(lambda s_: s_["tasks"][tid].pop("checking", None))
4578
+ out = out.strip()
4579
+ for l in out.splitlines():
4580
+ if l.startswith(("SKIPPED_CHECK", "SETUP ", "WARN ")):
4581
+ say(l)
4024
4582
  if code == 7:
4025
4583
  held(tid, out)
4026
- return False
4584
+ return
4027
4585
  if code == 3:
4028
- say(f"{tid} failed: {out.splitlines()[0]}", True)
4029
- return False
4586
+ say(f"{tid} failed: {out.splitlines()[0] if out else 'merge stopped'}", True)
4587
+ return
4030
4588
  if code in (4, 6):
4031
4589
  s_ = load()
4032
4590
  if code == 4 and s_["tasks"][tid].get("conflicts", 0) > MAX_CONFLICT:
4033
4591
  park(tid, "failed", f"merge conflict still unresolved after {MAX_CONFLICT} attempts")
4034
- return False
4592
+ return
4035
4593
  what = "merge conflict" if code == 4 else f"passes alone but fails the check on {s_['branch']} (not committed)"
4036
- if holds(s_, tid):
4594
+ if not s_["tasks"][tid].get("job"): # the dispatch step sent its job already, while this was collected
4595
+ say(f"{tid} {what} -> sent to {s_['tasks'][tid].get('worker') or 'the next free coder'}")
4596
+ elif holds(s_, tid):
4037
4597
  say(f"{tid} {what} -> back to {s_['tasks'][tid]['worker']}")
4038
4598
  code, out = run("send-job", tid, ok=(0, 5))
4039
4599
  sent(code, out, tid, s_["tasks"][tid]["worker"])
4040
4600
  else:
4041
4601
  say(f"{tid} {what} -> queued for the next free coder")
4042
- return False
4043
- say(f"{tid} checked and merged into {st_['branch']}")
4044
- return True
4602
+ return
4603
+ if code != 0:
4604
+ raise RuntimeError(f"orch merge {tid} -> exit {code}: {out}")
4605
+ say(f"{tid} checked and merged into {load()['branch']}")
4045
4606
 
4046
4607
  def handle(tid, t):
4608
+ if t["status"] in ("awaiting-review", "reviewing", "reviewed") and early_followup(tid, t):
4609
+ return
4047
4610
  if t["status"] == "verifying":
4611
+ if checking(tid):
4612
+ return # its check runs in the background: its end is an event
4613
+ k = t["attempt"]
4614
+ chk = t.get("chk") if (t.get("chk") or {}).get("attempt") == k else None
4615
+ if chk is None:
4616
+ if t.get("prechecked") != k:
4617
+ if not pre_check(tid, t):
4618
+ return
4619
+ patch_state(lambda s_: s_["tasks"][tid].update(prechecked=k))
4620
+ t = load()["tasks"][tid]
4621
+ if early_review_ok(tid, t):
4622
+ code, out = run("review", tid, ok=(0, 3, 5))
4623
+ patch_state(lambda s_: s_["tasks"][tid].update(early=k))
4624
+ say(out.splitlines()[-1] + (" (alongside its check: `Early review: on`)" if code == 0 else ""))
4625
+ start_check(tid, t["dir"])
4626
+ return
4627
+ post_check(tid, t, chk)
4628
+ elif t["status"] == "awaiting-review":
4629
+ code, out = run("review", tid, ok=(0, 3, 5))
4630
+ if code == 0:
4631
+ waited = end_wait(tid, "reviewer")
4632
+ say(out + (f" ({tid} waited {_fmt_secs(waited)} for the reviewer)" if waited else ""))
4633
+ elif code == 3:
4634
+ start_wait(tid, "reviewer", "the reviewer")
4635
+ elif code == 5:
4636
+ n = (load().get("reviewer_info") or {}).get("delivery_fails", 0)
4637
+ say(f"{tid}: could not reach the reviewer — retrying when herdr sees it again (or after "
4638
+ f"{SEND_RETRY_S if n < UNREACHABLE_AFTER else UNREACHABLE_MIN * 60}s)\n{out}",
4639
+ n in (1, UNREACHABLE_AFTER))
4640
+ else:
4641
+ handle_rest(tid, t)
4642
+
4643
+ def pre_check(tid, t):
4644
+ """What a finished coder's work must pass before its check runs: a usable result file, no open question,
4645
+ its scope, its acceptance criteria. False when it went back to the coder or was parked."""
4646
+ if True:
4048
4647
  res, err = read_result(t.get("last_result"))
4049
4648
  if err and err != "missing":
4050
4649
  if t.get("result_fixes", 0) >= 1:
4051
4650
  park(tid, "paused", f"result file still not usable ({err}): {t.get('last_result')}")
4052
- return
4651
+ return False
4053
4652
  patch_state(lambda s_: s_["tasks"][tid].update(result_fixes=s_["tasks"][tid].get("result_fixes", 0) + 1))
4054
4653
  say(f"{tid}: result file not usable ({err}) -> asked the coder once to rewrite it")
4055
4654
  write_and_send(tid, "result-fix-1.md",
@@ -4057,19 +4656,19 @@ def _autopilot(args):
4057
4656
  "Don't change any code for this. Write the result file the prompt names, in the "
4058
4657
  "`result_format` shape from task.json (valid JSON), plus the report, then the done "
4059
4658
  "file.\n")
4060
- return
4659
+ return False
4061
4660
  rp = t.get("last_report")
4062
4661
  rtext = Path(rp).read_text() if rp and Path(rp).exists() else ""
4063
4662
  if res:
4064
4663
  if res["status"] in ("question", "blocked"):
4065
4664
  qs = [str(q) for q in res.get("questions", []) if q] or ["the coder is " + res["status"]]
4066
4665
  park(tid, "paused", "; ".join(qs)[:400])
4067
- return
4666
+ return False
4068
4667
  else:
4069
4668
  q = [l for l in rtext.splitlines() if l.strip().upper().startswith("QUESTION:")]
4070
4669
  if q:
4071
4670
  park(tid, "paused", q[0].strip()[9:].strip() or "worker asked a question")
4072
- return
4671
+ return False
4073
4672
  # scope: the real diff against the milestone's Likely files
4074
4673
  s_ = load()
4075
4674
  allowed = s_["tasks"][tid].get("files") or []
@@ -4086,7 +4685,7 @@ def _autopilot(args):
4086
4685
  f"{', '.join(new)}.\nUndo those changes, or, if the task truly can't be done without them, "
4087
4686
  f"leave them and explain why in your report. Then run `{st['check']}`.\n"),
4088
4687
  f"still outside its scope after {MAX_FIX} fix rounds: {', '.join(new)}")
4089
- return
4688
+ return False
4090
4689
  if new:
4091
4690
  hot = [f for f in new if HOTSPOT_RE.search(f)]
4092
4691
  say(f"{tid} changed files outside its Likely files: {', '.join(new)}" +
@@ -4112,8 +4711,14 @@ def _autopilot(args):
4112
4711
  "exist), don't try again: set status `question`, say which criterion and why, and offer to "
4113
4712
  "build the rest and defer that one. The developer decides.\n"),
4114
4713
  f"acceptance criteria still not met after {MAX_FIX} fix rounds")
4115
- return
4116
- ok, tail = check(t["dir"], tid)
4714
+ return False
4715
+ return True
4716
+
4717
+ def post_check(tid, t, chk):
4718
+ """The check of a coder's work came back (verifying): on to review or landing, or a fix round."""
4719
+ patch_state(lambda s_: s_["tasks"][tid]["chk"].update(used=True))
4720
+ ok, tail = chk["ok"], chk["tail"]
4721
+ if True:
4117
4722
  if ok:
4118
4723
  if t["review"] and not t.get("review_ok"):
4119
4724
  _, hout = run("handoff", tid)
@@ -4124,27 +4729,10 @@ def _autopilot(args):
4124
4729
  else:
4125
4730
  land(tid)
4126
4731
  else:
4127
- code, out = run("bump", tid, "fix", ok=(0, 3))
4128
- if code == 3:
4129
- fail(tid, f"checks still failing after {MAX_FIX} fix rounds")
4130
- else:
4131
- n = load()["tasks"][tid]["fix"]
4132
- say(f"{tid} checks failed -> fix round {n}")
4133
- write_and_send(tid, f"fix-{n}.md",
4134
- f"# Checks failing for {tid} (round {n})\n\nThe check command `{st['check']}` "
4135
- f"failed. Diagnose the cause and fix it; you decide how. Don't change unrelated "
4136
- f"code, and don't weaken or skip tests to make them pass.\n\n"
4137
- f"```\n{tail}\n```\n")
4138
- elif t["status"] == "awaiting-review":
4139
- code, out = run("review", tid, ok=(0, 3, 5))
4140
- if code == 0:
4141
- say(out)
4142
- elif code == 5:
4143
- n = (load().get("reviewer_info") or {}).get("delivery_fails", 0)
4144
- say(f"{tid}: could not reach the reviewer — retrying when herdr sees it again (or after "
4145
- f"{SEND_RETRY_S if n < UNREACHABLE_AFTER else UNREACHABLE_MIN * 60}s)\n{out}",
4146
- n in (1, UNREACHABLE_AFTER))
4147
- elif t["status"] == "reviewed":
4732
+ check_fix(tid, tail)
4733
+
4734
+ def handle_rest(tid, t):
4735
+ if t["status"] == "reviewed":
4148
4736
  k = t["review_round"]
4149
4737
  blockers, _, known = review_findings(tid, k)
4150
4738
  where = f".orchestrate/review/{tid}/review-{k}.json"
@@ -4186,17 +4774,21 @@ def _autopilot(args):
4186
4774
  code, out = run("send-job" if kind == "FIX" else "send", tid, *([] if kind == "FIX" else ["task.md"]),
4187
4775
  ok=(0, 5))
4188
4776
  if sent(code, out, tid, worker):
4189
- go_ts = load()["tasks"][tid].get("go_ts")
4190
- if go_ts:
4191
- patch_state(lambda s_: s_["tasks"][tid].pop("go_ts", None))
4777
+ t_ = load()["tasks"][tid]
4778
+ go_ts, lw = t_.get("go_ts"), t_.get("lead_wait_s")
4779
+ if go_ts or lw is not None:
4780
+ patch_state(lambda s_: [s_["tasks"][tid].pop(k, None) for k in ("go_ts", "lead_wait_s")])
4192
4781
  say(f"{tid} fix job -> {worker}" if kind == "FIX" else f"{tid} -> {worker}"
4193
- + (f" ({max(0, now() - go_ts)}s after the lead's dispatch or answer)" if go_ts else ""))
4782
+ + (f" ({max(0, now() - go_ts)}s after the lead's dispatch or answer)" if go_ts else "")
4783
+ + (f" — it waited {_fmt_secs(lw)} for the lead's dispatch" if lw else ""))
4194
4784
 
4195
4785
  def on_event(ev):
4196
4786
  parts = ev.split()
4197
4787
  if len(parts) < 2:
4198
4788
  return
4199
4789
  kind, tid = parts[0], parts[1]
4790
+ if kind == "BG_DONE":
4791
+ return # a background check or merge ended: the next loop collects it
4200
4792
  agent = (re.search(r"agent=(\S+)", ev) or re.search(r"worker=(\S+)", ev) or [None, None])[1]
4201
4793
  s_ = load()
4202
4794
  t = s_["tasks"].get(tid, {})
@@ -4316,6 +4908,15 @@ def _autopilot(args):
4316
4908
  + str([n + (f" ({w['model']})" if w.get("model") else "") for n, w in st["workers"].items()])
4317
4909
  + (f", budget {st['budget_s'] // 60} min" if st.get("budget_s") else "")
4318
4910
  + (f"; events go to the lead ({st['lead']['name']})" if lead_on(st) else ""))
4911
+ gone = lead_missing(st)
4912
+ if gone:
4913
+ say(f"!! LEAD NOT FOUND: the lead ({st['lead']['name']}) can't be woken ({gone}). Its events are kept and wait "
4914
+ f"for it; in the lead's pane: herdr agent rename <its pane id> {st['lead']['name']}", True)
4915
+ BG_DIR.mkdir(exist_ok=True)
4916
+ for f in BG_DIR.glob("*"): # left by a manager that stopped: its jobs are gone
4917
+ f.unlink(missing_ok=True)
4918
+ patch_state(lambda s_: [t_.pop("checking", None) for t_ in s_["tasks"].values()])
4919
+ atexit.register(bg_stop)
4319
4920
  last_tick = time.time()
4320
4921
  slept = sleep_meter()
4321
4922
  waiting_since = None # set while nothing runs and the run waits for the lead or the developer
@@ -4371,8 +4972,12 @@ def _autopilot(args):
4371
4972
  f"`Budget:` in plan.md (or remove it) and run autopilot again; work in progress is kept.", True)
4372
4973
  sys.exit(3)
4373
4974
 
4374
- # 1. act on tasks waiting for us
4375
- for tid in st["order"]:
4975
+ # 1. act on tasks waiting for us: background jobs that ended first, then reviews (so the reviewer is never
4976
+ # idle while work waits for it), then the rest in plan order
4977
+ bg_reap()
4978
+ st = load()
4979
+ first = {"reviewed": 0, "awaiting-review": 1}
4980
+ for tid in sorted(st["order"], key=lambda k: first.get(st["tasks"][k]["status"], 2)):
4376
4981
  t = st["tasks"][tid]
4377
4982
  guarded(tid, lambda: handle(tid, t))
4378
4983
 
@@ -4443,6 +5048,8 @@ def _autopilot(args):
4443
5048
  + ("## Models: planned and actual\n| Milestone | Planned tier | Ran on | Escalated | Why this tier |\n"
4444
5049
  "|---|---|---|---|---|\n" + "\n".join(models) + "\n\n" if models else "") +
4445
5050
  f"## Time: estimate vs actual\n{timing}\n\n"
5051
+ f"## Waiting: time milestones sat still\nA finished or ready milestone that waited for something else "
5052
+ f"first (counted in the times above).\n{wait_table(tasks)}\n\n"
4446
5053
  f"## Checked automatically\nAlready verified by the run; nobody needs to redo these by hand.\n"
4447
5054
  f"{auto_checked(st, ok)}\n\n"
4448
5055
  f"## Run report\n```\n{report}\n```\n\n"
@@ -4482,6 +5089,11 @@ def _autopilot(args):
4482
5089
  True)
4483
5090
  break
4484
5091
  time.sleep(POLL_STEP_S)
5092
+ s_ = load()
5093
+ if unread_events(s_) and lead_missing(s_):
5094
+ say(f"ALL_DONE, but the lead ({st['lead']['name']}) was NEVER WOKEN: herdr can't find it, so it "
5095
+ f"does not know the run finished. Name its pane (herdr agent rename <its pane id> "
5096
+ f"{st['lead']['name']}), then `orch resume`", True)
4485
5097
  sys.exit(0 if ok else 3)
4486
5098
  active = [k for k, v in tasks.items() if v["status"] in ACTIVE and v["status"] != "held"]
4487
5099
  ready = [k for k, v in tasks.items() if v["status"] == "pending" and deps_met(st, v)]
@@ -4521,6 +5133,21 @@ def _autopilot(args):
4521
5133
  guarded(evtid, lambda: on_event(ev))
4522
5134
 
4523
5135
 
5136
+ WAIT_NAMES = {"check slot": "a free check slot", "merge": "the merge step", "reviewer": "the reviewer",
5137
+ "lead": "the lead's dispatch"}
5138
+
5139
+
5140
+ def wait_table(tasks):
5141
+ rows = []
5142
+ for k, v in tasks.items():
5143
+ ws = {w: s for w, s in (v.get("waits") or {}).items() if s}
5144
+ if ws:
5145
+ rows.append(f"| {k} | " + ", ".join(f"{WAIT_NAMES.get(w, w)} {_fmt_secs(s)}" for w, s in ws.items())
5146
+ + f" | {_fmt_secs(sum(ws.values()))} |")
5147
+ return ("| Milestone | Waited for | Total |\n|---|---|---|\n" + "\n".join(rows)) if rows else \
5148
+ "No milestone waited: each one went on as soon as it could."
5149
+
5150
+
4524
5151
  def _fmt_secs(s):
4525
5152
  s = int(s or 0)
4526
5153
  return f"{s // 3600}h{s % 3600 // 60:02d}m" if s >= 3600 else f"{s // 60}m{s % 60:02d}s"
@@ -4991,8 +5618,17 @@ def _herdr_json(cmd):
4991
5618
  def team_up(args):
4992
5619
  """Open a pane for every worker and the reviewer in the plan that herdr can't find: split from this pane, cd
4993
5620
  into the agent's folder (its worktree, or the repo), start it on its plan model, and give it its plan name."""
5621
+ args = list(args)
5622
+ flag = mode_flag(args, "usage: orch team up [--dry-run] [--mode panes|subagent]")
4994
5623
  dry = "--dry-run" in args
5624
+ if flag and not dry:
5625
+ set_mode(flag, hint=False)
4995
5626
  st = load()
5627
+ if (flag or run_mode(st)) == "subagent":
5628
+ print("mode subagent: no panes to open; the coder and the reviewer are Pi subagents")
5629
+ if dry:
5630
+ return
5631
+ sys.exit(1 if pi_setup() else 0)
4996
5632
  reg = registry(required=False) or {}
4997
5633
  agents = [(n, w, w.get("dir")) for n, w in st["workers"].items()]
4998
5634
  if st.get("reviewer"):
@@ -5305,12 +5941,12 @@ COMMANDS = {
5305
5941
  "send-job": cmd_send_job, "handoff": cmd_handoff, "needs-fix": cmd_needs_fix, "review-ok": cmd_review_ok,
5306
5942
  "requeue-review": cmd_requeue_review, "finish": cmd_finish, "resend": cmd_resend, "approve": cmd_approve,
5307
5943
  "report": cmd_report, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer, "defer": cmd_defer,
5308
- "escalate": cmd_escalate, "fix": cmd_fix, "team": cmd_team, "bench": cmd_bench, "stop": cmd_stop,
5309
- "doctor": lambda a: cmd_doctor_crash(a),
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),
5310
5946
  }
5311
5947
  # they lock per step instead of for the whole command (long-running, or they start the event manager after)
5312
- UNLOCKED = {"autopilot", "poll", "events", "dispatch", "answer", "defer", "fix", "team", "resume", "bench", "stop",
5313
- "doctor"}
5948
+ UNLOCKED = {"autopilot", "poll", "merge", "events", "dispatch", "answer", "defer", "fix", "team", "resume", "bench", "stop",
5949
+ "doctor", "check"}
5314
5950
 
5315
5951
  USAGE = """usage: orch <command> [args]
5316
5952
  version print the installed herdr-orchestra version
@@ -5323,15 +5959,24 @@ USAGE = """usage: orch <command> [args]
5323
5959
  lead whoami show the lead's own herdr pane and how to name it `lead`
5324
5960
  team <kind> [--coders N] [--models a,b] [--no-reviewer]
5325
5961
  the plan's team built from one installed tool: coders + reviewer on its catalog models
5326
- team up [--dry-run] open a herdr pane for every agent in the plan herdr can't find, in its folder, and name it
5962
+ team up [--dry-run] [--mode panes|subagent]
5963
+ open a herdr pane for every agent in the plan herdr can't find, in its folder, and name it
5964
+ (subagent mode: no panes; sets up the Pi coder/reviewer subagents instead)
5965
+ mode [panes|subagent] which mode runs use: panes (herdr panes, the default) or subagent (one Pi window)
5966
+ setup [--mode panes|subagent] get this machine ready for a mode; subagent: write ~/.pi/agent/agents/coder.md and
5967
+ reviewer.md from ~/.config/herdr-orchestra/config.json and install pi-subagents
5327
5968
  agents the agent registry: kinds, installed?, roles, herdr detection, launch commands
5328
5969
  agents launch <kind> [--model <id>] print the command that starts <kind> in a pane (auto-approve edits)
5329
5970
  models the model catalog: tiers (small / medium / high), ratings, and what policy forbids
5330
5971
  models show|check <id> one model's ratings and evidence / is it allowed?
5331
5972
  resume after a restart (computer off, herdr closed): name the agents' panes again, save unsaved
5332
5973
  work, re-send the tasks that were in progress and start the event manager
5974
+ story the run diary in plain words: each event and what the lead did (.orchestrate/story.md)
5975
+ plan show the plan for a person: each milestone in plain words, who builds it, how long, the order
5333
5976
  events [--peek] (lead) what you were woken for; reading acknowledges it
5334
5977
  dispatch <Mn>... [--to <worker>] [--tier <tier>] (lead) start or restart milestones; starts the event manager
5978
+ check [Mn] run the plan's check command in the main folder: CHECK PASS, or CHECK FAIL (exit 1)
5979
+ sub next | sub done <Mn> (lead, subagent mode) the next milestone and its task file | save a finished milestone
5335
5980
  answer <Mn> [--defer AC2,AC3] <text> (lead) the developer's answer: into plan.md, and back to the same coder;
5336
5981
  --defer records that the developer approved leaving those criteria undone
5337
5982
  defer <Mn> <AC2,AC3> <reason> (lead, only with the developer's yes) these criteria stay undone in Mn: no fix
@@ -5412,6 +6057,84 @@ def lead_check():
5412
6057
  + hermes_fix)
5413
6058
 
5414
6059
 
6060
+ def herdr_current_pane():
6061
+ """(pane id, sure): the pane this shell runs in. sure=False when HERDR_PANE_ID is unset, so the id herdr gave is
6062
+ the FOCUSED pane, which may be another one. (None, False) outside herdr."""
6063
+ pid = os.environ.get("HERDR_PANE_ID")
6064
+ if pid:
6065
+ return pid, True
6066
+ ok, data, out = _herdr_json([HERDR, "pane", "current"])
6067
+ if not ok:
6068
+ return None, False
6069
+ pid = _find_key(data, "pane_id") if data is not None else None
6070
+ if not pid:
6071
+ pid = (re.search(r'"?pane_id"?\s*[:=]\s*"?([\w:.-]+)', out) or [None, None])[1]
6072
+ return pid, False
6073
+
6074
+
6075
+ def name_lead(name, st=None):
6076
+ """Give this pane (the lead's own: HERDR_PANE_ID) the lead's name, so the event manager can wake it. The lead
6077
+ runs `orch lead plan`, `orch lead run`, `orch start` and `orch dispatch` from its own pane, so the pane they run
6078
+ in is the lead's; nothing depends on the lead obeying a playbook line. Never takes the name from another pane
6079
+ that runs an agent, and never renames a worker's or the reviewer's pane. Returns (ok, one line to print)."""
6080
+ pid = os.environ.get("HERDR_PANE_ID")
6081
+ if not pid:
6082
+ return False, ("HERDR_PANE_ID is not set in this shell, so orch can't tell which pane is yours and did not "
6083
+ "name it")
6084
+ ok, data, _ = _herdr_json([HERDR, "agent", "get", name])
6085
+ if ok and data is not None and not _shell_only(data):
6086
+ where = _find_key(data, "pane_id")
6087
+ if where == pid:
6088
+ return True, f"LEAD this pane ({pid}) is `{name}`: the event manager can wake it"
6089
+ if where:
6090
+ return False, (f"pane {where} already has the name `{name}` and runs an agent, so this pane ({pid}) was "
6091
+ f"not named. If that pane is not the lead: herdr agent rename {where} old-{name} && "
6092
+ f"herdr agent rename {pid} {name}")
6093
+ for n in list((st or {}).get("workers", {})) + ([st["reviewer"]] if (st or {}).get("reviewer") else []):
6094
+ if agent_pane(n) == pid:
6095
+ return False, f"this pane ({pid}) is {n}, not the lead, so it was not named `{name}`"
6096
+ ok, _, out = _herdr_json([HERDR, "agent", "rename", pid, name])
6097
+ if ok:
6098
+ return True, f"NAMED this pane ({pid}) is now `{name}`, so the event manager can wake it"
6099
+ return False, f"`herdr agent rename {pid} {name}` failed: {out.splitlines()[-1] if out else 'no answer'}"
6100
+
6101
+
6102
+ def lead_missing(st):
6103
+ """Why the event manager can't wake this run's lead (herdr has no agent with its name), or None when it can, or
6104
+ when there is nothing to check (no lead, `Lead mode: off`, a lead herdr can't watch or reached by pane id)."""
6105
+ if not lead_on(st):
6106
+ return None
6107
+ lead = st["lead"]
6108
+ if lead.get("pane") or not lead.get("detect", True):
6109
+ return None
6110
+ where, _ = herdr_presence(lead["name"])
6111
+ return {"agent": None, "shell": "only a plain shell is left in its pane",
6112
+ "gone": "herdr has no agent with this name"}[where]
6113
+
6114
+
6115
+ def require_lead(st, doing):
6116
+ """`orch start` / `orch dispatch`: a run with a lead must be able to wake it. Name this pane when it is the lead's
6117
+ (see name_lead); otherwise refuse, with the exact rename command, before anything changes. The event manager's
6118
+ own `orch start` is not checked here (its pane is not the lead's); it warns in its log instead."""
6119
+ if os.environ.get("ORCH_DRIVER"):
6120
+ return
6121
+ why = lead_missing(st)
6122
+ if not why:
6123
+ return
6124
+ name = st["lead"]["name"]
6125
+ ok, line = name_lead(name, st)
6126
+ if ok and not lead_missing(st):
6127
+ print(line)
6128
+ return
6129
+ pid, sure = herdr_current_pane()
6130
+ die(f"NO LEAD: the lead `{name}` can't be woken ({why}), so nobody would hear when work finishes or a coder asks "
6131
+ f"something. {doing} was refused; nothing changed.\n"
6132
+ f" {line}.\n"
6133
+ f" If you are the lead, name your own pane, then run it again: herdr agent rename {pid or '<your pane id>'} "
6134
+ f"{name}" + ("" if sure or not pid else " (that is the FOCUSED pane: check it is yours)") + "\n"
6135
+ f" `orch lead whoami` shows your pane. To run with no lead, put `Lead mode: off` in plan.md and `orch sync`.")
6136
+
6137
+
5415
6138
  PB_MARK_RE = re.compile(r"^<!-- (/?)(full|start|quick)(?::\s*(.*?))?\s*-->$")
5416
6139
 
5417
6140
 
@@ -5472,6 +6195,30 @@ def run_playbook_part(text, name):
5472
6195
  return "\n".join(rows) + ("\n" if rows else "")
5473
6196
 
5474
6197
 
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"
6202
+ with contextlib.suppress(Exception):
6203
+ r = git("rev-parse", "--path-format=absolute", "--git-common-dir", check=False)
6204
+ if r.returncode == 0:
6205
+ o = Path(r.stdout.strip()).parent / ".orchestrate"
6206
+ if (o / "state.json").exists():
6207
+ 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
6212
+ if not os.environ.get("HERDR_PANE_ID"):
6213
+ pid, _ = herdr_current_pane()
6214
+ if pid:
6215
+ print(f"LEAD name your pane `{name}` (HERDR_PANE_ID is unset, so orch can't tell which pane is yours): "
6216
+ f"`orch lead whoami`, then herdr agent rename <your pane id> {name}\n")
6217
+ return
6218
+ ok, line = name_lead(name, st)
6219
+ print(line + ("" if ok else f"\n Name your pane `{name}` before `orch start`: `orch lead whoami` shows it.") + "\n")
6220
+
6221
+
5475
6222
  def cmd_lead(args):
5476
6223
  """orch lead plan|run -> print the lead playbook; orch lead whoami -> this pane + how to name it `lead`."""
5477
6224
  sub = args[0] if args else ""
@@ -5488,7 +6235,15 @@ def cmd_lead(args):
5488
6235
  print(run_playbook_part(pb.read_text(), args[2] if len(args) > 2 else ""), end="")
5489
6236
  return
5490
6237
  label = f"{sub} ({part})" if part else sub
6238
+ subagent = current_mode()[0] == "subagent"
6239
+ if subagent and sub == "run":
6240
+ pb = asset("playbooks/subagent.md") or die("playbooks/subagent.md not found next to orch or in the install")
6241
+ label = "run (subagent mode)"
5491
6242
  print(f"herdr-orchestra {installed_version()} — lead playbook: {label}\n")
6243
+ if not part and not subagent:
6244
+ lead_self_name()
6245
+ if subagent and sub == "plan":
6246
+ print(SUBAGENT_PLAN_NOTE, end="")
5492
6247
  print(plan_playbook_part(pb.read_text(), part) if sub == "plan" else pb.read_text(), end="")
5493
6248
  return
5494
6249
  if sub == "check":
@@ -5513,8 +6268,13 @@ def cmd_lead(args):
5513
6268
  except (ValueError, KeyError, TypeError):
5514
6269
  pid = (re.search(r'"?pane_id"?\s*[:=]\s*"?([\w:.-]+)', out) or [None, None])[1]
5515
6270
  print(out)
5516
- print(f"This pane is YOU (the lead). Name it: herdr agent rename {pid or '<pane id>'} lead\n"
5517
- f"Write `Lead: lead (<your kind>)` in the plan header, and never prompt this pane.")
6271
+ named = False
6272
+ if os.environ.get("HERDR_PANE_ID"):
6273
+ named, line = name_lead("lead")
6274
+ print(line)
6275
+ 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.")
5518
6278
  return
5519
6279
  die("usage: orch lead plan | run | check | whoami")
5520
6280
 
@@ -6214,6 +6974,361 @@ def cmd_update(args):
6214
6974
  print(f"Go back any time: orch update --version v{cur}")
6215
6975
 
6216
6976
 
6977
+ # ---------------------------------------------------------------- run modes: panes (herdr) or subagent (one Pi window)
6978
+ # `panes` is today's workflow and the default: coders and the reviewer are agents in herdr panes, the event manager
6979
+ # drives them. `subagent` is for Pi (https://pi.dev) with the @tintinweb/pi-subagents extension: the lead stays in one
6980
+ # window and starts the coder and the reviewer as Pi subagents, one milestone at a time. Nothing about panes mode
6981
+ # changes when nobody picks subagent.
6982
+ ORCH_MODES = ("panes", "subagent")
6983
+ PI_SUBAGENTS = "npm:@tintinweb/pi-subagents"
6984
+ PI_AGENT_MARK = "<!-- written by `orch setup` (herdr-orchestra). orch rewrites this file; delete this line to keep your own edits. -->"
6985
+
6986
+
6987
+ def user_config_file():
6988
+ return Path(os.environ.get("ORCH_CONFIG_FILE") or Path.home() / ".config/herdr-orchestra/config.json")
6989
+
6990
+
6991
+ def config_load():
6992
+ try:
6993
+ data = json.loads(user_config_file().read_text())
6994
+ return data if isinstance(data, dict) else {}
6995
+ except (OSError, ValueError):
6996
+ return {}
6997
+
6998
+
6999
+ def config_save(data):
7000
+ p = user_config_file()
7001
+ p.parent.mkdir(parents=True, exist_ok=True)
7002
+ tmp = p.with_suffix(".json.tmp")
7003
+ tmp.write_text(json.dumps(data, indent=2) + "\n")
7004
+ os.replace(tmp, p)
7005
+
7006
+
7007
+ def config_mode():
7008
+ m = str(config_load().get("mode") or "panes").lower()
7009
+ return m if m in ORCH_MODES else "panes"
7010
+
7011
+
7012
+ def run_mode(st):
7013
+ """A run keeps the mode it was planned in. Runs from before 6.2.0 have no `orch_mode`: they are panes runs."""
7014
+ m = (st or {}).get("orch_mode") or "panes"
7015
+ return m if m in ORCH_MODES else "panes"
7016
+
7017
+
7018
+ def _repo_state_path():
7019
+ """.orchestrate/state.json of the repo this shell is in, or None (outside a repo, or no run yet)."""
7020
+ r = git("rev-parse", "--path-format=absolute", "--git-common-dir", check=False)
7021
+ if r.returncode != 0:
7022
+ return None
7023
+ p = Path(r.stdout.strip()).parent / ".orchestrate" / "state.json"
7024
+ return p if p.exists() else None
7025
+
7026
+
7027
+ def current_mode():
7028
+ """(mode, where it comes from): this repo's run, else the machine's config, else panes."""
7029
+ with contextlib.suppress(Exception):
7030
+ p = _repo_state_path()
7031
+ if p:
7032
+ return run_mode(json.loads(p.read_text())), "this repo's run"
7033
+ if "mode" in config_load():
7034
+ return config_mode(), short(user_config_file())
7035
+ return "panes", "default"
7036
+
7037
+
7038
+ def mode_flag(args, usage):
7039
+ """Take `--mode <panes|subagent>` (or `--mode=...`) out of args; returns the mode or None."""
7040
+ for i, a in enumerate(list(args)):
7041
+ if a == "--mode" or a.startswith("--mode="):
7042
+ val = a.split("=", 1)[1] if "=" in a else (args[i + 1] if len(args) > i + 1 else "")
7043
+ del args[i:i + (1 if "=" in a else 2)]
7044
+ val = val.lower()
7045
+ if val not in ORCH_MODES:
7046
+ die(f"--mode must be panes or subagent, got {val!r} — {usage}")
7047
+ return val
7048
+ return None
7049
+
7050
+
7051
+ def pi_bin():
7052
+ return os.environ.get("ORCH_PI") or "pi"
7053
+
7054
+
7055
+ def pi_agents_dir():
7056
+ return Path(os.environ.get("PI_CODING_AGENT_DIR") or Path.home() / ".pi/agent") / "agents"
7057
+
7058
+
7059
+ 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
7060
+ is in your prompt. Read it and build what it asks. The task says what and why; you decide how.
7061
+
7062
+ - Work only in this folder, on the branch that is checked out. Never commit, push, stash, reset or switch branches:
7063
+ orch saves your work when the milestone is done.
7064
+ - Never weaken, skip or delete tests to make the check pass.
7065
+ - Before you finish, run the check command named in the task file and fix what fails.
7066
+ - If something only the developer can decide blocks you, stop and reply `QUESTION: <the question>` with 2 or 3
7067
+ concrete options. Don't guess.
7068
+ - When the lead sends you a failing check or review findings, fix exactly those and run the check again.
7069
+
7070
+ End every reply with: the files you changed, the check result (PASS or FAIL), and one line per acceptance criterion:
7071
+ `AC<n>: met|not met - <evidence: a test, a command, or file:line>`.
7072
+ """
7073
+
7074
+ PI_REVIEWER_BODY = """You are the reviewer in a herdr-orchestra run. The lead sends you one milestone: its task file and what changed.
7075
+ You never edit files. Read the task file, then the change (`git diff HEAD` and `git status --short` for new files),
7076
+ and the code around it.
7077
+
7078
+ Reply with one line per finding, most serious first:
7079
+ - `BLOCKER: <file:line> - <problem> - <why it matters> (AC<n> when it breaks a criterion)` for a bug, a broken or
7080
+ missing acceptance criterion, a missing test for new behaviour, or a security problem.
7081
+ - `SUGGESTION: <file:line> - <idea>` for something nice to have.
7082
+ - `NO FINDINGS` when there is nothing to report.
7083
+ Then one line per acceptance criterion: `AC<n>: met|not met - <evidence>`.
7084
+ """
7085
+
7086
+
7087
+ def pi_agent_text(role, conf):
7088
+ """coder.md / reviewer.md for pi-subagents: front matter from the config, then the role's instructions."""
7089
+ model, thinking = (conf or {}).get("model"), (conf or {}).get("thinking")
7090
+ desc = ("herdr-orchestra coder: builds one milestone from its task file" if role == "coder" else
7091
+ "herdr-orchestra reviewer: reviews one milestone, never edits files")
7092
+ fm = [f"name: {role}", f"description: {desc}"]
7093
+ if role == "reviewer":
7094
+ fm.append("tools: read, bash, grep, find, ls")
7095
+ if model:
7096
+ fm.append(f"model: {model}")
7097
+ if thinking:
7098
+ fm.append(f"thinking: {thinking}")
7099
+ fm += ["prompt_mode: append", "skills: false", "run_in_background: false"]
7100
+ body = PI_CODER_BODY if role == "coder" else PI_REVIEWER_BODY
7101
+ return "---\n" + "\n".join(fm) + "\n---\n\n" + PI_AGENT_MARK + "\n\n" + body
7102
+
7103
+
7104
+ def pi_setup():
7105
+ """Subagent mode: write ~/.pi/agent/agents/coder.md and reviewer.md from the config, and install pi-subagents.
7106
+ Returns the number of problems (0 = ready)."""
7107
+ conf = config_load().get("subagent") or {}
7108
+ if not isinstance(conf, dict):
7109
+ conf = {}
7110
+ cat = models_catalog()
7111
+ problems = 0
7112
+ for role in ("coder", "reviewer"):
7113
+ rc = conf.get(role) if isinstance(conf.get(role), dict) else {}
7114
+ why = model_denied(cat, str(rc.get("model") or "").lower() or None)
7115
+ if why:
7116
+ print(f"REFUSED {role}: model {rc['model']!r} is not allowed in runs (pattern {why!r}) — pick another "
7117
+ f"in {short(user_config_file())}")
7118
+ problems += 1
7119
+ continue
7120
+ p = pi_agents_dir() / f"{role}.md"
7121
+ text = pi_agent_text(role, rc)
7122
+ if p.exists() and PI_AGENT_MARK not in p.read_text():
7123
+ print(f"KEPT {short(p)}: you edited it (no orch line in it), so orch leaves it alone")
7124
+ continue
7125
+ if p.exists() and p.read_text() == text:
7126
+ print(f"ok {short(p)}")
7127
+ continue
7128
+ p.parent.mkdir(parents=True, exist_ok=True)
7129
+ p.write_text(text)
7130
+ print(f"WROTE {short(p)} (model: {rc.get('model') or 'the same as the lead'}"
7131
+ + (f", thinking: {rc['thinking']}" if rc.get("thinking") else "") + ")")
7132
+ pi = shutil.which(pi_bin())
7133
+ if not pi:
7134
+ print(f"NO PI `{pi_bin()}` is not on PATH. Install Pi (npm install -g @earendil-works/pi-coding-agent), "
7135
+ f"then run `orch setup --mode subagent` again to add pi-subagents")
7136
+ return problems + 1
7137
+ try:
7138
+ listed = subprocess.run([pi, "list"], text=True, capture_output=True, timeout=60)
7139
+ have = "@tintinweb/pi-subagents" in (listed.stdout + listed.stderr)
7140
+ except (OSError, subprocess.TimeoutExpired):
7141
+ have = False
7142
+ if have:
7143
+ print(f"ok {PI_SUBAGENTS} is installed")
7144
+ return problems
7145
+ print(f"INSTALL {PI_SUBAGENTS} (pi install)")
7146
+ try:
7147
+ r = subprocess.run([pi, "install", PI_SUBAGENTS], text=True, capture_output=True, timeout=600)
7148
+ ok = r.returncode == 0
7149
+ out = (r.stdout + r.stderr).strip()
7150
+ except (OSError, subprocess.TimeoutExpired) as e:
7151
+ ok, out = False, str(e)
7152
+ if ok:
7153
+ print(f"INSTALLED {PI_SUBAGENTS}: restart Pi (or /reload) so it loads the Agent tool")
7154
+ return problems
7155
+ print(f"FAILED pi install {PI_SUBAGENTS}:\n" + "\n".join(out.splitlines()[-10:])
7156
+ + f"\n run it yourself: pi install {PI_SUBAGENTS}")
7157
+ return problems + 1
7158
+
7159
+
7160
+ def cmd_setup(args):
7161
+ """orch setup [--mode panes|subagent] -> get this machine ready for a mode (and save it with --mode)."""
7162
+ usage = "usage: orch setup [--mode panes|subagent]"
7163
+ args = list(args)
7164
+ flag = mode_flag(args, usage)
7165
+ if args:
7166
+ die(usage)
7167
+ if flag:
7168
+ set_mode(flag, hint=False)
7169
+ mode = flag or current_mode()[0]
7170
+ if mode == "panes":
7171
+ print("mode panes: nothing to set up here. Coders and the reviewer run in herdr panes; `orch team up` opens "
7172
+ "them when a run starts.")
7173
+ return
7174
+ sys.exit(1 if pi_setup() else 0)
7175
+
7176
+
7177
+ def cmd_mode(args):
7178
+ """orch mode -> which mode is active and where it comes from; orch mode panes|subagent -> switch."""
7179
+ if not args:
7180
+ mode, src = current_mode()
7181
+ print(f"mode: {mode} ({src})")
7182
+ return
7183
+ if len(args) != 1 or args[0].lower() not in ORCH_MODES:
7184
+ die("usage: orch mode [panes|subagent]")
7185
+ set_mode(args[0].lower())
7186
+
7187
+
7188
+ def set_mode(mode, hint=True):
7189
+ """Save the machine's mode, and switch this repo's run too when nothing in it is in progress."""
7190
+ c = config_load()
7191
+ c["mode"] = mode
7192
+ config_save(c)
7193
+ print(f"mode: {mode} (saved in {short(user_config_file())})")
7194
+ p = None
7195
+ with contextlib.suppress(Exception):
7196
+ p = _repo_state_path()
7197
+ if p:
7198
+ global ROOT, ORCH, STATE
7199
+ ROOT, ORCH, STATE = p.parent.parent, p.parent, p
7200
+ with state_lock():
7201
+ st = load()
7202
+ busy = [k for k, v in st["tasks"].items() if v["status"] in ACTIVE]
7203
+ if run_mode(st) != mode and (driver_alive() or busy):
7204
+ print(f"NOT CHANGED this repo's run stays {run_mode(st)}: "
7205
+ + (f"{', '.join(busy)} in progress" if busy else "the event manager is running")
7206
+ + ". Switch when nothing is in progress.")
7207
+ elif run_mode(st) != mode:
7208
+ st["orch_mode"] = mode
7209
+ save(st)
7210
+ print(f"this repo's run: {mode}")
7211
+ if mode == "subagent" and hint:
7212
+ missing = [r for r in ("coder", "reviewer") if not (pi_agents_dir() / f"{r}.md").exists()]
7213
+ if missing:
7214
+ print(f"NEXT run `orch setup --mode subagent`: it writes the {' and '.join(missing)} agent file(s) "
7215
+ f"and installs pi-subagents")
7216
+
7217
+
7218
+ SUBAGENT_PLAN_NOTE = """SUBAGENT MODE (Pi, one window). This replaces every herdr step below:
7219
+ - Skip `orch lead check` and `herdr agent ...`: no panes are used. Skip step 3 (Discover the team) and `orch team`.
7220
+ - Write the team exactly like this in the plan header:
7221
+ Lead: lead (pi)
7222
+ Lead mode: off
7223
+ Workers: coder (pi)
7224
+ Reviewer: reviewer (pi)
7225
+ Isolation: shared
7226
+ `coder` and `reviewer` are the Pi subagents `orch setup --mode subagent` made (~/.pi/agent/agents). They run on
7227
+ the models in ~/.config/herdr-orchestra/config.json, so keep each milestone's Tier and Model why as usual, and
7228
+ ignore `orch sync` WARNs that Workers names no model.
7229
+ - One milestone runs at a time (one folder). Everything else in this playbook applies.
7230
+
7231
+ """
7232
+
7233
+
7234
+ def subagent_ready_or_die(st):
7235
+ if run_mode(st) != "subagent":
7236
+ die("this run is in panes mode — `orch sub` is for subagent mode (`orch mode subagent`); "
7237
+ "in panes mode use `orch dispatch`")
7238
+ if st["isolation"] != "shared":
7239
+ die("subagent mode works in one folder: put `Isolation: shared` in the plan header, then `orch sync`")
7240
+ if git("rev-parse", "--abbrev-ref", "HEAD", cwd=ROOT).stdout.strip() != st["branch"]:
7241
+ die(f"not on {st['branch']} — run `orch start` first")
7242
+
7243
+
7244
+ def cmd_check(args):
7245
+ """orch check [Mn] -> run the plan's check command in the main folder: CHECK PASS / CHECK FAIL (exit 1)."""
7246
+ if len(args) > 1:
7247
+ die("usage: orch check [Mn]")
7248
+ st = load()
7249
+ if args:
7250
+ task(st, args[0])
7251
+ if not st.get("check"):
7252
+ print("CHECK NONE: the plan has no `Check command`")
7253
+ return
7254
+ ok, tail, secs = run_check(st, ROOT)
7255
+ if not driver_alive():
7256
+ with state_lock():
7257
+ st = load()
7258
+ note_green(st, ROOT, ok) # `orch finish` reuses a pass on exactly these files
7259
+ save(st)
7260
+ label = f" {args[0]}" if args else ""
7261
+ if ok:
7262
+ print(f"CHECK PASS{label} ({secs}s): {st['check']}")
7263
+ return
7264
+ print(f"CHECK FAIL{label} ({secs}s): {st['check']}\n" + "\n".join(tail.splitlines()[-30:]))
7265
+ sys.exit(1)
7266
+
7267
+
7268
+ def cmd_sub(args):
7269
+ """orch sub next | done <Mn> -> subagent mode: the next milestone and its task file; save a finished one."""
7270
+ usage = "usage: orch sub next | orch sub done <Mn>"
7271
+ sub = args[0] if args else die(usage)
7272
+ st = load()
7273
+ subagent_ready_or_die(st)
7274
+ coder = next(iter(st["workers"]), None) or die("the plan has no Workers line")
7275
+ if sub == "next":
7276
+ cur = [k for k in st["order"] if st["tasks"][k]["status"] in ("coding", "verifying")]
7277
+ if cur:
7278
+ tid = cur[0]
7279
+ t = st["tasks"][tid]
7280
+ print(f"CURRENT {tid}: {t['title']} (not saved yet: finish it, then `orch sub done {tid}`)")
7281
+ print(f"TASK {Path(t['dir']) / TASK_DIR / tid / 'task.md'}")
7282
+ print(f"REVIEW {'yes' if t.get('review') else 'no'}")
7283
+ return
7284
+ held = [k for k in st["order"] if st["tasks"][k]["status"] == "held"]
7285
+ ready = [k for k in st["order"] if st["tasks"][k]["status"] == "pending" and deps_met(st, st["tasks"][k])]
7286
+ if not ready:
7287
+ left = {k: v["status"] for k, v in st["tasks"].items() if v["status"] not in ("merged", "skipped")}
7288
+ if not left:
7289
+ print(f"ALL_DONE every milestone is saved on {st['branch']}")
7290
+ return
7291
+ if held:
7292
+ print("HELD " + ", ".join(held) + ": risky changes wait for the developer (`orch status` shows why; "
7293
+ "they run `orch approve <Mn>`, then `orch sub done <Mn>`)")
7294
+ print("WAITING " + ", ".join(f"{k} ({s})" for k, s in left.items() if k not in held)
7295
+ + " — nothing is ready to start")
7296
+ sys.exit(3)
7297
+ tid = ready[0]
7298
+ if is_dirty(ROOT):
7299
+ die("the folder has uncommitted changes that no milestone owns — commit, stash or discard them first")
7300
+ cmd_prepare([tid, coder])
7301
+ cmd_write_task([tid])
7302
+ st = load()
7303
+ t = st["tasks"][tid]
7304
+ print(f"NEXT {tid}: {t['title']}")
7305
+ print(f"TASK {Path(t['dir']) / TASK_DIR / tid / 'task.md'}")
7306
+ print(f"REVIEW {'yes' if t.get('review') else 'no'}")
7307
+ return
7308
+ if sub == "done":
7309
+ need(args, 2, "sub done <Mn>")
7310
+ tid = args[1]
7311
+ t = task(st, tid)
7312
+ if t["status"] == "merged":
7313
+ print(f"MERGED {tid} (already saved)")
7314
+ return
7315
+ if t["status"] == "coding":
7316
+ move(st, tid, "verifying")
7317
+ save(st)
7318
+ elif t["status"] not in ("verifying", "committed"):
7319
+ die(f"{tid} is {t['status']}: only a milestone from `orch sub next` can be saved"
7320
+ + (" (the developer runs `orch approve` first)" if t["status"] == "held" else ""))
7321
+ story_note(st, f"{tid} saved by the subagent run")
7322
+ save(st)
7323
+ cmd_commit([tid])
7324
+ st = load()
7325
+ left = [k for k, v in st["tasks"].items() if v["status"] not in ("merged", "skipped")]
7326
+ print("ALL_DONE every milestone is saved; write the summary, then the developer runs `orch finish`"
7327
+ if not left else "NEXT run `orch sub next`")
7328
+ return
7329
+ die(usage)
7330
+
7331
+
6217
7332
  def cmd_config(args):
6218
7333
  """orch config -> this machine's settings; orch config auto-update on|off."""
6219
7334
  if args[:1] == ["auto-update"] and args[1:2] and args[1].lower() in ("on", "off"):
@@ -6298,7 +7413,8 @@ if __name__ == "__main__":
6298
7413
  update_notice()
6299
7414
  sys.exit(0)
6300
7415
  NO_REPO_COMMANDS = {"lead": cmd_lead, "agents": cmd_agents, "doctor": cmd_doctor, "models": cmd_models,
6301
- "team": cmd_team, "update": cmd_update, "config": cmd_config}
7416
+ "team": cmd_team, "update": cmd_update, "config": cmd_config, "mode": cmd_mode,
7417
+ "setup": cmd_setup}
6302
7418
  if (len(sys.argv) >= 2 and sys.argv[1] in NO_REPO_COMMANDS # work outside a git repo
6303
7419
  and sys.argv[2:3] != ["up"] and sys.argv[2:3] != ["--crash"]): # (`orch team up` reads the run's state)
6304
7420
  try:
@@ -6315,6 +7431,7 @@ if __name__ == "__main__":
6315
7431
  ORCH = ROOT / ".orchestrate"
6316
7432
  ORCH.mkdir(exist_ok=True)
6317
7433
  STATE = ORCH / "state.json"
7434
+ BG_DIR = ORCH / "bg"
6318
7435
  if sys.argv[1] not in LEASE_FREE:
6319
7436
  require_driver()
6320
7437
  try: