herdr-orchestra 5.10.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/orch CHANGED
@@ -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"}
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)
@@ -1268,6 +1287,10 @@ def cmd_sync(args):
1268
1287
  "setup_inputs": [p.strip("`") for p in re.split(r"[,\s]+", get("setup inputs")) if p.strip("`")],
1269
1288
  "scope": scope,
1270
1289
  "risk_hold": risk_hold,
1290
+ "parallel_checks": par_checks,
1291
+ "early_review": early_review,
1292
+ "branch_check": branch_check,
1293
+ "auto_dispatch": auto_dispatch,
1271
1294
  "budget_s": budget_s,
1272
1295
  "estimate_s": feature_est,
1273
1296
  "check": get("check command"),
@@ -1287,6 +1310,7 @@ def cmd_sync(args):
1287
1310
  if lead else None),
1288
1311
  "lead_mode": lead_mode,
1289
1312
  "lead_events": old.get("lead_events", []),
1313
+ "story": old.get("story", []),
1290
1314
  "lead_seq": old.get("lead_seq", 0),
1291
1315
  "lead_wake": old.get("lead_wake"),
1292
1316
  "lead_ready_told": old.get("lead_ready_told"),
@@ -1330,6 +1354,8 @@ def cmd_sync(args):
1330
1354
  "parallel": field(t, "parallel", "").lower().startswith("allow"),
1331
1355
  "tier": tiers[tid], "needs": needs[tid], "model_why": field(t, "model why"), "role": field(t, "role"),
1332
1356
  "estimate_s": estimates[tid],
1357
+ # for the developer (`orch plan show`): the milestone in plain words, and the plan's own reasons
1358
+ "plain": field(t, "plain"), "why_sep": field(t, "why separate"), "deps_text": field(t, "depends on"),
1333
1359
  }
1334
1360
  if status != st["tasks"][tid]["status"]:
1335
1361
  move(st, tid, status, {"skipped": "unticked in plan.md", "needs-answer": "open questions in plan.md"}
@@ -1781,6 +1807,7 @@ def default_base(st):
1781
1807
 
1782
1808
  def cmd_start(args):
1783
1809
  st = load()
1810
+ require_lead(st, "orch start")
1784
1811
  ensure_excluded()
1785
1812
  cur = git("rev-parse", "--abbrev-ref", "HEAD", cwd=ROOT).stdout.strip()
1786
1813
  if st.get("base") == st["branch"]:
@@ -1839,6 +1866,10 @@ def cmd_start(args):
1839
1866
  herdr = "found" if herdr_state(name) is not None else "NOT FOUND"
1840
1867
  lost = lost or herdr == "NOT FOUND"
1841
1868
  print(f"{label} {name} kind={w.get('kind')}{where} herdr={herdr}")
1869
+ if lead_on(st) and not os.environ.get("ORCH_DRIVER"):
1870
+ ld = st["lead"] # require_lead above made sure herdr can wake it
1871
+ print(f"LEAD {ld['name']} kind={ld.get('kind')} herdr="
1872
+ + (f"pane {ld['pane']}" if ld.get("pane") else "found" if ld.get("detect", True) else "detect:off"))
1842
1873
  if lost:
1843
1874
  print("HINT an agent herdr can't find: after a herdr or computer restart the panes come back without their "
1844
1875
  "names — `orch resume` names them again; `orch team up` opens the ones that are really gone")
@@ -2506,6 +2537,8 @@ def cmd_poll(args):
2506
2537
  events.append(f"IDLE {tid} agent={agent} (no sentinel after {age}s)")
2507
2538
  elif age > budget:
2508
2539
  events.append(f"TIMEOUT {tid} agent={agent} after {age // 60} min")
2540
+ if BG_DIR.is_dir() and any(BG_DIR.glob("*.exit")):
2541
+ events.append("BG_DONE - (a background check or merge of the event manager ended)")
2509
2542
  if events or changed:
2510
2543
  save(st)
2511
2544
  if not any(t.get("wait") for t in st["tasks"].values()):
@@ -2584,9 +2617,62 @@ def _finish(st, tid):
2584
2617
  save(st)
2585
2618
 
2586
2619
 
2620
+ def merge_check_needed(st, tid):
2621
+ """Whether landing Mn must run the check again on the feature branch. Not when the branch would hold exactly the
2622
+ files whose check already passed in the coder's folder: nothing else landed since the coder started (the branch
2623
+ head is part of its saved work) and its saved work is the very tree that was checked. Then a second check would
2624
+ run on the same files and can only say the same thing."""
2625
+ t = st["tasks"][tid]
2626
+ chk = t.get("chk") or {}
2627
+ if st["isolation"] != "worktree" or not st.get("check") or not chk.get("ok") or not chk.get("tree"):
2628
+ return True
2629
+ if st.get("branch_check") == "always": # the check depends on more than the files (the folder, the branch)
2630
+ return True
2631
+ src = work_ref(st, tid)
2632
+ if not src:
2633
+ return True
2634
+ tree = git("rev-parse", f"{src}^{{tree}}", cwd=ROOT, check=False).stdout.strip()
2635
+ if tree != chk["tree"]:
2636
+ return True # the work changed after its check (or the check left files behind)
2637
+ return git("merge-base", "--is-ancestor", st["branch"], src, cwd=ROOT, check=False).returncode != 0
2638
+
2639
+
2587
2640
  def cmd_merge(args):
2641
+ """orch merge Mn -> land a committed milestone on the feature branch, checked first so nothing red lands.
2642
+ The state lock is held only while the run's state or the main folder change, not while the check runs, so the
2643
+ event manager and the lead keep working meanwhile (the `merging` journal covers a crash in between)."""
2588
2644
  need(args, 1, "merge <Mn>")
2589
2645
  tid = args[0]
2646
+ with state_lock():
2647
+ st, need_check = _merge_start(tid)
2648
+ if need_check is None:
2649
+ return
2650
+ ok, tail = ensure_root_setup(st)
2651
+ secs = 0
2652
+ if ok:
2653
+ ok, tail, secs = run_check(st, ROOT)
2654
+ with state_lock():
2655
+ st2 = load()
2656
+ t = st2["tasks"][tid]
2657
+ if st.get("root_setup_hash") != st2.get("root_setup_hash"):
2658
+ st2["root_setup_hash"] = st["root_setup_hash"]
2659
+ t.setdefault("checks", []).append({"where": "branch", "ok": ok, "secs": secs, "ts": now()})
2660
+ fault("after-check")
2661
+ if not ok:
2662
+ git("reset", "--hard", "-q", "HEAD", cwd=ROOT)
2663
+ st2["merging"] = None
2664
+ _integration_failed(st2, tid, tail)
2665
+ git("commit", "-q", "-m", commit_message(st2, tid), cwd=ROOT)
2666
+ note_green(st2, ROOT, True)
2667
+ fault("after-merge-commit")
2668
+ git("update-ref", "-d", task_ref(st2, tid), cwd=ROOT, check=False)
2669
+ _finish(st2, tid)
2670
+ print(f"MERGED {tid} into {st2['branch']}")
2671
+
2672
+
2673
+ def _merge_start(tid):
2674
+ """cmd_merge's first part, under the state lock: squash Mn into the main folder. Returns (state, need_check):
2675
+ need_check None means it is done already (no changes, or no second check needed: committed and merged)."""
2590
2676
  st = load()
2591
2677
  t = task(st, tid)
2592
2678
  if st["isolation"] == "shared":
@@ -2628,23 +2714,23 @@ def cmd_merge(args):
2628
2714
  sys.exit(4)
2629
2715
  if git("diff", "--cached", "--quiet", cwd=ROOT, check=False).returncode == 0:
2630
2716
  print(f"NOTE {tid} had no changes to merge")
2717
+ elif merge_check_needed(st, tid):
2718
+ save(st)
2719
+ return st, True
2631
2720
  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")
2721
+ ok, tail = ensure_root_setup(st) # keep the main folder's dependencies current all the same
2638
2722
  if not ok:
2639
- git("reset", "--hard", "-q", "HEAD", cwd=ROOT)
2640
- st["merging"] = None
2641
- _integration_failed(st, tid, tail)
2723
+ print(f"WARN {tail.splitlines()[0] if tail else 'setup failed in the main folder'}")
2724
+ print(f"SKIPPED_CHECK {tid}: the branch gets exactly the files whose check passed in the coder's folder "
2725
+ f"(nothing else landed meanwhile), so the check was not run again")
2726
+ fault("after-check")
2642
2727
  git("commit", "-q", "-m", commit_message(st, tid), cwd=ROOT)
2643
2728
  note_green(st, ROOT, True)
2644
2729
  fault("after-merge-commit")
2645
2730
  git("update-ref", "-d", task_ref(st, tid), cwd=ROOT, check=False)
2646
2731
  _finish(st, tid)
2647
2732
  print(f"MERGED {tid} into {st['branch']}")
2733
+ return st, None
2648
2734
 
2649
2735
 
2650
2736
  def _hold(st, tid, risks):
@@ -2931,13 +3017,24 @@ def cmd_status(args):
2931
3017
  + (f"tier={t['tier'] if rank(t.get('min_tier')) <= rank(t.get('tier')) else t['min_tier'] + '^'} "
2932
3018
  if need_rank(t) else "") + t["title"]
2933
3019
  + (f" [{t['reason']}]" if t.get("reason") else "")
3020
+ + (f" [check running {_fmt_secs(now() - c['since'])} in "
3021
+ f"{'the main folder (before landing)' if c['where'] == 'branch' else 'its folder'}]"
3022
+ if (c := t.get("checking")) else "")
3023
+ + (f" [waiting {_fmt_secs(now() - w['since'])} for {w.get('behind') or w['what']}]"
3024
+ if (w := t.get("waiting")) else "")
2934
3025
  + (f" !! but {t['worker']} has no agent in herdr ({here[t['worker']]}): nothing is working on it — "
2935
3026
  f"`orch resume`" if t["status"] in ("coding", "conflict") and here.get(t.get("worker"))
2936
3027
  in ("NO AGENT", "SHELL ONLY") else ""))
2937
3028
  if lead_on(st):
2938
3029
  ev = [e for e in st["lead_events"] if event_open(st, e)]
2939
3030
  hold = undispatched(st)
3031
+ gone = lead_missing(st)
3032
+ if gone:
3033
+ print(f"!! LEAD NOT FOUND: the event manager can't wake the lead `{st['lead']['name']}` ({gone}). In the "
3034
+ f"lead's pane: herdr agent rename <its pane id> {st['lead']['name']} (`orch lead whoami` there "
3035
+ f"shows the id)")
2940
3036
  print(f" lead {st['lead']['name']}: {len(unread_events(st))} unread event(s), {len(ev)} open"
3037
+ + (" !! LEAD NOT FOUND" if gone else "")
2941
3038
  + (f"; waiting for `orch dispatch`: {', '.join(hold)}" if hold else "")
2942
3039
  + (f"; wake-up sent {lw['n']}x (last {_fmt_secs(now() - lw.get('ts', now()))} ago), not picked up yet"
2943
3040
  if unread_events(st) and (lw := st.get("lead_wake") or {}).get("n") else "")
@@ -3012,6 +3109,35 @@ def github_compare_url(remote, base, branch):
3012
3109
  return f"https://github.com/{m.group(1)}/compare/{base}...{branch}?expand=1" if m else None
3013
3110
 
3014
3111
 
3112
+ # AI tools sign their own commits and PRs ("Co-Authored-By: Claude ...", "Generated with Claude Code"). A run's
3113
+ # commits and PR are the developer's: orch never adds such lines, and keeps them out of what it publishes.
3114
+ AI_CREDIT_RE = re.compile(
3115
+ r"(?im)^[ \t]*(?:co-authored-by:[^\n]*(?:claude|anthropic|openai|codex|copilot|gemini|cursor|aider|devin|"
3116
+ r"opencode|antigravity|noreply@anthropic|noreply@openai)[^\n]*|claude-session:[^\n]*|(?:🤖\s*)?generated (?:with|by) \[?(?:claude|codex|"
3117
+ r"copilot|gemini|cursor|aider|opencode|antigravity)[^\n]*|https?://claude\.ai/code/session_\S*)[ \t]*\n?")
3118
+ AI_AUTHOR_RE = re.compile(r"(?i)noreply@anthropic\.com|noreply@openai\.com|^(?:claude|copilot|codex)\s*<")
3119
+
3120
+
3121
+ def strip_ai_credit(text):
3122
+ """The text without lines that credit an AI tool, and without the blank lines they leave at the end."""
3123
+ return AI_CREDIT_RE.sub("", text).rstrip() + "\n"
3124
+
3125
+
3126
+ def ai_credited_commits(base):
3127
+ """Commits on the run's branch that credit an AI tool (as author, or with a Co-Authored-By line). orch never
3128
+ makes them: a coder or the lead committed by itself."""
3129
+ mb = git("merge-base", base, "HEAD", cwd=ROOT, check=False).stdout.strip()
3130
+ if not mb:
3131
+ return []
3132
+ out = git("log", "--format=%h%x1f%an <%ae>%x1f%B%x1e", f"{mb}..HEAD", cwd=ROOT, check=False).stdout
3133
+ found = []
3134
+ for rec in out.split("\x1e"):
3135
+ parts = rec.strip("\n").split("\x1f")
3136
+ if len(parts) == 3 and (AI_AUTHOR_RE.search(parts[1]) or AI_CREDIT_RE.search(parts[2] + "\n")):
3137
+ found.append(f"{parts[0]} {parts[2].strip().splitlines()[0] if parts[2].strip() else ''}")
3138
+ return found
3139
+
3140
+
3015
3141
  def cmd_finish(args):
3016
3142
  """orch finish [--no-push] [--recheck] -> final check (reused when it already passed on exactly these files;
3017
3143
  --recheck runs it anyway), drop hidden refs and worktrees, push the feature branch, open a PR."""
@@ -3051,6 +3177,15 @@ def cmd_finish(args):
3051
3177
  if branch_exists(f"{st['branch']}-{tid}"):
3052
3178
  git("branch", "-D", "-q", f"{st['branch']}-{tid}", cwd=ROOT, check=False)
3053
3179
  print(f"CLEAN {st['branch']} is the only branch this run made ({len(refs)} hidden ref(s) removed)")
3180
+ credited = ai_credited_commits(base)
3181
+ if credited:
3182
+ print(f"WARN {len(credited)} commit(s) on {st['branch']} credit an AI tool (a Claude author or a "
3183
+ f"Co-Authored-By line). orch did not make them: an agent committed by itself. They go into the PR as "
3184
+ f"they are; to drop the credit, reword them before you push: " + "; ".join(credited[:5]))
3185
+ summary = ORCH / "summary.md"
3186
+ pr_body = ORCH / "pr-body.md" # the PR text: the summary, without any AI tool's credit line
3187
+ pr_body.write_text(strip_ai_credit(summary.read_text()) if summary.exists() else
3188
+ f"Built by herdr-orchestra from .orchestrate/plan.md ({len(st['order'])} milestones).\n")
3054
3189
  for ref in rescued:
3055
3190
  print(f"KEPT {ref}: unsaved files orch rescued during the run and no milestone used — look with "
3056
3191
  f"`git show --stat {ref}`, delete with `git update-ref -d {ref}`")
@@ -3066,11 +3201,9 @@ def cmd_finish(args):
3066
3201
  print(f"PUSHED {st['branch']} to origin")
3067
3202
  compare = github_compare_url(url, base, st["branch"])
3068
3203
  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
3204
  try:
3073
- r = subprocess.run(["gh", "pr", "create", "--base", base, "--head", st["branch"], "--title", title, *body],
3205
+ r = subprocess.run(["gh", "pr", "create", "--base", base, "--head", st["branch"], "--title", title,
3206
+ "--body-file", str(pr_body)],
3074
3207
  cwd=ROOT, text=True, capture_output=True, timeout=120)
3075
3208
  except (OSError, subprocess.TimeoutExpired) as e:
3076
3209
  r = subprocess.CompletedProcess([], 1, "", str(e))
@@ -3078,7 +3211,9 @@ def cmd_finish(args):
3078
3211
  print(f"PR {r.stdout.strip().splitlines()[-1] if r.stdout.strip() else 'created'}")
3079
3212
  return
3080
3213
  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 ""))
3214
+ print(f"OPEN A PR from {st['branch']} into {base}" + (f": {compare}" if compare else "")
3215
+ + f" — title: {title!r}, text: .orchestrate/pr-body.md (use them as they are: add no \"Generated with\" or "
3216
+ f"Co-Authored-By line)")
3082
3217
 
3083
3218
 
3084
3219
  # ---------------------------------------------------------------- v4: task files, nudge, autopilot
@@ -3122,7 +3257,7 @@ WORKER_RULES = """## Rules for you (the coder)
3122
3257
 
3123
3258
  # plan.md lines that are for the lead and orch, not the coder: they stay in plan.md and task.json
3124
3259
  LEAD_ONLY_FIELDS = {"depends on", "why separate", "prefer", "tier", "needs", "model why", "estimate", "role",
3125
- "review", "parallel"}
3260
+ "review", "parallel", "plain"}
3126
3261
 
3127
3262
 
3128
3263
  def coder_section(text, drop_criteria):
@@ -3269,6 +3404,7 @@ def cmd_dispatch(args):
3269
3404
  need(args, 1, "dispatch <Mn> [Mn...] [--to <worker>] [--tier small|medium|high]")
3270
3405
  with state_lock():
3271
3406
  st = load()
3407
+ require_lead(st, "orch dispatch")
3272
3408
  if opts.get("--to") and opts["--to"] not in st["workers"]:
3273
3409
  die(f"unknown worker {opts['--to']!r} — workers: {', '.join(st['workers'])}")
3274
3410
  if opts.get("--to"):
@@ -3292,7 +3428,11 @@ def cmd_dispatch(args):
3292
3428
  t = st["tasks"][tid]
3293
3429
  t["go"] = True
3294
3430
  t["go_ts"] = now()
3295
- t.pop("ready_ts", None)
3431
+ rt = t.pop("ready_ts", None)
3432
+ if rt and t["status"] == "pending": # it was ready and waited for this dispatch
3433
+ ws = t.setdefault("waits", {})
3434
+ ws["lead"] = ws.get("lead", 0) + max(0, now() - rt)
3435
+ t["lead_wait_s"] = max(0, now() - rt)
3296
3436
  if opts.get("--to"):
3297
3437
  t["assign"] = opts["--to"]
3298
3438
  if opts.get("--tier"):
@@ -3305,6 +3445,9 @@ def cmd_dispatch(args):
3305
3445
  print(f"DISPATCH {tid} -> {' or '.join(who) or 'nobody (every coder is off)'}"
3306
3446
  + (f" (tier {TIERS[need_rank(t) - 1]})" if need_rank(t) else "")
3307
3447
  + (f" — starts when {', '.join(waits)} merged" if waits else ""))
3448
+ story_note(st, f"{tid} ({t['title']}) was sent to start" + (f" on {opts['--to']}" if opts.get("--to") else "")
3449
+ + (f", on a {opts['--tier']} model" if opts.get("--tier") else "")
3450
+ + (f"; it starts when {', '.join(waits)} has landed" if waits else ""))
3308
3451
  if who and not opts.get("--to"):
3309
3452
  missing = [n for n in who if presence_word(st, n) not in ("ok", "detect:off")]
3310
3453
  if len(missing) == len(who):
@@ -3406,6 +3549,7 @@ def cmd_defer(args):
3406
3549
  ids = parse_defer_ids(tid, raw)
3407
3550
  record_deferral(t, tid, ids, reason)
3408
3551
  add_plan_note(tid, defer_note(t, ids, reason))
3552
+ story_note(st, f"{tid} ({t['title']}): {', '.join(ids)} left undone, as you approved ({reason[:200]})")
3409
3553
  save(st)
3410
3554
  print(f"DEFERRED {tid} {','.join(ids)}: no fix rounds for them; the summary lists them as not done "
3411
3555
  f"(follow-up). Why: {reason}")
@@ -3443,7 +3587,9 @@ def cmd_answer(args):
3443
3587
  if last in st["workers"]:
3444
3588
  t["assign"] = last
3445
3589
  t.setdefault("answers", []).append({"ts": now(), "text": text, **({"deferred": ids} if ids else {})})
3446
- _park(st, tid, "pending", f"answered: {text[:200]}")
3590
+ story_note(st, f"{tid} ({t['title']}) got the answer \"{text[:200]}\" and goes back to "
3591
+ f"{last or 'the next free coder'}" + (f"; {', '.join(ids)} left undone, as you approved" if ids else ""))
3592
+ _park(st, tid, "pending", f"answered: {text[:200]}") # saves the state
3447
3593
  print(f"ANSWERED {tid}: written to plan.md; it goes back to {last or 'the next free coder'} with its work so far")
3448
3594
  if ids:
3449
3595
  print(f"DEFERRED {tid} {','.join(ids)}: no fix rounds for them; the summary lists them as not done (follow-up)")
@@ -3508,6 +3654,7 @@ def cmd_fix(args):
3508
3654
  }
3509
3655
  if who:
3510
3656
  st["tasks"][new]["assign"] = who
3657
+ story_note(st, f"{new} added: a follow-up to {tid} (\"{text[:200]}\"), sent to {who or 'the next free coder'}")
3511
3658
  save(st)
3512
3659
  print(f"FIX {new} \"{title}\" -> {who or 'the next free coder (nobody on the team built ' + tid + ')'}; "
3513
3660
  f"added to plan.md, the check" + (" and the review" if st["tasks"][new]["review"] else "") + " still run")
@@ -3528,7 +3675,7 @@ EVENT_HELP = {
3528
3675
  "merged": "landed on the feature branch. Nothing to do unless it unlocked work listed under READY.",
3529
3676
  "ready": "milestones are ready for you: `orch dispatch <Mn>...`.",
3530
3677
  "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.",
3678
+ "auto-dispatched": "already started by the event manager (the reason is on the line above). Nothing to do.",
3532
3679
  "reviewer-lost": "the reviewer can't be reached, so the milestone waits for review (its work is kept). Tell the "
3533
3680
  "developer the fix in the event text (usually: rename the reviewer's new pane). Review resumes "
3534
3681
  "by itself once herdr finds the reviewer again.",
@@ -3544,6 +3691,152 @@ EVENT_HELP = {
3544
3691
  }
3545
3692
 
3546
3693
 
3694
+ def say_line(st, e):
3695
+ """The event in plain words, for the developer: the lead says it in its chat, and `orch story` keeps it."""
3696
+ tid, text = e.get("task"), (e.get("text") or "").strip()
3697
+ t = st["tasks"].get(tid or "", {})
3698
+ name = f"{tid} ({t.get('title', '')})" if tid else ""
3699
+ k = e["kind"]
3700
+ if k == "merged":
3701
+ how = "its check passed" + (" and the reviewer approved it" if t.get("review") else "")
3702
+ return f"{name} is done: {how}, and it is on {st['branch']}."
3703
+ if k == "ready":
3704
+ ids = re.findall(r"M\d+", text)
3705
+ return ("Ready to start: " + ", ".join(f"{i} ({st['tasks'][i]['title']})" if i in st["tasks"] else i
3706
+ for i in ids) + ".")
3707
+ if k == "auto-dispatched":
3708
+ m = re.search(r"as soon as (.+?) landed", text)
3709
+ return (f"{name} has started by itself, because {m.group(1)} landed." if m else
3710
+ f"{name} has started by itself: {text}.")
3711
+ if k == "paused":
3712
+ if "?" in text and not text.startswith(("orch error", "result file", "review output")):
3713
+ return f"{name} is paused: the coder asks: {text}"
3714
+ return f"{name} is paused: {text}."
3715
+ if k == "failed":
3716
+ return f"{name} failed: {text}."
3717
+ if k == "held":
3718
+ return f"{name} is finished but waits for your OK, because it has a risky change: {text}."
3719
+ if k == "needs-answer":
3720
+ return f"{name} can't start yet: the plan has open questions only you can answer."
3721
+ if k == "escalated":
3722
+ return f"{name} moved to a stronger model: {text}."
3723
+ if k == "reviewer-lost":
3724
+ return f"The reviewer can't be reached, so {name} waits for its review: {text}"
3725
+ if k == "worker-lost":
3726
+ return f"A coder disappeared while working on {name}: {text}"
3727
+ if k == "herdr-restart":
3728
+ return f"Most agents disappeared at once (herdr was probably restarted): {text}"
3729
+ if k == "all_done":
3730
+ return f"Every milestone is done: {text}."
3731
+ if k == "stopped":
3732
+ return f"The event manager stopped: {text}."
3733
+ return f"{k} {name}: {text}".strip()
3734
+
3735
+
3736
+ def story_lines(st):
3737
+ """The run diary: every event in plain words, and what the lead did, in time order."""
3738
+ items = [(e["ts"], "event", say_line(st, e)) for e in st.get("lead_events", [])]
3739
+ items += [(n["ts"], n.get("who", "lead"), n["text"]) for n in st.get("story", [])]
3740
+ return [f"{time.strftime('%H:%M', time.localtime(ts))} {'what happened' if who == 'event' else 'the ' + who + ' did'}: {txt}"
3741
+ for ts, who, txt in sorted(items, key=lambda x: x[0])]
3742
+
3743
+
3744
+ def write_story(st):
3745
+ lines = story_lines(st)
3746
+ with contextlib.suppress(OSError):
3747
+ (ORCH / "story.md").write_text(f"# Run diary: {st.get('title') or st['branch']} ({st['branch']})\n\n"
3748
+ "What happened, in plain words, and what the lead did about it. "
3749
+ "`orch story` prints it; the detail is in autopilot.log.\n\n"
3750
+ + "".join(f"- {l}\n" for l in lines))
3751
+ return lines
3752
+
3753
+
3754
+ def cmd_story(args):
3755
+ """orch story -> the run diary in plain words (also saved as .orchestrate/story.md)."""
3756
+ st = load()
3757
+ lines = write_story(st)
3758
+ print(f"RUN DIARY: {st.get('title') or st['branch']} ({st['branch']})")
3759
+ print("\n".join(lines) if lines else "Nothing yet: the diary fills as the run goes (events go to the lead only "
3760
+ "with a `Lead:` line in the plan).")
3761
+
3762
+
3763
+ def _short_dur(s):
3764
+ s = int(s or 0)
3765
+ 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"
3766
+
3767
+
3768
+ def plan_steps(st, tids):
3769
+ """The plan's shape for a person: which milestones start together, step by step (a milestone starts once
3770
+ everything it depends on has landed). Milestones that already landed count as done."""
3771
+ level = {}
3772
+
3773
+ def lv(tid, seen=()):
3774
+ if tid not in level:
3775
+ deps = [d for d in st["tasks"][tid]["deps"] if d in tids and d not in seen]
3776
+ level[tid] = 1 + max((lv(d, seen + (tid,)) for d in deps), default=0)
3777
+ return level[tid]
3778
+ for tid in tids:
3779
+ lv(tid)
3780
+ return [[t for t in tids if level[t] == n] for n in range(1, max(level.values(), default=0) + 1)]
3781
+
3782
+
3783
+ def cmd_plan(args):
3784
+ """orch plan show -> the plan for a person: one short card per milestone in plain words (from each milestone's
3785
+ `Plain:` line), what it waits for and why, who builds it on which model, how long it should take, and which
3786
+ milestones run together. plan.md keeps every detail; this is the part a developer reads."""
3787
+ if args[:1] != ["show"]:
3788
+ die("usage: orch plan show")
3789
+ st = load()
3790
+ tids = [t for t in st["order"] if st["tasks"][t]["status"] != "skipped"]
3791
+ print(f"PLAN in plain words: {st.get('title') or st['branch']} — {len(tids)} milestone(s) on {st['branch']}"
3792
+ + (f", about {_short_dur(st['estimate_s'])} in all" if st.get("estimate_s") else ""))
3793
+ missing = []
3794
+ for tid in tids:
3795
+ t = st["tasks"][tid]
3796
+ plain = (t.get("plain") or "").strip()
3797
+ if not plain:
3798
+ missing.append(tid)
3799
+ print(f"\n{tid} {t['title']}" + (f" — {plain}" if plain else ""))
3800
+ if t.get("why_sep") and len(tids) > 1:
3801
+ print(f" Why its own step: {t['why_sep']}")
3802
+ deps = [d for d in t["deps"]]
3803
+ if deps:
3804
+ why = re.sub(r"^(M\d+[\s,]*)+", "", t.get("deps_text") or "").strip(" ()") if len(deps) == 1 else ""
3805
+ m = re.findall(r"M\d+\s*\(([^)]*)\)", t.get("deps_text") or "")
3806
+ why = "; ".join(m) or why
3807
+ print(f" Waits for: {', '.join(deps)}" + (f" ({why})" if why else ""))
3808
+ else:
3809
+ print(" Waits for: nothing, it can start first")
3810
+ who = []
3811
+ for n in eligible_workers(st, t):
3812
+ w = st["workers"][n]
3813
+ who.append(f"{n} ({w['model']})" if w.get("model") else n)
3814
+ bits = [f"Built by: {' or '.join(who) if who else 'the next free coder'}"]
3815
+ if t.get("tier"):
3816
+ bits.append(f"{t['tier']} model")
3817
+ if t.get("estimate_s"):
3818
+ bits.append(f"about {_short_dur(t['estimate_s'])}")
3819
+ bits.append(f"reviewed by {st['reviewer']}" if t.get("review") and st.get("reviewer") else "no review")
3820
+ print(" " + " · ".join(bits))
3821
+ if t["status"] != "pending":
3822
+ now_ = {"merged": "done, on the branch", "coding": "being built", "verifying": "being checked",
3823
+ "awaiting-review": "waiting for the reviewer", "reviewing": "being reviewed",
3824
+ "reviewed": "reviewed, landing next", "committed": "landing", "needs-fix": "being fixed",
3825
+ "paused": "paused", "failed": "failed", "held": "waiting for your OK",
3826
+ "needs-answer": "waiting for your answer"}.get(t["status"], t["status"])
3827
+ print(f" Now: {now_}" + (f" ({t['reason']})" if t.get("reason") and t["status"] != "merged" else ""))
3828
+ steps = plan_steps(st, tids)
3829
+ if len(tids) > 1:
3830
+ print("\nOrder:")
3831
+ for i, g in enumerate(steps, 1):
3832
+ print(f" {i}. {' and '.join(g)}" + (" at the same time" if len(g) > 1 else "")
3833
+ + ("" if i == 1 else f" (after {' and '.join(steps[i - 2])})"))
3834
+ if missing:
3835
+ print(f"\nWARN no `Plain:` line for {', '.join(missing)}: add one sentence in plain words to each "
3836
+ f"(what the developer will get, no code words), then `orch sync`.")
3837
+ print("\nEvery detail (files, criteria, models, notes) stays in .orchestrate/plan.md.")
3838
+
3839
+
3547
3840
  def cmd_events(args):
3548
3841
  """orch events [--peek] -> what the lead was woken for. Reading the events acknowledges them (not with --peek)."""
3549
3842
  peek = "--peek" in args
@@ -3560,6 +3853,7 @@ def cmd_events(args):
3560
3853
  head = f"#{e['id']} {e['kind'].upper()}" + (f" {e['task']} \"{tt.get('title', '')}\"" if e.get("task") else "")
3561
3854
  print(head + (f": {e['text']}" if e.get("text") else ""))
3562
3855
  print(" -> " + EVENT_HELP.get(e["kind"], "").format(t=e.get("task") or "<Mn>"))
3856
+ print(" SAY: " + say_line(st, e))
3563
3857
  print(f"EVENTS for the lead — run {st['branch']}: {len(new)} new, {len(old)} still open")
3564
3858
  for e in new:
3565
3859
  show(e)
@@ -3596,12 +3890,16 @@ def cmd_events(args):
3596
3890
  print("\n" + run_playbook_part(text, "ALL_DONE"), end="")
3597
3891
  print("Handle each event above, then STOP: you are woken again when something else happens. Never prompt a "
3598
3892
  "coder yourself and never poll.")
3893
+ if new or old:
3894
+ print("BEFORE YOU STOP, tell the developer in your chat, one short line per event: its SAY line, then what "
3895
+ "you did about it (or \"nothing for me to do\"). Never end a wake-up without saying it.")
3599
3896
  if not peek and new:
3600
3897
  for e in new:
3601
3898
  e["read"] = now()
3602
3899
  if st.get("lead_wake"):
3603
3900
  st["lead_wake"]["read_ts"] = now() # for the event manager's timing line
3604
3901
  save(st)
3902
+ write_story(st)
3605
3903
 
3606
3904
 
3607
3905
  def cmd_escalate(args):
@@ -3781,8 +4079,15 @@ def cmd_autopilot(args):
3781
4079
  sys.exit(0)
3782
4080
  except SystemExit as e:
3783
4081
  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")
4082
+ unwoken = ""
4083
+ with contextlib.suppress(BaseException):
4084
+ unwoken = lead_unwoken(load()) if STATE.exists() else ""
4085
+ ended("exit", f"exit {code}" + (f"; {unwoken}" if unwoken else ""))
4086
+ log_line(f"{tag} STOPPED: " + ("the event manager finished the run (exit 0)" if code == 0 else
4087
+ f"the event manager exited (code {code}); the line above says why")
4088
+ + (f" — but {unwoken}" if unwoken else ""))
4089
+ if unwoken and shutil.which("notify-send"):
4090
+ subprocess.run(["notify-send", "orch autopilot", f"{tag} {unwoken}"], capture_output=True)
3786
4091
  raise
3787
4092
  except KeyboardInterrupt:
3788
4093
  ended("stopped", "Ctrl-C")
@@ -3801,6 +4106,24 @@ def cmd_autopilot(args):
3801
4106
  raise
3802
4107
 
3803
4108
 
4109
+ def lead_unwoken(st):
4110
+ """The event manager is leaving: if the lead still has unread events, one line that says so and why (it was never
4111
+ woken because herdr can't find it, or it did not read the wake-ups), with what to do. "" when all is read."""
4112
+ if not lead_on(st):
4113
+ return ""
4114
+ un = unread_events(st)
4115
+ if not un:
4116
+ return ""
4117
+ name, lw = st["lead"]["name"], st.get("lead_wake") or {}
4118
+ gone = lead_missing(st) if lw.get("gone") or not lw.get("n") else None
4119
+ what = ", ".join(dict.fromkeys(e["kind"].upper() + (f" {e['task']}" if e.get("task") else "") for e in un[:6]))
4120
+ if gone or lw.get("gone"):
4121
+ return (f"the lead `{name}` was never woken ({gone or 'herdr could not find it'}): {len(un)} event(s) wait "
4122
+ f"for it ({what}). Name the lead's pane (herdr agent rename <its pane id> {name}), then `orch resume` "
4123
+ f"wakes it; `orch events --peek` shows them")
4124
+ return (f"the lead `{name}` has not read {len(un)} event(s) ({what}) — tell it: run `orch events`")
4125
+
4126
+
3804
4127
  def manager_begin():
3805
4128
  """The event manager starting: report a predecessor that died without a word, then record this one (pid, host,
3806
4129
  this run's processes) so the next one can do the same for it. Safe to call twice."""
@@ -3930,7 +4253,9 @@ def _autopilot(args):
3930
4253
  deliver(s_, lead, text)
3931
4254
  except DeliveryError as e:
3932
4255
  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}))
4256
+ gone = bool(lw.get("gone")) or "not_found" in str(e) or "not found" in str(e) # herdr has no such agent
4257
+ patch_state(lambda s2: s2.update(lead_wake={"upto": newest, "ts": now(), "n": n, "wait": SEND_RETRY_S,
4258
+ **({"gone": True} if gone else {})}))
3934
4259
  return
3935
4260
  wait = min(LEAD_REWAKE_S, LEAD_CONFIRM_S * 2 ** n) if watch else LEAD_REWAKE_S
3936
4261
  oldest = min(e["ts"] for e in un)
@@ -3952,21 +4277,31 @@ def _autopilot(args):
3952
4277
  hold = undispatched(s_)
3953
4278
  if not hold:
3954
4279
  return
3955
- late = [k for k in hold if now() - s_["tasks"][k].get("ready_ts", now()) > LEAD_WAIT_S]
4280
+ # `Auto dispatch: on` (the default): a milestone that a landing unlocked starts at once; the lead hears of
4281
+ # it (AUTO-DISPATCHED) instead of being asked. The plan already says what it is and who may take it.
4282
+ auto = [k for k in hold if s_.get("auto_dispatch", True) and s_["tasks"][k]["deps"]
4283
+ and s_["run"].get("started")]
4284
+ late = [k for k in hold if k not in auto and now() - s_["tasks"][k].get("ready_ts", now()) > LEAD_WAIT_S]
3956
4285
 
3957
4286
  def upd(s2):
3958
4287
  for k in hold:
3959
4288
  s2["tasks"][k].setdefault("ready_ts", now())
4289
+ for k in auto:
4290
+ s2["tasks"][k]["go"] = True
4291
+ lead_event(s2, "auto-dispatched", k, f"started by the event manager as soon as "
4292
+ f"{', '.join(s2['tasks'][k]['deps'])} landed (`Auto dispatch: on` in plan.md)")
3960
4293
  for k in late:
3961
4294
  s2["tasks"][k]["go"] = True
3962
4295
  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]
4296
+ rest = [k for k in hold if k not in late and k not in auto]
3964
4297
  if rest and rest != s2.get("lead_ready_told"): # once per set, not once per loop
3965
4298
  lead_event(s2, "ready", None, ", ".join(rest))
3966
4299
  s2["lead_ready_told"] = rest
3967
4300
  patch_state(upd)
3968
4301
  for k in late:
3969
4302
  say(f"{k}: the lead did not dispatch it within {LEAD_WAIT_S // 60} min -> started without it", True)
4303
+ for k in auto:
4304
+ say(f"{k}: {', '.join(s_['tasks'][k]['deps'])} landed, so it starts now (auto dispatch); the lead is told")
3970
4305
 
3971
4306
  def guarded(tid, fn):
3972
4307
  """One task's orch error never stops the run: that task is paused with the error, the rest carry on."""
@@ -4011,45 +4346,299 @@ def _autopilot(args):
4011
4346
  say(f"{tid} is HELD for your approval: {out.splitlines()[0].split('—', 1)[-1].strip()}. "
4012
4347
  f"Look at it, then run `orch approve {tid}`; autopilot keeps going with the rest", True)
4013
4348
 
4349
+ # ---- background jobs: a check or a merge runs beside the event loop, and its end is one more event (like a
4350
+ # browser's fetch: the work happens elsewhere, the callback is queued). Nothing waits for a check to finish.
4351
+ bg = {}
4352
+
4353
+ def check_slots():
4354
+ return max(1, load().get("parallel_checks", 1)) - sum(1 for j in bg.values() if j["uses_check"])
4355
+
4356
+ def checking(tid):
4357
+ return any(j["tid"] == tid and j["kind"] == "check" for j in bg.values())
4358
+
4359
+ def bg_start(name, tid, kind, shell_cmd, cwd, uses_check, on_done, timeout=None):
4360
+ log, ex = BG_DIR / f"{name}.log", BG_DIR / f"{name}.exit"
4361
+ ex.unlink(missing_ok=True)
4362
+ q = shlex.quote
4363
+ wrapped = (f"( {shell_cmd}\n) > {q(str(log))} 2>&1; echo $? > {q(str(ex))}.tmp; "
4364
+ f"mv {q(str(ex))}.tmp {q(str(ex))}")
4365
+ p = subprocess.Popen(["/bin/sh", "-c", wrapped], cwd=cwd, stdin=subprocess.DEVNULL,
4366
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
4367
+ bg[name] = {"p": p, "tid": tid, "kind": kind, "t0": time.time(), "log": log, "exit": ex,
4368
+ "uses_check": uses_check, "on_done": on_done, "timeout": timeout}
4369
+
4370
+ def bg_reap():
4371
+ """Collect the background jobs that ended and run what each one's end means."""
4372
+ for name, j in list(bg.items()):
4373
+ secs = round(time.time() - j["t0"], 1)
4374
+ timed_out = False
4375
+ if j["p"].poll() is None and j["exit"].exists():
4376
+ with contextlib.suppress(subprocess.TimeoutExpired):
4377
+ j["p"].wait(timeout=5) # it wrote its exit code: it is leaving
4378
+ if j["p"].poll() is None:
4379
+ if not (j["timeout"] and secs > j["timeout"]):
4380
+ continue
4381
+ timed_out = True
4382
+ with contextlib.suppress(OSError):
4383
+ os.killpg(j["p"].pid, signal.SIGTERM)
4384
+ with contextlib.suppress(subprocess.TimeoutExpired):
4385
+ j["p"].wait(timeout=30)
4386
+ try:
4387
+ code = int(j["exit"].read_text().strip())
4388
+ except (OSError, ValueError):
4389
+ code = 124 if timed_out else (j["p"].returncode or 1)
4390
+ try:
4391
+ out = j["log"].read_text(errors="replace")
4392
+ except OSError:
4393
+ out = ""
4394
+ if timed_out:
4395
+ code, out = 124, out + f"\ncheck command timed out after {j['timeout'] // 60} min"
4396
+ del bg[name]
4397
+ for f in (j["log"], j["exit"]):
4398
+ f.unlink(missing_ok=True)
4399
+ guarded(j["tid"], lambda: j["on_done"](code, out, secs))
4400
+
4401
+ def bg_stop():
4402
+ """The event manager is leaving: stop the checks it started (a merge is left to finish: it is journaled)."""
4403
+ for j in bg.values():
4404
+ if j["kind"] == "check" and j["p"].poll() is None:
4405
+ with contextlib.suppress(OSError):
4406
+ os.killpg(j["p"].pid, signal.SIGTERM)
4407
+
4408
+ # ---- waits: time a finished or ready milestone sat still because something else had to happen first
4409
+ def start_wait(tid, what, behind):
4410
+ s_ = load()
4411
+ if (s_["tasks"][tid].get("waiting") or {}).get("what") == what:
4412
+ return
4413
+ patch_state(lambda s2: s2["tasks"][tid].update(waiting={"what": what, "since": now(), "behind": behind}))
4414
+
4415
+ def end_wait(tid, what):
4416
+ """Close Mn's wait for `what`: add it to the milestone's waits (summary) and log it. Returns the seconds."""
4417
+ w = load()["tasks"][tid].get("waiting") or {}
4418
+ if w.get("what") != what:
4419
+ return 0
4420
+ secs = max(0, now() - w["since"])
4421
+
4422
+ def upd(s2):
4423
+ t2 = s2["tasks"][tid]
4424
+ t2.pop("waiting", None)
4425
+ ws = t2.setdefault("waits", {})
4426
+ ws[what] = ws.get(what, 0) + secs
4427
+ patch_state(upd)
4428
+ if secs and what != "reviewer": # the reviewer wait is said with the review it waited for
4429
+ say(f"{tid} waited {_fmt_secs(secs)} for {w.get('behind') or what}")
4430
+ return secs
4431
+
4432
+ def start_check(tid, d):
4433
+ """Start Mn's check in its folder, in the background. False when every check slot is busy (it waits)."""
4434
+ s_ = load()
4435
+ t_ = s_["tasks"][tid]
4436
+ k = t_["attempt"]
4437
+ if not s_.get("check"):
4438
+ check_done(tid, k, d, None, 0, "", 0)
4439
+ return True
4440
+ if check_slots() <= 0:
4441
+ busy = [j["tid"] for j in bg.values() if j["uses_check"]]
4442
+ start_wait(tid, "check slot", f"{', '.join(busy)}'s check" if busy else "a free check slot")
4443
+ return False
4444
+ end_wait(tid, "check slot")
4445
+ tree0 = tree_of(d)
4446
+ patch_state(lambda s2: s2["tasks"][tid].update(checking={"since": now(), "where": "worktree"}))
4447
+ bg_start(f"check-{tid}-{k}", tid, "check", s_["check"], d, True,
4448
+ lambda code, out, secs: check_done(tid, k, d, tree0, code, out, secs), CHECK_TIMEOUT_S)
4449
+ return True
4450
+
4451
+ def check_done(tid, k, d, tree0, code, out, secs):
4452
+ ok = code == 0
4453
+ tail = "\n".join(out.splitlines()[-60:])
4454
+ tree = tree_of(d) if ok and tree0 else None
4455
+
4456
+ def upd(s2):
4457
+ t2 = s2["tasks"][tid]
4458
+ t2.pop("checking", None)
4459
+ if s2.get("check"):
4460
+ t2.setdefault("checks", []).append({"where": "worktree", "ok": ok, "secs": secs, "ts": now()})
4461
+ # the tree is kept only when the check left the files as it found them: then a branch that gets exactly
4462
+ # these files needs no second check (merge_check_needed)
4463
+ t2["chk"] = {"attempt": k, "ok": ok, "tail": tail, "tree": tree if tree and tree == tree0 else None,
4464
+ "used": False}
4465
+ note_green(s2, d, ok)
4466
+ patch_state(upd)
4467
+ if s_check := load().get("check"):
4468
+ say(f"{tid} check {'passed' if ok else 'FAILED'} in {_fmt_secs(secs)} ({s_check})")
4469
+
4470
+ def early_review_ok(tid, t):
4471
+ s_ = load()
4472
+ return (s_.get("early_review", True) and bool(s_.get("check")) and bool(s_.get("reviewer"))
4473
+ and t["review"] and not t.get("review_ok") and not t.get("pre_conflict") and holds(s_, tid))
4474
+
4475
+ def check_fix(tid, tail, blockers=()):
4476
+ """The check failed: one fix round for the coder that holds Mn, with the reviewer's blockers if there are."""
4477
+ code, _ = run("bump", tid, "fix", ok=(0, 3))
4478
+ if code == 3:
4479
+ fail(tid, f"checks still failing after {MAX_FIX} fix rounds")
4480
+ return
4481
+ n = load()["tasks"][tid]["fix"]
4482
+ say(f"{tid} checks failed -> fix round {n}" + (f" (with the reviewer's {len(blockers)} blocker(s))"
4483
+ if blockers else ""))
4484
+ write_and_send(tid, f"fix-{n}.md",
4485
+ f"# Checks failing for {tid} (round {n})\n\nThe check command `{st['check']}` "
4486
+ f"failed. Diagnose the cause and fix it; you decide how. Don't change unrelated "
4487
+ f"code, and don't weaken or skip tests to make them pass.\n\n"
4488
+ f"```\n{tail}\n```\n"
4489
+ + ("\nThe reviewer also found these problems in the same version (it reviewed it while the "
4490
+ "check ran). Investigate each one too; if you think one is wrong, say why in your report:\n"
4491
+ + "\n".join(blockers) + "\n" if blockers else ""))
4492
+
4493
+ def early_followup(tid, t):
4494
+ """Mn's review was sent alongside its check (`Early review: on`). Match the two up. True when handle()
4495
+ has nothing more to do for Mn now."""
4496
+ if t.get("early") != t.get("attempt"):
4497
+ return False
4498
+ if checking(tid):
4499
+ return t["status"] == "reviewed" # the review is back first: it waits for the check
4500
+ chk = t.get("chk") if (t.get("chk") or {}).get("attempt") == t["attempt"] else None
4501
+ if chk is None: # the event manager restarted while the check ran: run it again
4502
+ start_check(tid, t["dir"])
4503
+ return t["status"] == "reviewed"
4504
+ if chk["ok"]:
4505
+ if not chk.get("used"):
4506
+ patch_state(lambda s_: s_["tasks"][tid]["chk"].update(used=True))
4507
+ if holds(load(), tid):
4508
+ _, hout = run("handoff", tid)
4509
+ if hout.startswith("HANDED_OFF"):
4510
+ say(f"{tid} passed its check while being reviewed; {t['worker']} is free for other work")
4511
+ return False
4512
+ if t["status"] == "reviewing":
4513
+ return True # check failed: wait for the review, then one fix round for both
4514
+ blockers = []
4515
+ if t["status"] == "reviewed":
4516
+ blockers, _, _ = review_findings(tid, t["review_round"])
4517
+ why = "the check failed" + (" while it was being reviewed" if t["status"] == "reviewed" else "")
4518
+
4519
+ def upd(s_):
4520
+ t2 = s_["tasks"][tid]
4521
+ t2["chk"]["used"] = True
4522
+ t2["early"] = None
4523
+ t2["review_ok"] = False
4524
+ if t["status"] == "reviewed": # that review round looked at a version that fails its check:
4525
+ t2["review_base"] = t2.get("review_base", 0) + 1 # it does not count against the review cap
4526
+ move(s_, tid, "needs-fix", why)
4527
+ patch_state(upd)
4528
+ check_fix(tid, chk["tail"], blockers)
4529
+ return True
4530
+
4014
4531
  def land(tid):
4532
+ """Land a milestone: commit it, then merge it onto the feature branch in the background (the merge runs the
4533
+ check there unless the files are the ones already checked). One merge at a time: they all go through the
4534
+ main folder. Waits are counted (see add_wait)."""
4015
4535
  st_ = load()
4016
- code, out = run("commit", tid, ok=(0, 7))
4017
- if code == 7:
4018
- held(tid, out)
4019
- return False
4536
+ t_ = st_["tasks"][tid]
4020
4537
  if st_["isolation"] == "shared":
4538
+ if any(j["kind"] == "check" for j in bg.values()):
4539
+ return False # a commit in the shared folder waits for a check running in it
4540
+ code, out = run("commit", tid, ok=(0, 7))
4541
+ if code == 7:
4542
+ held(tid, out)
4543
+ return False
4021
4544
  say(f"{tid} landed on {st_['branch']}")
4022
4545
  return True
4023
- code, out = run("merge", tid, ok=(0, 3, 4, 6, 7))
4546
+ if any(j["kind"] == "merge" and j["tid"] == tid for j in bg.values()):
4547
+ return None # its merge is running
4548
+ if t_["status"] != "committed":
4549
+ code, out = run("commit", tid, ok=(0, 7))
4550
+ if code == 7:
4551
+ held(tid, out)
4552
+ return False
4553
+ st_ = load()
4554
+ uses = merge_check_needed(st_, tid)
4555
+ other = next((j["tid"] for j in bg.values() if j["kind"] == "merge"), None)
4556
+ if other or (uses and check_slots() <= 0):
4557
+ start_wait(tid, "merge", f"the merge of {other}" if other else "a free check slot")
4558
+ return None
4559
+ end_wait(tid, "merge")
4560
+ if uses:
4561
+ patch_state(lambda s_: s_["tasks"][tid].update(checking={"since": now(), "where": "branch"}))
4562
+ bg_start(f"merge-{tid}", tid, "merge", shlex.join([sys.executable, os.path.abspath(__file__), "merge", tid]),
4563
+ ROOT, uses, lambda code, out, secs: merge_done(tid, code, out))
4564
+ return None
4565
+
4566
+ def merge_done(tid, code, out):
4567
+ patch_state(lambda s_: s_["tasks"][tid].pop("checking", None))
4568
+ out = out.strip()
4569
+ for l in out.splitlines():
4570
+ if l.startswith(("SKIPPED_CHECK", "SETUP ", "WARN ")):
4571
+ say(l)
4024
4572
  if code == 7:
4025
4573
  held(tid, out)
4026
- return False
4574
+ return
4027
4575
  if code == 3:
4028
- say(f"{tid} failed: {out.splitlines()[0]}", True)
4029
- return False
4576
+ say(f"{tid} failed: {out.splitlines()[0] if out else 'merge stopped'}", True)
4577
+ return
4030
4578
  if code in (4, 6):
4031
4579
  s_ = load()
4032
4580
  if code == 4 and s_["tasks"][tid].get("conflicts", 0) > MAX_CONFLICT:
4033
4581
  park(tid, "failed", f"merge conflict still unresolved after {MAX_CONFLICT} attempts")
4034
- return False
4582
+ return
4035
4583
  what = "merge conflict" if code == 4 else f"passes alone but fails the check on {s_['branch']} (not committed)"
4036
- if holds(s_, tid):
4584
+ if not s_["tasks"][tid].get("job"): # the dispatch step sent its job already, while this was collected
4585
+ say(f"{tid} {what} -> sent to {s_['tasks'][tid].get('worker') or 'the next free coder'}")
4586
+ elif holds(s_, tid):
4037
4587
  say(f"{tid} {what} -> back to {s_['tasks'][tid]['worker']}")
4038
4588
  code, out = run("send-job", tid, ok=(0, 5))
4039
4589
  sent(code, out, tid, s_["tasks"][tid]["worker"])
4040
4590
  else:
4041
4591
  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
4592
+ return
4593
+ if code != 0:
4594
+ raise RuntimeError(f"orch merge {tid} -> exit {code}: {out}")
4595
+ say(f"{tid} checked and merged into {load()['branch']}")
4045
4596
 
4046
4597
  def handle(tid, t):
4598
+ if t["status"] in ("awaiting-review", "reviewing", "reviewed") and early_followup(tid, t):
4599
+ return
4047
4600
  if t["status"] == "verifying":
4601
+ if checking(tid):
4602
+ return # its check runs in the background: its end is an event
4603
+ k = t["attempt"]
4604
+ chk = t.get("chk") if (t.get("chk") or {}).get("attempt") == k else None
4605
+ if chk is None:
4606
+ if t.get("prechecked") != k:
4607
+ if not pre_check(tid, t):
4608
+ return
4609
+ patch_state(lambda s_: s_["tasks"][tid].update(prechecked=k))
4610
+ t = load()["tasks"][tid]
4611
+ if early_review_ok(tid, t):
4612
+ code, out = run("review", tid, ok=(0, 3, 5))
4613
+ patch_state(lambda s_: s_["tasks"][tid].update(early=k))
4614
+ say(out.splitlines()[-1] + (" (alongside its check: `Early review: on`)" if code == 0 else ""))
4615
+ start_check(tid, t["dir"])
4616
+ return
4617
+ post_check(tid, t, chk)
4618
+ elif t["status"] == "awaiting-review":
4619
+ code, out = run("review", tid, ok=(0, 3, 5))
4620
+ if code == 0:
4621
+ waited = end_wait(tid, "reviewer")
4622
+ say(out + (f" ({tid} waited {_fmt_secs(waited)} for the reviewer)" if waited else ""))
4623
+ elif code == 3:
4624
+ start_wait(tid, "reviewer", "the reviewer")
4625
+ elif code == 5:
4626
+ n = (load().get("reviewer_info") or {}).get("delivery_fails", 0)
4627
+ say(f"{tid}: could not reach the reviewer — retrying when herdr sees it again (or after "
4628
+ f"{SEND_RETRY_S if n < UNREACHABLE_AFTER else UNREACHABLE_MIN * 60}s)\n{out}",
4629
+ n in (1, UNREACHABLE_AFTER))
4630
+ else:
4631
+ handle_rest(tid, t)
4632
+
4633
+ def pre_check(tid, t):
4634
+ """What a finished coder's work must pass before its check runs: a usable result file, no open question,
4635
+ its scope, its acceptance criteria. False when it went back to the coder or was parked."""
4636
+ if True:
4048
4637
  res, err = read_result(t.get("last_result"))
4049
4638
  if err and err != "missing":
4050
4639
  if t.get("result_fixes", 0) >= 1:
4051
4640
  park(tid, "paused", f"result file still not usable ({err}): {t.get('last_result')}")
4052
- return
4641
+ return False
4053
4642
  patch_state(lambda s_: s_["tasks"][tid].update(result_fixes=s_["tasks"][tid].get("result_fixes", 0) + 1))
4054
4643
  say(f"{tid}: result file not usable ({err}) -> asked the coder once to rewrite it")
4055
4644
  write_and_send(tid, "result-fix-1.md",
@@ -4057,19 +4646,19 @@ def _autopilot(args):
4057
4646
  "Don't change any code for this. Write the result file the prompt names, in the "
4058
4647
  "`result_format` shape from task.json (valid JSON), plus the report, then the done "
4059
4648
  "file.\n")
4060
- return
4649
+ return False
4061
4650
  rp = t.get("last_report")
4062
4651
  rtext = Path(rp).read_text() if rp and Path(rp).exists() else ""
4063
4652
  if res:
4064
4653
  if res["status"] in ("question", "blocked"):
4065
4654
  qs = [str(q) for q in res.get("questions", []) if q] or ["the coder is " + res["status"]]
4066
4655
  park(tid, "paused", "; ".join(qs)[:400])
4067
- return
4656
+ return False
4068
4657
  else:
4069
4658
  q = [l for l in rtext.splitlines() if l.strip().upper().startswith("QUESTION:")]
4070
4659
  if q:
4071
4660
  park(tid, "paused", q[0].strip()[9:].strip() or "worker asked a question")
4072
- return
4661
+ return False
4073
4662
  # scope: the real diff against the milestone's Likely files
4074
4663
  s_ = load()
4075
4664
  allowed = s_["tasks"][tid].get("files") or []
@@ -4086,7 +4675,7 @@ def _autopilot(args):
4086
4675
  f"{', '.join(new)}.\nUndo those changes, or, if the task truly can't be done without them, "
4087
4676
  f"leave them and explain why in your report. Then run `{st['check']}`.\n"),
4088
4677
  f"still outside its scope after {MAX_FIX} fix rounds: {', '.join(new)}")
4089
- return
4678
+ return False
4090
4679
  if new:
4091
4680
  hot = [f for f in new if HOTSPOT_RE.search(f)]
4092
4681
  say(f"{tid} changed files outside its Likely files: {', '.join(new)}" +
@@ -4112,8 +4701,14 @@ def _autopilot(args):
4112
4701
  "exist), don't try again: set status `question`, say which criterion and why, and offer to "
4113
4702
  "build the rest and defer that one. The developer decides.\n"),
4114
4703
  f"acceptance criteria still not met after {MAX_FIX} fix rounds")
4115
- return
4116
- ok, tail = check(t["dir"], tid)
4704
+ return False
4705
+ return True
4706
+
4707
+ def post_check(tid, t, chk):
4708
+ """The check of a coder's work came back (verifying): on to review or landing, or a fix round."""
4709
+ patch_state(lambda s_: s_["tasks"][tid]["chk"].update(used=True))
4710
+ ok, tail = chk["ok"], chk["tail"]
4711
+ if True:
4117
4712
  if ok:
4118
4713
  if t["review"] and not t.get("review_ok"):
4119
4714
  _, hout = run("handoff", tid)
@@ -4124,27 +4719,10 @@ def _autopilot(args):
4124
4719
  else:
4125
4720
  land(tid)
4126
4721
  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":
4722
+ check_fix(tid, tail)
4723
+
4724
+ def handle_rest(tid, t):
4725
+ if t["status"] == "reviewed":
4148
4726
  k = t["review_round"]
4149
4727
  blockers, _, known = review_findings(tid, k)
4150
4728
  where = f".orchestrate/review/{tid}/review-{k}.json"
@@ -4186,17 +4764,21 @@ def _autopilot(args):
4186
4764
  code, out = run("send-job" if kind == "FIX" else "send", tid, *([] if kind == "FIX" else ["task.md"]),
4187
4765
  ok=(0, 5))
4188
4766
  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))
4767
+ t_ = load()["tasks"][tid]
4768
+ go_ts, lw = t_.get("go_ts"), t_.get("lead_wait_s")
4769
+ if go_ts or lw is not None:
4770
+ patch_state(lambda s_: [s_["tasks"][tid].pop(k, None) for k in ("go_ts", "lead_wait_s")])
4192
4771
  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 ""))
4772
+ + (f" ({max(0, now() - go_ts)}s after the lead's dispatch or answer)" if go_ts else "")
4773
+ + (f" — it waited {_fmt_secs(lw)} for the lead's dispatch" if lw else ""))
4194
4774
 
4195
4775
  def on_event(ev):
4196
4776
  parts = ev.split()
4197
4777
  if len(parts) < 2:
4198
4778
  return
4199
4779
  kind, tid = parts[0], parts[1]
4780
+ if kind == "BG_DONE":
4781
+ return # a background check or merge ended: the next loop collects it
4200
4782
  agent = (re.search(r"agent=(\S+)", ev) or re.search(r"worker=(\S+)", ev) or [None, None])[1]
4201
4783
  s_ = load()
4202
4784
  t = s_["tasks"].get(tid, {})
@@ -4316,6 +4898,15 @@ def _autopilot(args):
4316
4898
  + str([n + (f" ({w['model']})" if w.get("model") else "") for n, w in st["workers"].items()])
4317
4899
  + (f", budget {st['budget_s'] // 60} min" if st.get("budget_s") else "")
4318
4900
  + (f"; events go to the lead ({st['lead']['name']})" if lead_on(st) else ""))
4901
+ gone = lead_missing(st)
4902
+ if gone:
4903
+ say(f"!! LEAD NOT FOUND: the lead ({st['lead']['name']}) can't be woken ({gone}). Its events are kept and wait "
4904
+ f"for it; in the lead's pane: herdr agent rename <its pane id> {st['lead']['name']}", True)
4905
+ BG_DIR.mkdir(exist_ok=True)
4906
+ for f in BG_DIR.glob("*"): # left by a manager that stopped: its jobs are gone
4907
+ f.unlink(missing_ok=True)
4908
+ patch_state(lambda s_: [t_.pop("checking", None) for t_ in s_["tasks"].values()])
4909
+ atexit.register(bg_stop)
4319
4910
  last_tick = time.time()
4320
4911
  slept = sleep_meter()
4321
4912
  waiting_since = None # set while nothing runs and the run waits for the lead or the developer
@@ -4371,8 +4962,12 @@ def _autopilot(args):
4371
4962
  f"`Budget:` in plan.md (or remove it) and run autopilot again; work in progress is kept.", True)
4372
4963
  sys.exit(3)
4373
4964
 
4374
- # 1. act on tasks waiting for us
4375
- for tid in st["order"]:
4965
+ # 1. act on tasks waiting for us: background jobs that ended first, then reviews (so the reviewer is never
4966
+ # idle while work waits for it), then the rest in plan order
4967
+ bg_reap()
4968
+ st = load()
4969
+ first = {"reviewed": 0, "awaiting-review": 1}
4970
+ for tid in sorted(st["order"], key=lambda k: first.get(st["tasks"][k]["status"], 2)):
4376
4971
  t = st["tasks"][tid]
4377
4972
  guarded(tid, lambda: handle(tid, t))
4378
4973
 
@@ -4443,6 +5038,8 @@ def _autopilot(args):
4443
5038
  + ("## Models: planned and actual\n| Milestone | Planned tier | Ran on | Escalated | Why this tier |\n"
4444
5039
  "|---|---|---|---|---|\n" + "\n".join(models) + "\n\n" if models else "") +
4445
5040
  f"## Time: estimate vs actual\n{timing}\n\n"
5041
+ f"## Waiting: time milestones sat still\nA finished or ready milestone that waited for something else "
5042
+ f"first (counted in the times above).\n{wait_table(tasks)}\n\n"
4446
5043
  f"## Checked automatically\nAlready verified by the run; nobody needs to redo these by hand.\n"
4447
5044
  f"{auto_checked(st, ok)}\n\n"
4448
5045
  f"## Run report\n```\n{report}\n```\n\n"
@@ -4482,6 +5079,11 @@ def _autopilot(args):
4482
5079
  True)
4483
5080
  break
4484
5081
  time.sleep(POLL_STEP_S)
5082
+ s_ = load()
5083
+ if unread_events(s_) and lead_missing(s_):
5084
+ say(f"ALL_DONE, but the lead ({st['lead']['name']}) was NEVER WOKEN: herdr can't find it, so it "
5085
+ f"does not know the run finished. Name its pane (herdr agent rename <its pane id> "
5086
+ f"{st['lead']['name']}), then `orch resume`", True)
4485
5087
  sys.exit(0 if ok else 3)
4486
5088
  active = [k for k, v in tasks.items() if v["status"] in ACTIVE and v["status"] != "held"]
4487
5089
  ready = [k for k, v in tasks.items() if v["status"] == "pending" and deps_met(st, v)]
@@ -4521,6 +5123,21 @@ def _autopilot(args):
4521
5123
  guarded(evtid, lambda: on_event(ev))
4522
5124
 
4523
5125
 
5126
+ WAIT_NAMES = {"check slot": "a free check slot", "merge": "the merge step", "reviewer": "the reviewer",
5127
+ "lead": "the lead's dispatch"}
5128
+
5129
+
5130
+ def wait_table(tasks):
5131
+ rows = []
5132
+ for k, v in tasks.items():
5133
+ ws = {w: s for w, s in (v.get("waits") or {}).items() if s}
5134
+ if ws:
5135
+ rows.append(f"| {k} | " + ", ".join(f"{WAIT_NAMES.get(w, w)} {_fmt_secs(s)}" for w, s in ws.items())
5136
+ + f" | {_fmt_secs(sum(ws.values()))} |")
5137
+ return ("| Milestone | Waited for | Total |\n|---|---|---|\n" + "\n".join(rows)) if rows else \
5138
+ "No milestone waited: each one went on as soon as it could."
5139
+
5140
+
4524
5141
  def _fmt_secs(s):
4525
5142
  s = int(s or 0)
4526
5143
  return f"{s // 3600}h{s % 3600 // 60:02d}m" if s >= 3600 else f"{s // 60}m{s % 60:02d}s"
@@ -5305,11 +5922,11 @@ COMMANDS = {
5305
5922
  "send-job": cmd_send_job, "handoff": cmd_handoff, "needs-fix": cmd_needs_fix, "review-ok": cmd_review_ok,
5306
5923
  "requeue-review": cmd_requeue_review, "finish": cmd_finish, "resend": cmd_resend, "approve": cmd_approve,
5307
5924
  "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,
5925
+ "escalate": cmd_escalate, "fix": cmd_fix, "plan": cmd_plan, "story": cmd_story, "team": cmd_team, "bench": cmd_bench, "stop": cmd_stop,
5309
5926
  "doctor": lambda a: cmd_doctor_crash(a),
5310
5927
  }
5311
5928
  # 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",
5929
+ UNLOCKED = {"autopilot", "poll", "merge", "events", "dispatch", "answer", "defer", "fix", "team", "resume", "bench", "stop",
5313
5930
  "doctor"}
5314
5931
 
5315
5932
  USAGE = """usage: orch <command> [args]
@@ -5330,6 +5947,8 @@ USAGE = """usage: orch <command> [args]
5330
5947
  models show|check <id> one model's ratings and evidence / is it allowed?
5331
5948
  resume after a restart (computer off, herdr closed): name the agents' panes again, save unsaved
5332
5949
  work, re-send the tasks that were in progress and start the event manager
5950
+ story the run diary in plain words: each event and what the lead did (.orchestrate/story.md)
5951
+ plan show the plan for a person: each milestone in plain words, who builds it, how long, the order
5333
5952
  events [--peek] (lead) what you were woken for; reading acknowledges it
5334
5953
  dispatch <Mn>... [--to <worker>] [--tier <tier>] (lead) start or restart milestones; starts the event manager
5335
5954
  answer <Mn> [--defer AC2,AC3] <text> (lead) the developer's answer: into plan.md, and back to the same coder;
@@ -5412,6 +6031,84 @@ def lead_check():
5412
6031
  + hermes_fix)
5413
6032
 
5414
6033
 
6034
+ def herdr_current_pane():
6035
+ """(pane id, sure): the pane this shell runs in. sure=False when HERDR_PANE_ID is unset, so the id herdr gave is
6036
+ the FOCUSED pane, which may be another one. (None, False) outside herdr."""
6037
+ pid = os.environ.get("HERDR_PANE_ID")
6038
+ if pid:
6039
+ return pid, True
6040
+ ok, data, out = _herdr_json([HERDR, "pane", "current"])
6041
+ if not ok:
6042
+ return None, False
6043
+ pid = _find_key(data, "pane_id") if data is not None else None
6044
+ if not pid:
6045
+ pid = (re.search(r'"?pane_id"?\s*[:=]\s*"?([\w:.-]+)', out) or [None, None])[1]
6046
+ return pid, False
6047
+
6048
+
6049
+ def name_lead(name, st=None):
6050
+ """Give this pane (the lead's own: HERDR_PANE_ID) the lead's name, so the event manager can wake it. The lead
6051
+ runs `orch lead plan`, `orch lead run`, `orch start` and `orch dispatch` from its own pane, so the pane they run
6052
+ in is the lead's; nothing depends on the lead obeying a playbook line. Never takes the name from another pane
6053
+ that runs an agent, and never renames a worker's or the reviewer's pane. Returns (ok, one line to print)."""
6054
+ pid = os.environ.get("HERDR_PANE_ID")
6055
+ if not pid:
6056
+ return False, ("HERDR_PANE_ID is not set in this shell, so orch can't tell which pane is yours and did not "
6057
+ "name it")
6058
+ ok, data, _ = _herdr_json([HERDR, "agent", "get", name])
6059
+ if ok and data is not None and not _shell_only(data):
6060
+ where = _find_key(data, "pane_id")
6061
+ if where == pid:
6062
+ return True, f"LEAD this pane ({pid}) is `{name}`: the event manager can wake it"
6063
+ if where:
6064
+ return False, (f"pane {where} already has the name `{name}` and runs an agent, so this pane ({pid}) was "
6065
+ f"not named. If that pane is not the lead: herdr agent rename {where} old-{name} && "
6066
+ f"herdr agent rename {pid} {name}")
6067
+ for n in list((st or {}).get("workers", {})) + ([st["reviewer"]] if (st or {}).get("reviewer") else []):
6068
+ if agent_pane(n) == pid:
6069
+ return False, f"this pane ({pid}) is {n}, not the lead, so it was not named `{name}`"
6070
+ ok, _, out = _herdr_json([HERDR, "agent", "rename", pid, name])
6071
+ if ok:
6072
+ return True, f"NAMED this pane ({pid}) is now `{name}`, so the event manager can wake it"
6073
+ return False, f"`herdr agent rename {pid} {name}` failed: {out.splitlines()[-1] if out else 'no answer'}"
6074
+
6075
+
6076
+ def lead_missing(st):
6077
+ """Why the event manager can't wake this run's lead (herdr has no agent with its name), or None when it can, or
6078
+ when there is nothing to check (no lead, `Lead mode: off`, a lead herdr can't watch or reached by pane id)."""
6079
+ if not lead_on(st):
6080
+ return None
6081
+ lead = st["lead"]
6082
+ if lead.get("pane") or not lead.get("detect", True):
6083
+ return None
6084
+ where, _ = herdr_presence(lead["name"])
6085
+ return {"agent": None, "shell": "only a plain shell is left in its pane",
6086
+ "gone": "herdr has no agent with this name"}[where]
6087
+
6088
+
6089
+ def require_lead(st, doing):
6090
+ """`orch start` / `orch dispatch`: a run with a lead must be able to wake it. Name this pane when it is the lead's
6091
+ (see name_lead); otherwise refuse, with the exact rename command, before anything changes. The event manager's
6092
+ own `orch start` is not checked here (its pane is not the lead's); it warns in its log instead."""
6093
+ if os.environ.get("ORCH_DRIVER"):
6094
+ return
6095
+ why = lead_missing(st)
6096
+ if not why:
6097
+ return
6098
+ name = st["lead"]["name"]
6099
+ ok, line = name_lead(name, st)
6100
+ if ok and not lead_missing(st):
6101
+ print(line)
6102
+ return
6103
+ pid, sure = herdr_current_pane()
6104
+ die(f"NO LEAD: the lead `{name}` can't be woken ({why}), so nobody would hear when work finishes or a coder asks "
6105
+ f"something. {doing} was refused; nothing changed.\n"
6106
+ f" {line}.\n"
6107
+ f" If you are the lead, name your own pane, then run it again: herdr agent rename {pid or '<your pane id>'} "
6108
+ f"{name}" + ("" if sure or not pid else " (that is the FOCUSED pane: check it is yours)") + "\n"
6109
+ f" `orch lead whoami` shows your pane. To run with no lead, put `Lead mode: off` in plan.md and `orch sync`.")
6110
+
6111
+
5415
6112
  PB_MARK_RE = re.compile(r"^<!-- (/?)(full|start|quick)(?::\s*(.*?))?\s*-->$")
5416
6113
 
5417
6114
 
@@ -5472,6 +6169,30 @@ def run_playbook_part(text, name):
5472
6169
  return "\n".join(rows) + ("\n" if rows else "")
5473
6170
 
5474
6171
 
6172
+ def lead_self_name():
6173
+ """`orch lead plan` / `orch lead run` (not a wake-up's --section): name the pane they run in as the lead. The
6174
+ name is the run's `Lead:` (from state.json, else plan.md), else `lead`. Prints one line; never fails."""
6175
+ st, name = None, "lead"
6176
+ with contextlib.suppress(Exception):
6177
+ r = git("rev-parse", "--path-format=absolute", "--git-common-dir", check=False)
6178
+ if r.returncode == 0:
6179
+ o = Path(r.stdout.strip()).parent / ".orchestrate"
6180
+ if (o / "state.json").exists():
6181
+ st = json.loads((o / "state.json").read_text())
6182
+ name = (st.get("lead") or {}).get("name") or name
6183
+ elif (o / "plan.md").exists():
6184
+ m = re.search(r"(?mi)^Lead:\s*([\w.-]+)", (o / "plan.md").read_text())
6185
+ name = m.group(1) if m and m.group(1).lower() != "none" else name
6186
+ if not os.environ.get("HERDR_PANE_ID"):
6187
+ pid, _ = herdr_current_pane()
6188
+ if pid:
6189
+ print(f"LEAD name your pane `{name}` (HERDR_PANE_ID is unset, so orch can't tell which pane is yours): "
6190
+ f"`orch lead whoami`, then herdr agent rename <your pane id> {name}\n")
6191
+ return
6192
+ ok, line = name_lead(name, st)
6193
+ print(line + ("" if ok else f"\n Name your pane `{name}` before `orch start`: `orch lead whoami` shows it.") + "\n")
6194
+
6195
+
5475
6196
  def cmd_lead(args):
5476
6197
  """orch lead plan|run -> print the lead playbook; orch lead whoami -> this pane + how to name it `lead`."""
5477
6198
  sub = args[0] if args else ""
@@ -5489,6 +6210,8 @@ def cmd_lead(args):
5489
6210
  return
5490
6211
  label = f"{sub} ({part})" if part else sub
5491
6212
  print(f"herdr-orchestra {installed_version()} — lead playbook: {label}\n")
6213
+ if not part:
6214
+ lead_self_name()
5492
6215
  print(plan_playbook_part(pb.read_text(), part) if sub == "plan" else pb.read_text(), end="")
5493
6216
  return
5494
6217
  if sub == "check":
@@ -5513,8 +6236,13 @@ def cmd_lead(args):
5513
6236
  except (ValueError, KeyError, TypeError):
5514
6237
  pid = (re.search(r'"?pane_id"?\s*[:=]\s*"?([\w:.-]+)', out) or [None, None])[1]
5515
6238
  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.")
6239
+ named = False
6240
+ if os.environ.get("HERDR_PANE_ID"):
6241
+ named, line = name_lead("lead")
6242
+ print(line)
6243
+ if not named:
6244
+ print(f"This pane is YOU (the lead). Name it: herdr agent rename {pid or '<pane id>'} lead")
6245
+ print("Write `Lead: lead (<your kind>)` in the plan header, and never prompt this pane.")
5518
6246
  return
5519
6247
  die("usage: orch lead plan | run | check | whoami")
5520
6248
 
@@ -6315,6 +7043,7 @@ if __name__ == "__main__":
6315
7043
  ORCH = ROOT / ".orchestrate"
6316
7044
  ORCH.mkdir(exist_ok=True)
6317
7045
  STATE = ORCH / "state.json"
7046
+ BG_DIR = ORCH / "bg"
6318
7047
  if sys.argv[1] not in LEASE_FREE:
6319
7048
  require_driver()
6320
7049
  try: