herdr-orchestra 6.22.0 → 6.24.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
@@ -1190,7 +1190,8 @@ def is_dirty(path):
1190
1190
 
1191
1191
  # ---------------------------------------------------------------- plan parsing
1192
1192
  HEAD_RE = re.compile(r"^## \[( |x|X)\]\s*(M\d+)\s*:\s*(.+?)\s*$")
1193
- FIELD_RE = re.compile(r"^([A-Z][A-Za-z ]+):\s*(.*)$")
1193
+ # a key is words; its last word may also hold digits, dots, dashes (`Check web-app:`, `Workers api2:`)
1194
+ FIELD_RE = re.compile(r"^([A-Z][A-Za-z ]*(?: [A-Za-z0-9][\w.-]*)?):\s*(.*)$")
1194
1195
 
1195
1196
 
1196
1197
  def parse_plan(text):
@@ -1243,6 +1244,9 @@ def field(t, key, default=""):
1243
1244
  return " ".join(vals).strip() if vals else default
1244
1245
 
1245
1246
 
1247
+ EXT_DEP_RE = re.compile(r"\b([A-Za-z][\w.-]*):(M\d+)\b")
1248
+
1249
+
1246
1250
  def split_ids(s):
1247
1251
  if not s or s.lower() in ("none", "-", "n/a"):
1248
1252
  return []
@@ -1343,6 +1347,14 @@ def cmd_sync(args):
1343
1347
  workers = parse_agents(get("workers"))
1344
1348
  if not workers:
1345
1349
  errors.append("plan header needs `Workers: claude-1 (claude), codex-1 (codex)`")
1350
+ # a monorepo's sides: `Check frontend: cd web && pnpm test` + `Side: frontend` on a milestone checks only that side
1351
+ sides = {k[len("check "):].strip(): " ".join(v).strip() for k, v in cfg.items()
1352
+ if k.startswith("check ") and k != "check command" and " ".join(v).strip()}
1353
+ workspace = get("workspace") or None # written by `orch sync` in a workspace of several repos
1354
+ ws_repos = workspace_repos(Path(workspace)) if workspace else {}
1355
+ if workspace and not ws_repos:
1356
+ errors.append(f"`Workspace: {workspace}` names a folder with no workspace plan (.orchestrate/workspace.json) — "
1357
+ f"run `orch sync` in that folder")
1346
1358
  rev = get("reviewer", "none")
1347
1359
  rm = re.match(r"([\w.-]+)\s*\(", rev)
1348
1360
  reviewer = None if rev.lower().startswith("none") or not rm else rm.group(1)
@@ -1392,7 +1404,28 @@ def cmd_sync(args):
1392
1404
  errors.append(f"duplicate task ids: {sorted(dupes)}")
1393
1405
  by_id = {t["id"]: t for t in tasks}
1394
1406
  # "Depends on: M1 (uses the API types M1 defines), M2 (needs the table)": reasons in parentheses
1395
- deps = {t["id"]: split_ids(re.sub(r"\([^)]*\)", "", field(t, "depends on", "none"))) for t in tasks}
1407
+ deps = {t["id"]: split_ids(EXT_DEP_RE.sub("", re.sub(r"\([^)]*\)", "", field(t, "depends on", "none"))))
1408
+ for t in tasks}
1409
+ # "Depends on: backend:M2 (the endpoint)": a milestone of another repo in the same workspace
1410
+ ext_deps = {}
1411
+ for t in tasks:
1412
+ for repo_, mid in EXT_DEP_RE.findall(re.sub(r"\([^)]*\)", "", field(t, "depends on", "none"))):
1413
+ if repo_.lower() not in ws_repos:
1414
+ errors.append(f"{t['id']} depends on {repo_}:{mid}, but " + (
1415
+ f"the workspace has no repo {repo_!r} (repos: {', '.join(ws_repos)})" if ws_repos else
1416
+ "this run is not part of a workspace of several repos (write the repo:Mn form only there)"))
1417
+ continue
1418
+ ext_deps.setdefault(t["id"], []).append({"repo": repo_.lower(), "path": ws_repos[repo_.lower()],
1419
+ "id": mid})
1420
+ side_of = {}
1421
+ for t in tasks:
1422
+ sd = field(t, "side").split()[0].lower() if field(t, "side") else None
1423
+ if sd and sd not in sides:
1424
+ errors.append(f"{t['id']} has `Side: {sd}`, but the plan has no `Check {sd}:` line"
1425
+ + (f" (sides: {', '.join(sides)})" if sides else
1426
+ " — add one, e.g. `Check frontend: cd frontend && npm test`"))
1427
+ side_of[t["id"]] = sd if sd in sides else None
1428
+ errors += name_clashes(workers, reviewer, lead[0] if lead else None, workspace)
1396
1429
  for t in tasks:
1397
1430
  raw = field(t, "depends on", "none")
1398
1431
  for d in deps[t["id"]]:
@@ -1642,7 +1675,7 @@ def cmd_sync(args):
1642
1675
  "title": title_m.group(1) if title_m else branch,
1643
1676
  "commits": commits,
1644
1677
  "mode": mode,
1645
- "orch_mode": old.get("orch_mode") or config_mode(), # panes (herdr) or subagent (Pi): kept for the run
1678
+ "orch_mode": plan_orch_mode(old, branch, lead[1][0] if lead else None), # panes, or subagent (Pi leads only)
1646
1679
  "quick_because": quick_because if quick else None,
1647
1680
  "green_tree": old.get("green_tree"),
1648
1681
  "integration_broken": old.get("integration_broken"),
@@ -1665,6 +1698,8 @@ def cmd_sync(args):
1665
1698
  "budget_s": budget_s,
1666
1699
  "estimate_s": feature_est,
1667
1700
  "check": get("check command"),
1701
+ "sides": sides,
1702
+ "workspace": workspace,
1668
1703
  "setup": get("setup command", "none"),
1669
1704
  "reviewer": reviewer,
1670
1705
  "reviewer_info": ({"kind": rev_kind, "pane": rev_pane, "detect": detect(rev_kind, rev_pane, "Reviewer"),
@@ -1733,6 +1768,7 @@ def cmd_sync(args):
1733
1768
  "plain": field(t, "plain"), "why_sep": field(t, "why separate"), "deps_text": field(t, "depends on"),
1734
1769
  # hard to undo: always held for `orch approve`, with the coder's proof (None = easy to undo)
1735
1770
  "door": "one-way" if tid in doors else None, "door_why": doors.get(tid) or None,
1771
+ "side": side_of.get(tid), "ext_deps": ext_deps.get(tid) or [],
1736
1772
  }
1737
1773
  if status != st["tasks"][tid]["status"]:
1738
1774
  move(st, tid, status, {"skipped": "unticked in plan.md", "needs-answer": "open questions in plan.md"}
@@ -2314,13 +2350,25 @@ def review_findings(tid, k):
2314
2350
  return blockers, sugg, known
2315
2351
 
2316
2352
 
2317
- def run_check(st, cwd):
2318
- """(passed, last 60 lines, seconds) for the plan's check command in cwd."""
2319
- if not st.get("check"):
2353
+ def check_for(st, tid=None):
2354
+ """The check command for milestone tid: its side's (`Side: frontend` + `Check frontend: ...`), else the plan's."""
2355
+ side = (st.get("tasks", {}).get(tid) or {}).get("side") if tid else None
2356
+ return (st.get("sides") or {}).get(side) or st.get("check") or ""
2357
+
2358
+
2359
+ def full_check(st, tid=None):
2360
+ """True when tid is checked with the plan's whole check command (not only its side's)."""
2361
+ return check_for(st, tid) == (st.get("check") or "")
2362
+
2363
+
2364
+ def run_check(st, cwd, tid=None):
2365
+ """(passed, last 60 lines, seconds) for the check command of milestone tid (else the plan's) in cwd."""
2366
+ cmd = check_for(st, tid)
2367
+ if not cmd:
2320
2368
  return True, "", 0
2321
2369
  t0 = time.time()
2322
2370
  try:
2323
- r = subprocess.run(st["check"], shell=True, cwd=cwd, text=True, capture_output=True, timeout=CHECK_TIMEOUT_S)
2371
+ r = subprocess.run(cmd, shell=True, cwd=cwd, text=True, capture_output=True, timeout=CHECK_TIMEOUT_S)
2324
2372
  ok, tail = r.returncode == 0, "\n".join((r.stdout + r.stderr).splitlines()[-60:])
2325
2373
  except subprocess.TimeoutExpired:
2326
2374
  ok, tail = False, f"check command timed out after {CHECK_TIMEOUT_S // 60} min"
@@ -2344,9 +2392,10 @@ def tree_of(d):
2344
2392
  return None
2345
2393
 
2346
2394
 
2347
- def note_green(st, d, ok):
2348
- """Remember the tree a passing check ran on in the main folder (a failing one forgets it)."""
2349
- if Path(d).resolve() != ROOT.resolve():
2395
+ def note_green(st, d, ok, tid=None):
2396
+ """Remember the tree a passing check ran on in the main folder (a failing one forgets it). Only the plan's whole
2397
+ check counts: a side's check (`Side:`) covers part of the repo, so `orch finish` must still run the whole one."""
2398
+ if Path(d).resolve() != ROOT.resolve() or (ok and not full_check(st, tid)):
2350
2399
  return
2351
2400
  st["green_tree"] = tree_of(d) if ok else None
2352
2401
 
@@ -2599,7 +2648,43 @@ def cmd_start(args):
2599
2648
 
2600
2649
 
2601
2650
  def deps_met(st, t):
2602
- return all(st["tasks"][d]["status"] == "merged" for d in t["deps"])
2651
+ return all(st["tasks"][d]["status"] == "merged" for d in t["deps"]) and not ext_waits(t)
2652
+
2653
+
2654
+ def ext_status(e):
2655
+ """Status of a milestone in another repo of the workspace (`Depends on: backend:M2`), read from that repo's run."""
2656
+ try:
2657
+ return json.loads((Path(e["path"]) / ".orchestrate" / "state.json").read_text())["tasks"][e["id"]]["status"]
2658
+ except (OSError, ValueError, KeyError, TypeError):
2659
+ return "unknown"
2660
+
2661
+
2662
+ def ext_waits(t):
2663
+ """The milestones in other repos that t still waits for: [(dep, its status)]."""
2664
+ out = []
2665
+ for e in t.get("ext_deps") or []:
2666
+ s_ = ext_status(e)
2667
+ if s_ != "merged":
2668
+ out.append((e, s_))
2669
+ return out
2670
+
2671
+
2672
+ def run_alive(path):
2673
+ """True while the event manager of the run in path (another repo of the workspace) holds its lease."""
2674
+ p = Path(path) / ".orchestrate" / "driver.lock"
2675
+ if not p.exists():
2676
+ return False
2677
+ with open(p, "a") as f:
2678
+ try:
2679
+ fcntl.flock(f, fcntl.LOCK_SH | fcntl.LOCK_NB)
2680
+ except OSError:
2681
+ return True
2682
+ fcntl.flock(f, fcntl.LOCK_UN)
2683
+ return False
2684
+
2685
+
2686
+ def ext_line(waits):
2687
+ return ", ".join(f"{e['repo']} {e['id']} ({s_})" for e, s_ in waits)
2603
2688
 
2604
2689
 
2605
2690
  def active_count(st):
@@ -2631,6 +2716,8 @@ def fix_jobs(st):
2631
2716
  def cmd_ready(args):
2632
2717
  st = load()
2633
2718
  cand = [tid for tid in st["order"] if st["tasks"][tid]["status"] == "pending" and deps_met(st, st["tasks"][tid])]
2719
+ ext_wait = [f"WAIT {tid} waits for another repo: {ext_line(ext_waits(st['tasks'][tid]))}" for tid in st["order"]
2720
+ if st["tasks"][tid]["status"] == "pending" and ext_waits(st["tasks"][tid])]
2634
2721
  # milestones that share Likely files run one after the other unless one says `Parallel: allow`
2635
2722
  busy = {}
2636
2723
  for tid, t in st["tasks"].items():
@@ -2668,7 +2755,7 @@ def cmd_ready(args):
2668
2755
  print(f"FIX {tid} {st['tasks'][tid]['status']} {st['tasks'][tid]['title']}")
2669
2756
  for tid in out:
2670
2757
  print(f"READY {tid} {st['tasks'][tid]['title']}")
2671
- for line in waits:
2758
+ for line in waits + ext_wait:
2672
2759
  print(line)
2673
2760
 
2674
2761
 
@@ -3024,7 +3111,7 @@ def cmd_needs_fix(args):
3024
3111
  t["job"] = {"file": f"review-fix-{k}.md", "body":
3025
3112
  f"# Review findings for {tid}: {t['title']} (round {k})\n\n"
3026
3113
  "The reviewer found the problems below. You own the fix: investigate each one and decide how to "
3027
- f"solve it. Keep every acceptance criterion in {TASK_DIR}/{tid}/task.md, then run `{st['check']}`.\n"
3114
+ f"solve it. Keep every acceptance criterion in {TASK_DIR}/{tid}/task.md, then run `{check_for(st, tid)}`.\n"
3028
3115
  "If you think a finding is wrong, explain why in your report instead of changing code for it.\n\n"
3029
3116
  + "\n".join(blockers) + "\n"}
3030
3117
  move(st, tid, "needs-fix")
@@ -3118,7 +3205,7 @@ def cmd_review(args):
3118
3205
  + (", the words listed above" if rules["glossary"] else "") +
3119
3206
  "? A `rules` finding names the rule it breaks in `rule`. Only written rules count: a matter of taste is at "
3120
3207
  "most a suggestion.\n"
3121
- f"The check command (`{st['check']}`) runs on this work by itself: don't report what lint, type checks or "
3208
+ f"The check command (`{check_for(st, tid)}`) runs on this work by itself: don't report what lint, type checks or "
3122
3209
  "tests already catch.\n"
3123
3210
  "Do NOT edit any code. Never commit, push or merge: no agent ever pushes to main or merges a PR, even when "
3124
3211
  "asked.\n"
@@ -3402,7 +3489,7 @@ def merge_check_needed(st, tid):
3402
3489
  run on the same files and can only say the same thing."""
3403
3490
  t = st["tasks"][tid]
3404
3491
  chk = t.get("chk") or {}
3405
- if st["isolation"] != "worktree" or not st.get("check") or not chk.get("ok") or not chk.get("tree"):
3492
+ if st["isolation"] != "worktree" or not check_for(st, tid) or not chk.get("ok") or not chk.get("tree"):
3406
3493
  return True
3407
3494
  if st.get("branch_check") == "always": # the check depends on more than the files (the folder, the branch)
3408
3495
  return True
@@ -3428,7 +3515,7 @@ def cmd_merge(args):
3428
3515
  ok, tail = ensure_root_setup(st)
3429
3516
  secs = 0
3430
3517
  if ok:
3431
- ok, tail, secs = run_check(st, ROOT)
3518
+ ok, tail, secs = run_check(st, ROOT, tid)
3432
3519
  with state_lock():
3433
3520
  st2 = load()
3434
3521
  t = st2["tasks"][tid]
@@ -3441,7 +3528,7 @@ def cmd_merge(args):
3441
3528
  st2["merging"] = None
3442
3529
  _integration_failed(st2, tid, tail)
3443
3530
  git("commit", "-q", "-m", commit_message(st2, tid), cwd=ROOT)
3444
- note_green(st2, ROOT, True)
3531
+ note_green(st2, ROOT, True, tid)
3445
3532
  fault("after-merge-commit")
3446
3533
  git("update-ref", "-d", task_ref(st2, tid), cwd=ROOT, check=False)
3447
3534
  _finish(st2, tid)
@@ -3486,7 +3573,7 @@ def _merge_start(tid):
3486
3573
  f"Other milestones landed on `{st['branch']}` while you worked, and they conflict with "
3487
3574
  f"yours in: {', '.join(files) or 'see git status'}.\n"
3488
3575
  f"In this folder run `git merge --no-commit {st['branch']}`, resolve every conflict so BOTH "
3489
- f"sides keep working (you own the resolution), then run `{st['check']}`. Do not commit.\n"}
3576
+ f"sides keep working (you own the resolution), then run `{check_for(st, tid)}`. Do not commit.\n"}
3490
3577
  save(st)
3491
3578
  who = t["worker"] if holds(st, tid) else "any free coder"
3492
3579
  print(f"CONFLICT {tid} files={','.join(files)} -> conflict job queued for {who} (`orch send-job {tid}`)")
@@ -3504,7 +3591,7 @@ def _merge_start(tid):
3504
3591
  f"(nothing else landed meanwhile), so the check was not run again")
3505
3592
  fault("after-check")
3506
3593
  git("commit", "-q", "-m", commit_message(st, tid), cwd=ROOT)
3507
- note_green(st, ROOT, True)
3594
+ note_green(st, ROOT, True, tid)
3508
3595
  fault("after-merge-commit")
3509
3596
  git("update-ref", "-d", task_ref(st, tid), cwd=ROOT, check=False)
3510
3597
  _finish(st, tid)
@@ -3546,9 +3633,9 @@ def _integration_failed(st, tid, tail):
3546
3633
  n = t["fix"]
3547
3634
  t["job"] = {"file": f"integration-fix-{n}.md", "body":
3548
3635
  f"# {tid} fails the check once merged onto `{st['branch']}` (round {n})\n\n"
3549
- f"Your milestone passes `{st['check']}` on its own, but fails once it is merged with what landed on "
3636
+ f"Your milestone passes `{check_for(st, tid)}` on its own, but fails once it is merged with what landed on "
3550
3637
  f"`{st['branch']}` since you started. In this folder run `git merge --no-commit {st['branch']}`, find "
3551
- f"the cause and fix it (you decide how, and keep both sides working), then run `{st['check']}`. "
3638
+ f"the cause and fix it (you decide how, and keep both sides working), then run `{check_for(st, tid)}`. "
3552
3639
  f"Don't commit, and don't weaken or skip tests.\n\n```\n{tail}\n```\n"}
3553
3640
  move(st, tid, "needs-fix", f"fails the check on {st['branch']} once merged (round {n})")
3554
3641
  t["wait"] = None
@@ -3844,7 +3931,7 @@ def cmd_status(args):
3844
3931
  else ""))
3845
3932
  for tid in st["order"]:
3846
3933
  t = st["tasks"][tid]
3847
- print(f" {tid:<4} {t['status']:<15} deps={','.join(t['deps']) or '-':<10} "
3934
+ print(f" {tid:<4} {t['status']:<15} deps={','.join(t['deps'] + [e['repo'] + ':' + e['id'] for e in t.get('ext_deps') or []]) or '-':<10} "
3848
3935
  f"worker={t.get('worker') or '-':<10} "
3849
3936
  + (f"tier={t['tier'] if rank(t.get('min_tier')) <= rank(t.get('tier')) else t['min_tier'] + '^'} "
3850
3937
  if need_rank(t) else "") + t["title"]
@@ -3875,6 +3962,10 @@ def cmd_status(args):
3875
3962
  print(f"ALL_DONE — run `orch finish` to push {st['branch']} and open a PR into {st.get('base')}")
3876
3963
  elif lead_on(st) and (undispatched(st) or any(event_open(st, e) for e in st["lead_events"])):
3877
3964
  pass
3965
+ elif not any(t["status"] in ACTIVE for t in st["tasks"].values()) and (ext := [
3966
+ f"{k} waits for {ext_line(ext_waits(t))}" for k, t in st["tasks"].items()
3967
+ if t["status"] == "pending" and ext_waits(t)]):
3968
+ print("WAITING FOR ANOTHER REPO — " + "; ".join(ext))
3878
3969
  elif not any(t["status"] in ACTIVE for t in st["tasks"].values()) and not any(
3879
3970
  t["status"] == "pending" and deps_met(st, t) for t in st["tasks"].values()):
3880
3971
  print("STUCK — nothing running and nothing ready; resolve paused/needs-answer/failed tasks with the developer")
@@ -4303,7 +4394,7 @@ WORKER_RULES = """## Rules for you (the coder)
4303
4394
 
4304
4395
  # plan.md lines that are for the lead and orch, not the coder: they stay in plan.md and task.json
4305
4396
  LEAD_ONLY_FIELDS = {"depends on", "why separate", "prefer", "tier", "needs", "model why", "estimate", "role", "door",
4306
- "review", "parallel", "plain"}
4397
+ "review", "parallel", "plain", "side", "repo"}
4307
4398
 
4308
4399
 
4309
4400
  def coder_section(text, drop_criteria):
@@ -4378,7 +4469,7 @@ def cmd_write_task(args):
4378
4469
  if contract["previous_work"]:
4379
4470
  parts += ["## Earlier work", f"An earlier attempt ({contract['previous_work']['by'] or 'another coder'}) left "
4380
4471
  "work in this folder. Look at it first and continue from it unless it is wrong.", ""]
4381
- parts += [f"## Check command\n`{st['check']}`", "", WORKER_RULES]
4472
+ parts += [f"## Check command\n`{check_for(st, tid)}`", "", WORKER_RULES]
4382
4473
  out = d / TASK_DIR / tid / "task.md"
4383
4474
  out.parent.mkdir(parents=True, exist_ok=True)
4384
4475
  out.write_text("\n".join(parts))
@@ -4414,7 +4505,7 @@ def task_contract(st, tid):
4414
4505
  "files_allowed": t.get("files") or [], "scope": st.get("scope", "warn"),
4415
4506
  "tier": t.get("tier"), "needs": t.get("needs") or [], "role": t.get("role") or None,
4416
4507
  "interfaces": items("interfaces"), "constraints": items("constraints"), "out_of_scope": items("out of scope"),
4417
- "depends_on": deps, "check": st["check"], "attempt": t.get("attempt", 0) + 1, "lost_attempts": t.get("lost", 0),
4508
+ "depends_on": deps, "check": check_for(st, tid), "attempt": t.get("attempt", 0) + 1, "lost_attempts": t.get("lost", 0),
4418
4509
  "previous_work": {"by": t.get("last_worker")} if work_ref(st, tid) else None,
4419
4510
  "result_format": RESULT_FORMAT,
4420
4511
  }
@@ -5260,6 +5351,11 @@ def _autopilot(args):
5260
5351
  out = (r.stdout + r.stderr).strip()
5261
5352
  if r.returncode not in ok:
5262
5353
  raise RuntimeError(f"orch {' '.join(str(x) for x in a)} -> exit {r.returncode}: {out}")
5354
+ if r.returncode == 0 and a[0] in ("send", "review"):
5355
+ # a job just started: tell herdr's sidebar now, not at the next round (a short review could be missed)
5356
+ with contextlib.suppress(NameError):
5357
+ if names:
5358
+ names.update(load())
5263
5359
  return r.returncode, out
5264
5360
 
5265
5361
  def patch_state(fn):
@@ -5269,8 +5365,8 @@ def _autopilot(args):
5269
5365
  save(s_)
5270
5366
 
5271
5367
  def check(cwd, tid=None, where="worktree"):
5272
- ok, tail, secs = run_check(st, cwd)
5273
- patch_state(lambda s_: note_green(s_, cwd, ok))
5368
+ ok, tail, secs = run_check(load(), cwd, tid)
5369
+ patch_state(lambda s_: note_green(s_, cwd, ok, tid))
5274
5370
  if tid:
5275
5371
  patch_state(lambda s_: s_["tasks"][tid].setdefault("checks", []).append(
5276
5372
  {"where": where, "ok": ok, "secs": secs, "ts": now()}))
@@ -5526,7 +5622,7 @@ def _autopilot(args):
5526
5622
  s_ = load()
5527
5623
  t_ = s_["tasks"][tid]
5528
5624
  k = t_["attempt"]
5529
- if not s_.get("check"):
5625
+ if not check_for(s_, tid):
5530
5626
  check_done(tid, k, d, None, 0, "", 0)
5531
5627
  return True
5532
5628
  if check_slots() <= 0:
@@ -5536,7 +5632,7 @@ def _autopilot(args):
5536
5632
  end_wait(tid, "check slot")
5537
5633
  tree0 = tree_of(d)
5538
5634
  patch_state(lambda s2: s2["tasks"][tid].update(checking={"since": now(), "where": "worktree"}))
5539
- bg_start(f"check-{tid}-{k}", tid, "check", s_["check"], d, True,
5635
+ bg_start(f"check-{tid}-{k}", tid, "check", check_for(s_, tid), d, True,
5540
5636
  lambda code, out, secs: check_done(tid, k, d, tree0, code, out, secs), CHECK_TIMEOUT_S)
5541
5637
  return True
5542
5638
 
@@ -5548,20 +5644,20 @@ def _autopilot(args):
5548
5644
  def upd(s2):
5549
5645
  t2 = s2["tasks"][tid]
5550
5646
  t2.pop("checking", None)
5551
- if s2.get("check"):
5647
+ if check_for(s2, tid):
5552
5648
  t2.setdefault("checks", []).append({"where": "worktree", "ok": ok, "secs": secs, "ts": now()})
5553
5649
  # the tree is kept only when the check left the files as it found them: then a branch that gets exactly
5554
5650
  # these files needs no second check (merge_check_needed)
5555
5651
  t2["chk"] = {"attempt": k, "ok": ok, "tail": tail, "tree": tree if tree and tree == tree0 else None,
5556
5652
  "used": False}
5557
- note_green(s2, d, ok)
5653
+ note_green(s2, d, ok, tid)
5558
5654
  patch_state(upd)
5559
- if s_check := load().get("check"):
5655
+ if s_check := check_for(load(), tid):
5560
5656
  say(f"{tid} check {'passed' if ok else 'FAILED'} in {_fmt_secs(secs)} ({s_check})")
5561
5657
 
5562
5658
  def early_review_ok(tid, t):
5563
5659
  s_ = load()
5564
- return (s_.get("early_review", True) and bool(s_.get("check")) and bool(s_.get("reviewer"))
5660
+ return (s_.get("early_review", True) and bool(check_for(s_, tid)) and bool(s_.get("reviewer"))
5565
5661
  and t["review"] and not t.get("review_ok") and not t.get("pre_conflict") and holds(s_, tid))
5566
5662
 
5567
5663
  def check_fix(tid, tail, blockers=()):
@@ -5574,7 +5670,7 @@ def _autopilot(args):
5574
5670
  say(f"{tid} checks failed -> fix round {n}" + (f" (with the reviewer's {len(blockers)} blocker(s))"
5575
5671
  if blockers else ""))
5576
5672
  write_and_send(tid, f"fix-{n}.md",
5577
- f"# Checks failing for {tid} (round {n})\n\nThe check command `{st['check']}` "
5673
+ f"# Checks failing for {tid} (round {n})\n\nThe check command `{check_for(st, tid)}` "
5578
5674
  f"failed. Diagnose the cause and fix it; you decide how. Don't change unrelated "
5579
5675
  f"code, and don't weaken or skip tests to make them pass.\n\n"
5580
5676
  f"```\n{tail}\n```\n"
@@ -5770,7 +5866,7 @@ def _autopilot(args):
5770
5866
  f"# {tid} changed files outside its scope (round {n})\n\n"
5771
5867
  f"This milestone may change only: {', '.join(allowed)}. It also changed: "
5772
5868
  f"{', '.join(new)}.\nUndo those changes, or, if the task truly can't be done without them, "
5773
- f"leave them and explain why in your report. Then run `{st['check']}`.\n"),
5869
+ f"leave them and explain why in your report. Then run `{check_for(st, tid)}`.\n"),
5774
5870
  f"still outside its scope after {MAX_FIX} fix rounds: {', '.join(new)}")
5775
5871
  return False
5776
5872
  if new:
@@ -5793,7 +5889,7 @@ def _autopilot(args):
5793
5889
  + "\n".join(f"- {c['id']}: {c.get('evidence', '')}" for c in unmet)
5794
5890
  + (f"\n\nAlready deferred by the developer (leave them; keep them `met: false`): "
5795
5891
  f"{', '.join(skipped)}." if skipped else "")
5796
- + f"\n\nFinish them (you decide how), run `{st['check']}`, and write a new result.\n"
5892
+ + f"\n\nFinish them (you decide how), run `{check_for(st, tid)}`, and write a new result.\n"
5797
5893
  "If one truly can't be met in this repo (for example an outside API or service it needs does not "
5798
5894
  "exist), don't try again: set status `question`, say which criterion and why, and offer to "
5799
5895
  "build the rest and defer that one. The developer decides.\n"),
@@ -6107,6 +6203,8 @@ def _autopilot(args):
6107
6203
  last_tick = time.time()
6108
6204
  slept = sleep_meter()
6109
6205
  waiting_since = None # set while nothing runs and the run waits for the lead or the developer
6206
+ ext_told = None # what was last said about waiting for another repo of the workspace
6207
+ ext_since = time.time()
6110
6208
  seen = {"procs": time.time(), "check": 0.0, "present": None, "told": False}
6111
6209
 
6112
6210
  def watch_herdr():
@@ -6307,6 +6405,23 @@ def _autopilot(args):
6307
6405
  run("poll", str(int(min(30, max(1, POLL_STEP_S * 3)))), ok=(0, 10))
6308
6406
  continue
6309
6407
  waiting_since = None
6408
+ # a workspace of several repos: a milestone here waits for one in another repo (its own run lands it)
6409
+ ext = {k: ext_waits(v) for k, v in tasks.items() if v["status"] == "pending" and v.get("ext_deps")
6410
+ and all(tasks[d]["status"] == "merged" for d in v["deps"])}
6411
+ ext = {k: w for k, w in ext.items() if w and not any(s_ in ("failed", "skipped") for _, s_ in w)}
6412
+ if not active and not ready and ext:
6413
+ line = "; ".join(f"{k} waits for {ext_line(w)}" for k, w in ext.items())
6414
+ if line != ext_told:
6415
+ say(f"waiting for another repo: {line}", True)
6416
+ ext_told, ext_since = line, time.time()
6417
+ idle = sorted({e["repo"] for w in ext.values() for e, _ in w if not run_alive(e["path"])})
6418
+ if idle and time.time() - ext_since > LEAD_IDLE_MAX_S:
6419
+ say(f"STOPPED — still waiting for another repo after {LEAD_IDLE_MAX_S // 60} min, and the event manager "
6420
+ f"of {', '.join(idle)} is not running: {line}. Everything is kept: start it there (`orch autopilot` "
6421
+ f"in the workspace starts every repo's)", True)
6422
+ sys.exit(3)
6423
+ run("poll", str(int(min(30, max(1, POLL_STEP_S * 3)))), ok=(0, 10))
6424
+ continue
6310
6425
  if not active and not ready:
6311
6426
  bg_reap() # a background merge that just ended (held, failed) says so before we stop
6312
6427
  waiting = [f" {k} {v['status']}: {v.get('reason') or ''}" for k, v in tasks.items()
@@ -6790,8 +6905,15 @@ def cmd_team(args):
6790
6905
  orch team up [--dry-run] -> open a herdr pane for every agent in the plan that herdr cannot find."""
6791
6906
  if args and args[0] == "up":
6792
6907
  return team_up(args[1:])
6793
- usage = "usage: orch team <kind> [--coders N] [--models a,b] [--no-reviewer] | orch team up [--dry-run]"
6794
- rest, coders, models, reviewer = list(args), None, None, True
6908
+ usage = ("usage: orch team <kind> [--coders N] [--models a,b] [--no-reviewer] [--prefix <name>] | "
6909
+ "orch team up [--dry-run]")
6910
+ rest, coders, models, reviewer, prefix = list(args), None, None, True, None
6911
+ if "--prefix" in rest:
6912
+ i = rest.index("--prefix")
6913
+ prefix = rest[i + 1] if len(rest) > i + 1 else die(usage)
6914
+ del rest[i:i + 2]
6915
+ if not re.fullmatch(r"[A-Za-z0-9][\w.-]*", prefix):
6916
+ die("--prefix takes a plain name, e.g. --prefix frontend")
6795
6917
  if "--no-reviewer" in rest:
6796
6918
  rest.remove("--no-reviewer")
6797
6919
  reviewer = False
@@ -6827,17 +6949,23 @@ def cmd_team(args):
6827
6949
  top = cands[-1][0] if cands else None
6828
6950
  no_flag = not v.get("model_flag")
6829
6951
  fmt = lambda name, m: f"{name} ({kind}: {m})" if m and not no_flag else f"{name} ({kind})"
6830
- workers = [fmt(f"{kind}-{i + 1}", m) for i, m in enumerate(picked)]
6952
+ if prefix is None: # another run is going on this machine: names it doesn't use
6953
+ prefix, busy_in = team_prefix([f"{kind}-{i + 1}" for i in range(len(picked))] + ["reviewer", "lead"])
6954
+ if prefix:
6955
+ print(f"NOTE: another run ({busy_in}) is going and uses these names, so this team's names start with "
6956
+ f"{prefix}- (herdr finds agents by name; `--prefix <name>` picks another)")
6957
+ pre = f"{prefix}-" if prefix else ""
6958
+ workers = [fmt(f"{pre}{kind}-{i + 1}", m) for i, m in enumerate(picked)]
6831
6959
  tier = {mid: t for mid, t in cands}
6832
6960
  print(f"TEAM from {kind}: {len(workers)} coder(s)" + (", 1 reviewer" if reviewer and "reviewer" in roles else ""))
6833
6961
  for i, m in enumerate(picked):
6834
- print(f" {kind + '-' + str(i + 1):<12} {m or 'its default model'}" + (f" ({tier[m]} tier)" if m in tier else ""))
6962
+ print(f" {pre + kind + '-' + str(i + 1):<12} {m or 'its default model'}" + (f" ({tier[m]} tier)" if m in tier else ""))
6835
6963
  if reviewer and "reviewer" in roles:
6836
- print(f" {'reviewer':<12} {top or 'its default model'}" + (f" ({tier[top]} tier)" if top in tier else ""))
6964
+ print(f" {pre + 'reviewer':<12} {top or 'its default model'}" + (f" ({tier[top]} tier)" if top in tier else ""))
6837
6965
  print("\nPlan header lines:")
6838
- print(f"Lead: lead ({kind}: <the model your own pane runs>)")
6966
+ print(f"Lead: {pre}lead ({kind}: <the model your own pane runs>)")
6839
6967
  print("Workers: " + ", ".join(workers))
6840
- print("Reviewer: " + (fmt("reviewer", top) if reviewer and "reviewer" in roles else "none"))
6968
+ print("Reviewer: " + (fmt(f"{pre}reviewer", top) if reviewer and "reviewer" in roles else "none"))
6841
6969
  if not cands and not models:
6842
6970
  print(f"\nNOTE: the model catalog has no allowed model for {kind}, so every pane starts on its default model "
6843
6971
  f"(add models in {user_models_file()} to get tiers)")
@@ -6847,7 +6975,7 @@ def cmd_team(args):
6847
6975
  print(f"\nNOTE: the strongest allowed {kind} model is {top} ({tier.get(top)} tier): high-tier milestones go to "
6848
6976
  f"it, and `orch sync` will say so")
6849
6977
  if top and v.get("model_flag") and "lead" in roles:
6850
- print(f"\nYour own lead pane on the strongest level (start it like this, then write `Lead: lead ({kind}: {top})`):"
6978
+ print(f"\nYour own lead pane on the strongest level (start it like this, then write `Lead: {pre}lead ({kind}: {top})`):"
6851
6979
  f"\n {launch_cmd(kind, v, top, strict=False, role='lead')}")
6852
6980
  print(f"\nCheck these are models your {kind} really reaches (`--models a,b` to choose others).")
6853
6981
  print("\nThese panes don't exist yet. After `orch sync` and `orch start`, `orch team up` opens each one in its "
@@ -6875,7 +7003,7 @@ def team_up(args):
6875
7003
  flag = mode_flag(args, "usage: orch team up [--dry-run] [--mode panes|subagent]")
6876
7004
  dry = "--dry-run" in args
6877
7005
  if flag and not dry:
6878
- set_mode(flag, hint=False)
7006
+ set_mode(flag, hint=False, agent=mode_target(flag, "usage: orch team up [--dry-run] [--mode panes|subagent]"))
6879
7007
  st = load()
6880
7008
  if (flag or run_mode(st)) == "subagent":
6881
7009
  print("mode subagent: no panes to open; the coder and the reviewer are Pi subagents")
@@ -7998,14 +8126,18 @@ USAGE = """usage: orch <command> [args]
7998
8126
  lead run --section <EVENT|ALL_DONE|rules> one part of the run playbook (orch events prints these for you)
7999
8127
  lead check preflight: is this agent in a Herdr pane / can it reach herdr?
8000
8128
  lead whoami show the lead's own herdr pane and name it as the plan's `Lead:` (default `lead`)
8001
- team <kind> [--coders N] [--models a,b] [--no-reviewer]
8129
+ team <kind> [--coders N] [--models a,b] [--no-reviewer] [--prefix <name>]
8002
8130
  the plan's team built from one installed tool: coders + reviewer on its catalog models
8131
+ (named after the repo, e.g. app-codex-1, while another run is going on this machine)
8003
8132
  team up [--dry-run] [--mode panes|subagent]
8004
8133
  open a herdr pane for every agent in the plan herdr can't find, in its folder, and name it
8005
8134
  (subagent mode: no panes; sets up the Pi coder/reviewer subagents instead)
8006
- mode [panes|subagent] which mode runs use: panes (herdr panes, the default) or subagent (one Pi window)
8007
- setup [--mode panes|subagent] get this machine ready for a mode; subagent: write ~/.pi/agent/agents/coder.md and
8008
- reviewer.md from ~/.config/herdr-orchestra/config.json and install pi-subagents
8135
+ mode [panes|subagent] [--agent <kind>] this agent's mode, or save one: panes (herdr panes, the default for
8136
+ every agent) or subagent (one Pi window; Pi only). Saved per agent in
8137
+ ~/.config/herdr-orchestra/config.json ("modes": {"pi": "subagent"}); ORCH_MODE=panes|subagent
8138
+ overrides it for one command. orch finds the agent by itself (ORCH_AGENT=<kind> to say it)
8139
+ setup [--mode panes|subagent] [--agent <kind>] get this machine ready for a mode; subagent (saved for Pi): write
8140
+ ~/.pi/agent/agents/coder.md and reviewer.md from the config and install pi-subagents
8009
8141
  agents the agent registry: kinds, installed?, roles, herdr detection, launch commands
8010
8142
  agents launch <kind> [--model <id>] [--role reviewer] print the command that starts <kind> in a pane
8011
8143
  (auto-approve edits; --role reviewer: its read-only reviewer command when it has one)
@@ -8033,7 +8165,9 @@ USAGE = """usage: orch <command> [args]
8033
8165
  guard [status|--print] install the pre-push guard: no agent ever pushes to main/master/the default branch
8034
8166
  (orch start installs it too); status: report it and whether GitHub protects main
8035
8167
  doctor [kind...] check installed agents against the real tool: version, launch flags, skills, herdr
8036
- sync parse .orchestrate/plan.md -> state.json (validates deps, cycles, overlaps)
8168
+ sync parse .orchestrate/plan.md -> state.json (validates deps, cycles, overlaps). In a workspace
8169
+ (plan header `Repos: frontend, backend`): writes and syncs each repo's own plan; then
8170
+ milestone commands go to that milestone's repo, the others run in every repo
8037
8171
  start create/switch to the feature branch (plan `Branch:`); create worker worktrees (worktree mode)
8038
8172
  status [--json] table of workers + tasks; prints ALL_DONE or STUCK when relevant. --json: the run summary
8039
8173
  both views read (milestones with their plain description, agents, counts, time, cost)
@@ -8313,6 +8447,8 @@ def lead_self_name():
8313
8447
 
8314
8448
  def cmd_lead(args):
8315
8449
  """orch lead plan|run -> print the lead playbook; orch lead whoami -> this pane + how to name it `lead`."""
8450
+ args = list(args)
8451
+ agent_flag(args, "usage: orch lead plan|run [--agent <kind>]") # which agent leads, when orch can't tell
8316
8452
  sub = args[0] if args else ""
8317
8453
  if sub in ("plan", "run"):
8318
8454
  pb = asset(f"playbooks/{sub}.md") or die(f"playbooks/{sub}.md not found next to orch or in the install")
@@ -8967,6 +9103,71 @@ def update_notice(network=True):
8967
9103
  pass
8968
9104
 
8969
9105
 
9106
+ def workspace_repos(ws):
9107
+ """{name: absolute path} of the repos in a workspace (its .orchestrate/workspace.json, written by `orch sync`)."""
9108
+ try:
9109
+ d = json.loads((Path(ws) / ".orchestrate" / "workspace.json").read_text())
9110
+ return {str(k).lower(): str(v) for k, v in (d.get("repos") or {}).items()}
9111
+ except (OSError, ValueError, AttributeError):
9112
+ return {}
9113
+
9114
+
9115
+ def run_names(root):
9116
+ """(workers + reviewer, lead name, workspace) of the run in root, from its state; None when it can't be read."""
9117
+ try:
9118
+ st = json.loads((Path(root) / ".orchestrate" / "state.json").read_text())
9119
+ except (OSError, ValueError):
9120
+ return None
9121
+ names = set(st.get("workers") or {}) | ({st["reviewer"]} if st.get("reviewer") else set())
9122
+ return names, (st.get("lead") or {}).get("name"), st.get("workspace")
9123
+
9124
+
9125
+ def name_clashes(workers, reviewer, lead, workspace):
9126
+ """Errors for agent names another run on this machine uses right now: herdr finds agents by name, so two runs
9127
+ with a `codex-1` each would send work to the same pane. A shared lead is fine inside one workspace."""
9128
+ if os.environ.get("ORCH_NAME_CHECK", "1") == "0":
9129
+ return []
9130
+ mine = set(workers) | ({reviewer} if reviewer else set()) | ({lead} if lead else set())
9131
+ errs = []
9132
+ here = ROOT.resolve() if ROOT else None
9133
+ for root in active_runs():
9134
+ if here and Path(root).resolve() == here:
9135
+ continue
9136
+ got = run_names(root)
9137
+ if not got:
9138
+ continue
9139
+ theirs, their_lead, their_ws = got
9140
+ if their_lead and not (workspace and their_ws == workspace and their_lead == lead):
9141
+ theirs = theirs | {their_lead}
9142
+ clash = sorted(mine & theirs)
9143
+ if clash:
9144
+ errs.append(f"{', '.join(clash)}: {'this name is' if len(clash) == 1 else 'these names are'} already used "
9145
+ f"by the run in {root}, which is going now. herdr finds agents by name, so both runs would "
9146
+ f"send work to the same pane. Rename {'it' if len(clash) == 1 else 'them'} in this plan, e.g. "
9147
+ f"`{(ROOT.name if ROOT else 'app')}-{clash[0]}` (`orch team <kind>` picks such names by "
9148
+ f"itself while another run is going)")
9149
+ return errs
9150
+
9151
+
9152
+ def team_prefix(names):
9153
+ """(prefix, the other run's folder) when a run going on this machine uses one of names, else (None, None).
9154
+ The prefix is this repo's folder name."""
9155
+ try:
9156
+ r = subprocess.run(["git", "rev-parse", "--show-toplevel"], text=True, capture_output=True, timeout=10)
9157
+ here = Path(r.stdout.strip()) if r.returncode == 0 and r.stdout.strip() else Path.cwd()
9158
+ except (OSError, subprocess.TimeoutExpired):
9159
+ here = Path.cwd()
9160
+ if os.environ.get("ORCH_NAME_CHECK", "1") == "0":
9161
+ return None, None
9162
+ for root in active_runs():
9163
+ if Path(root).resolve() == here.resolve():
9164
+ continue
9165
+ got = run_names(root)
9166
+ if got and (got[0] | ({got[1]} if got[1] else set())) & set(names):
9167
+ return re.sub(r"[^\w.-]", "-", here.name) or "run", root
9168
+ return None, None
9169
+
9170
+
8970
9171
  def active_runs():
8971
9172
  """Repos whose event manager is running on this machine right now (each manager signs in under active/)."""
8972
9173
  live = []
@@ -9156,9 +9357,84 @@ def config_save(data):
9156
9357
  os.replace(tmp, p)
9157
9358
 
9158
9359
 
9159
- def config_mode():
9160
- m = str(config_load().get("mode") or "panes").lower()
9161
- return m if m in ORCH_MODES else "panes"
9360
+ # The mode is saved per agent (`modes` in the config, e.g. {"modes": {"pi": "subagent"}}): an agent not listed
9361
+ # runs in panes mode. Subagent mode exists only for Pi today (it needs @tintinweb/pi-subagents), so orch never gives
9362
+ # another agent (Claude Code, Codex, Antigravity, ...) subagent instructions, whatever the config says.
9363
+ # Before 6.23.0 the config had one machine-wide `"mode"`; a saved `"mode": "subagent"` is read as Pi's, and the next
9364
+ # save moves it to `modes.pi`.
9365
+ SUBAGENT_AGENTS = ("pi",)
9366
+ AGENT_RE_KIND = re.compile(r"^[a-z][a-z0-9_-]{0,31}$")
9367
+ AGENT_OVERRIDE = None # set by `--agent <kind>`
9368
+
9369
+
9370
+ def config_modes(conf=None):
9371
+ """{agent: mode} from the config, with the old machine-wide `mode: subagent` read as Pi's."""
9372
+ conf = config_load() if conf is None else conf
9373
+ raw = conf.get("modes") if isinstance(conf.get("modes"), dict) else {}
9374
+ out = {str(k).lower(): str(v).lower() for k, v in raw.items() if str(v).lower() in ORCH_MODES}
9375
+ if str(conf.get("mode") or "").lower() == "subagent":
9376
+ out.setdefault("pi", "subagent")
9377
+ return out
9378
+
9379
+
9380
+ def config_mode(agent="pi"):
9381
+ """The mode saved for this agent; panes when none is saved, or when the agent has no subagent mode."""
9382
+ m = config_modes().get(agent or "", "panes")
9383
+ return m if m == "panes" or agent in SUBAGENT_AGENTS else "panes"
9384
+
9385
+
9386
+ def calling_agent():
9387
+ """Which agent runs this orch command (its kind, as in agents.toml), or None when orch can't tell.
9388
+ `--agent` or ORCH_AGENT win; then AI_AGENT, which the innermost agent sets (Pi: "pi", Claude Code:
9389
+ "claude-code_..."); then the marks agents leave in their shell (PI_CODING_AGENT, CLAUDECODE, CODEX_*, OPENCODE)."""
9390
+ e = os.environ
9391
+ v = (AGENT_OVERRIDE or e.get("ORCH_AGENT") or "").strip().lower()
9392
+ if v:
9393
+ return v
9394
+ names = {"pi": "pi", "claude": "claude", "codex": "codex", "opencode": "opencode", "amp": "amp",
9395
+ "hermes": "hermes", "agy": "agy", "antigravity": "agy", "gemini": "agy"}
9396
+ first = (re.split(r"[^a-z0-9]+", (e.get("AI_AGENT") or "").strip().lower()) or [""])[0]
9397
+ if first:
9398
+ return names.get(first, first if AGENT_RE_KIND.match(first) else None)
9399
+ if e.get("PI_CODING_AGENT") == "true":
9400
+ return "pi"
9401
+ if e.get("CLAUDECODE") == "1":
9402
+ return "claude"
9403
+ if any(k.startswith("CODEX_") for k in e):
9404
+ return "codex"
9405
+ if e.get("OPENCODE"):
9406
+ return "opencode"
9407
+ return None
9408
+
9409
+
9410
+ def agent_flag(args, usage):
9411
+ """Take `--agent <kind>` (or `--agent=<kind>`) out of args and use it as the calling agent; returns it or None."""
9412
+ global AGENT_OVERRIDE
9413
+ for i, a in enumerate(list(args)):
9414
+ if a == "--agent" or a.startswith("--agent="):
9415
+ val = (a.split("=", 1)[1] if "=" in a else (args[i + 1] if len(args) > i + 1 else "")).strip().lower()
9416
+ del args[i:i + (1 if "=" in a else 2)]
9417
+ if not AGENT_RE_KIND.match(val):
9418
+ die(f"--agent needs an agent kind such as pi, claude, codex or agy, got {val!r} — {usage}")
9419
+ AGENT_OVERRIDE = val
9420
+ return val
9421
+ return None
9422
+
9423
+
9424
+ def mode_env():
9425
+ """ORCH_MODE=panes|subagent: a one-command override (e.g. `ORCH_MODE=panes orch lead plan`); None when unset."""
9426
+ v = (os.environ.get("ORCH_MODE") or "").strip().lower()
9427
+ if not v:
9428
+ return None
9429
+ if v not in ORCH_MODES:
9430
+ die(f"ORCH_MODE must be panes or subagent, got {v!r}")
9431
+ return v
9432
+
9433
+
9434
+ def no_subagent_for(agent):
9435
+ return (f"subagent mode is only for Pi today (it uses Pi's pi-subagents); "
9436
+ f"{'this agent (' + agent + ')' if agent else 'orch cannot tell which agent this is, so it'} "
9437
+ f"uses panes mode. In Pi orch finds it by itself; elsewhere add `--agent pi` or set ORCH_AGENT=pi")
9162
9438
 
9163
9439
 
9164
9440
  def run_mode(st):
@@ -9197,17 +9473,48 @@ def _repo_state_path():
9197
9473
  return p if p.exists() else None
9198
9474
 
9199
9475
 
9200
- def current_mode():
9201
- """(mode, where it comes from): this repo's run, else the machine's config, else panes."""
9476
+ def current_mode(agent=...):
9477
+ """(mode, where it comes from) for the agent running orch: a one-command ORCH_MODE, else this repo's run, else
9478
+ the mode saved for this agent, else panes. Only Pi has a subagent mode, so any other agent gets panes even when
9479
+ this repo's last run or the config says subagent (that is Pi's)."""
9480
+ agent = calling_agent() if agent is ... else agent
9481
+ env = mode_env()
9482
+ if env == "subagent" and agent not in SUBAGENT_AGENTS:
9483
+ die("ORCH_MODE=subagent: " + no_subagent_for(agent))
9484
+ if env:
9485
+ return env, "ORCH_MODE"
9486
+ run = None
9202
9487
  with contextlib.suppress(Exception):
9203
9488
  p = _repo_state_path()
9204
9489
  if p:
9205
- return run_mode(json.loads(p.read_text())), "this repo's run"
9206
- if "mode" in config_load():
9207
- return config_mode(), short(user_config_file())
9490
+ run = run_mode(json.loads(p.read_text()))
9491
+ if agent not in SUBAGENT_AGENTS:
9492
+ if run == "panes":
9493
+ return "panes", "this repo's run"
9494
+ if run == "subagent" or "subagent" in config_modes().values():
9495
+ return "panes", f"{agent or 'this agent'}: subagent mode is only for Pi"
9496
+ return "panes", "default"
9497
+ if run:
9498
+ return run, "this repo's run"
9499
+ if agent in config_modes():
9500
+ return config_mode(agent), f"{agent}, in {short(user_config_file())}"
9208
9501
  return "panes", "default"
9209
9502
 
9210
9503
 
9504
+ def plan_orch_mode(old, branch, lead_kind):
9505
+ """The mode a run synced from the plan gets: subagent only when its lead is Pi and Pi's saved mode (or the run
9506
+ this plan already had, on the same branch) is subagent; every other lead runs in panes."""
9507
+ kind = (lead_kind or calling_agent() or "").lower()
9508
+ env = mode_env()
9509
+ if kind not in SUBAGENT_AGENTS:
9510
+ return "panes"
9511
+ if env:
9512
+ return env
9513
+ if old.get("branch") == branch and old.get("orch_mode") in ORCH_MODES:
9514
+ return old["orch_mode"]
9515
+ return config_mode(kind)
9516
+
9517
+
9211
9518
  def mode_flag(args, usage):
9212
9519
  """Take `--mode <panes|subagent>` (or `--mode=...`) out of args; returns the mode or None."""
9213
9520
  for i, a in enumerate(list(args)):
@@ -9376,16 +9683,30 @@ def pi_setup():
9376
9683
  return problems + 1
9377
9684
 
9378
9685
 
9686
+ def mode_target(mode, usage):
9687
+ """Which agent `orch mode` / `orch setup --mode` saves the mode for: `--agent`, else the agent running orch.
9688
+ Subagent mode is Pi's, so `--mode subagent` with no agent named (a plain terminal) is saved for Pi."""
9689
+ agent = AGENT_OVERRIDE or calling_agent()
9690
+ if mode == "subagent":
9691
+ if AGENT_OVERRIDE and agent not in SUBAGENT_AGENTS:
9692
+ die(f"{agent} has no subagent mode: it is only for Pi today (Pi's pi-subagents). {agent} stays in panes "
9693
+ f"mode — {usage}")
9694
+ return agent if agent in SUBAGENT_AGENTS else "pi"
9695
+ return agent if agent in SUBAGENT_AGENTS or AGENT_OVERRIDE else "pi"
9696
+
9697
+
9379
9698
  def cmd_setup(args):
9380
- """orch setup [--mode panes|subagent] -> get this machine ready for a mode (and save it with --mode)."""
9381
- usage = "usage: orch setup [--mode panes|subagent]"
9699
+ """orch setup [--mode panes|subagent] [--agent <kind>] -> get this machine ready for a mode (save it with --mode)."""
9700
+ usage = "usage: orch setup [--mode panes|subagent] [--agent <kind>]"
9382
9701
  args = list(args)
9702
+ agent_flag(args, usage)
9383
9703
  flag = mode_flag(args, usage)
9384
9704
  if args:
9385
9705
  die(usage)
9386
9706
  if flag:
9387
- set_mode(flag, hint=False)
9388
- mode = flag or current_mode()[0]
9707
+ set_mode(flag, hint=False, agent=mode_target(flag, usage))
9708
+ # setup only ever prepares Pi's subagents, so with no --mode it looks at Pi's saved mode too
9709
+ mode = flag or ("subagent" if "subagent" in (current_mode()[0], config_mode("pi")) else "panes")
9389
9710
  if mode == "panes":
9390
9711
  print("mode panes: nothing to set up here. Coders and the reviewer run in herdr panes; `orch team up` opens "
9391
9712
  "them when a run starts.")
@@ -9394,22 +9715,47 @@ def cmd_setup(args):
9394
9715
 
9395
9716
 
9396
9717
  def cmd_mode(args):
9397
- """orch mode -> which mode is active and where it comes from; orch mode panes|subagent -> switch."""
9718
+ """orch mode -> this agent's mode and where it comes from; orch mode panes|subagent [--agent <kind>] -> save it
9719
+ for that agent (subagent: Pi only)."""
9720
+ usage = "usage: orch mode [panes|subagent] [--agent <kind>]"
9721
+ args = list(args)
9722
+ agent_flag(args, usage)
9398
9723
  if not args:
9399
- mode, src = current_mode()
9724
+ agent = calling_agent()
9725
+ mode, src = current_mode(agent)
9400
9726
  print(f"mode: {mode} ({src})")
9727
+ saved = config_modes()
9728
+ others = {k: v for k, v in saved.items() if k != agent and v != "panes"}
9729
+ if others:
9730
+ print("saved per agent: " + ", ".join(f"{k}={v}" for k, v in sorted(others.items()))
9731
+ + " (every other agent: panes)")
9732
+ if "modes" not in config_load() and "pi" in saved:
9733
+ print(f"NOTE {short(user_config_file())} still has the old machine-wide \"mode\": \"subagent\". orch "
9734
+ f"reads it as Pi's only; `orch mode subagent` (or panes) saves it the new way")
9401
9735
  return
9402
9736
  if len(args) != 1 or args[0].lower() not in ORCH_MODES:
9403
- die("usage: orch mode [panes|subagent]")
9404
- set_mode(args[0].lower())
9737
+ die(usage)
9738
+ set_mode(args[0].lower(), agent=mode_target(args[0].lower(), usage))
9405
9739
 
9406
9740
 
9407
- def set_mode(mode, hint=True):
9408
- """Save the machine's mode, and switch this repo's run too when nothing in it is in progress."""
9741
+ def set_mode(mode, hint=True, agent="pi"):
9742
+ """Save the mode for one agent (`modes.<agent>`), and switch this repo's run too when its lead is that agent and
9743
+ nothing in it is in progress. The old machine-wide `mode` key is moved into `modes.pi`."""
9409
9744
  c = config_load()
9410
- c["mode"] = mode
9745
+ modes = config_modes(c)
9746
+ moved = "mode" in c
9747
+ c.pop("mode", None)
9748
+ if mode == "panes":
9749
+ modes.pop(agent, None)
9750
+ else:
9751
+ modes[agent] = mode
9752
+ c["modes"] = modes
9411
9753
  config_save(c)
9412
- print(f"mode: {mode} (saved in {short(user_config_file())})")
9754
+ print(f"mode: {mode} for {agent} (saved in {short(user_config_file())}; "
9755
+ + ("every other agent uses panes)" if mode == "subagent" else
9756
+ "agents with no saved mode use panes)"))
9757
+ if moved:
9758
+ print("MOVED the old machine-wide \"mode\" setting: it now applies to Pi only (\"modes\": {\"pi\": ...})")
9413
9759
  p = None
9414
9760
  with contextlib.suppress(Exception):
9415
9761
  p = _repo_state_path()
@@ -9419,11 +9765,16 @@ def set_mode(mode, hint=True):
9419
9765
  with state_lock():
9420
9766
  st = load()
9421
9767
  busy = [k for k, v in st["tasks"].items() if v["status"] in ACTIVE]
9422
- if run_mode(st) != mode and (driver_alive() or busy):
9768
+ lead_kind = ((st.get("lead") or {}).get("kind") or "").lower()
9769
+ if mode == "subagent" and lead_kind not in SUBAGENT_AGENTS:
9770
+ if run_mode(st) != mode:
9771
+ print(f"this repo's run stays {run_mode(st)}: its lead is {lead_kind or 'not named'}, and "
9772
+ f"subagent mode needs `Lead: lead (pi)` (the next Pi-led plan uses it)")
9773
+ elif run_mode(st) != mode and (driver_alive() or busy):
9423
9774
  print(f"NOT CHANGED this repo's run stays {run_mode(st)}: "
9424
9775
  + (f"{', '.join(busy)} in progress" if busy else "the event manager is running")
9425
9776
  + ". Switch when nothing is in progress.")
9426
- elif run_mode(st) != mode:
9777
+ elif run_mode(st) != mode and (lead_kind == agent or (not lead_kind and agent in SUBAGENT_AGENTS)):
9427
9778
  st["orch_mode"] = mode
9428
9779
  save(st)
9429
9780
  print(f"this repo's run: {mode}")
@@ -9450,6 +9801,302 @@ SUBAGENT_PLAN_NOTE = """SUBAGENT MODE (Pi, one window). This replaces every herd
9450
9801
  """
9451
9802
 
9452
9803
 
9804
+ # ---------------------------------------------------------------- a workspace of several repos (frontend + backend)
9805
+ # A folder (a git repo or not) whose .orchestrate/plan.md has `Repos: frontend, backend` is a workspace. Every
9806
+ # milestone names its repo (`Repo: backend`). `orch sync` there writes one normal plan per repo (in that repo's own
9807
+ # .orchestrate/), so each repo is an ordinary run: its own worktrees (`<repo>-wt/<coder>`), its own feature branch,
9808
+ # its own check, its own PR. One lead drives all of them from the workspace folder; orch sends each command to the
9809
+ # repo its milestone belongs to, or to every repo. A milestone may wait for one of another repo: `backend:M2`.
9810
+ WS_GENERATED = "<!-- written by `orch sync` from the workspace plan {plan}: edit that file, not this one -->"
9811
+ WS_PER_REPO = ("check ", "setup ", "workers ", "reviewer ")
9812
+
9813
+
9814
+ def ws_plan_repos(ws, cfg):
9815
+ """{name: absolute path} from the header `Repos: frontend, backend` (or `Repos: web=apps/web, api=../api`)."""
9816
+ out = {}
9817
+ for item in re.split(r"[,\s]+", " ".join(cfg.get("repos", []))):
9818
+ if not item:
9819
+ continue
9820
+ name, _, rel = item.partition("=")
9821
+ rel = rel or name
9822
+ out[(name if _ else Path(rel).name).lower()] = str((Path(ws) / rel).resolve())
9823
+ return out
9824
+
9825
+
9826
+ def _git_top(d):
9827
+ try:
9828
+ r = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], cwd=str(d), text=True,
9829
+ capture_output=True, timeout=10)
9830
+ except (OSError, subprocess.TimeoutExpired):
9831
+ return None
9832
+ return Path(r.stdout.strip()).parent.resolve() if r.returncode == 0 and r.stdout.strip() else None
9833
+
9834
+
9835
+ def find_workspace(start):
9836
+ """The workspace folder start is in (its .orchestrate/plan.md has `Repos:`), unless start is inside one of its
9837
+ repos or their coder folders: commands there belong to that repo's own run. None when there is no workspace."""
9838
+ p = Path(start).resolve()
9839
+ for d in [p, *p.parents]:
9840
+ plan = d / ".orchestrate" / "plan.md"
9841
+ if not plan.is_file():
9842
+ continue
9843
+ try:
9844
+ cfg, _ = parse_plan(plan.read_text())
9845
+ except OSError:
9846
+ return None
9847
+ if not cfg.get("repos"):
9848
+ return None # the nearest plan is an ordinary run's
9849
+ repos = [Path(r).resolve() for r in ws_plan_repos(d, cfg).values()]
9850
+ top = _git_top(p)
9851
+ if top and top in repos:
9852
+ return None
9853
+ if any(p == r or r in p.parents for r in repos):
9854
+ return None
9855
+ return d
9856
+ return None
9857
+
9858
+
9859
+ def _fields(lines):
9860
+ """Header lines -> [(key or None, [lines])]: a `Key: value` line with its continuation lines, or another line."""
9861
+ out = []
9862
+ for line in lines:
9863
+ fm = FIELD_RE.match(line.strip())
9864
+ if fm and not line.startswith((" ", "\t", "-")):
9865
+ out.append((fm.group(1).strip().lower(), [line]))
9866
+ elif out and out[-1][0] and line.strip() and line.startswith((" ", "\t", "-")):
9867
+ out[-1][1].append(line)
9868
+ else:
9869
+ out.append((None, [line]))
9870
+ return out
9871
+
9872
+
9873
+ def _prefix_agents(value, repo):
9874
+ """`claude-1 (claude: sonnet), codex-1 (codex)` -> `frontend-claude-1 (claude: sonnet), frontend-codex-1 (codex)`."""
9875
+ return re.sub(r"([\w.-]+)(\s*\()", lambda m: (m.group(1) if m.group(1).lower().startswith(repo + "-")
9876
+ else f"{repo}-{m.group(1)}") + m.group(2), value)
9877
+
9878
+
9879
+ def ws_repo_plan(ws, text, repo, task_repo, all_repos):
9880
+ """The plan for one repo of the workspace: the shared header, that repo's check, setup, coders and reviewer, its
9881
+ milestones (a dependency on another repo's milestone written `backend:M2`) and every other section."""
9882
+ lines = text.splitlines()
9883
+ first = next((i for i, l in enumerate(lines) if l.startswith("## ")), len(lines))
9884
+ head = _fields(lines[:first])
9885
+ get = {k: " ".join(x.split(":", 1)[1].strip() if j == 0 else x.strip() for j, x in enumerate(ls)).strip()
9886
+ for k, ls in head if k}
9887
+ out = [WS_GENERATED.format(plan=Path(ws) / ".orchestrate" / "plan.md")]
9888
+ for k, ls in head:
9889
+ if k and (k in ("repos", "workers", "reviewer", "check command", "setup command", "workspace")
9890
+ or (k.startswith(WS_PER_REPO) and k.split(" ", 1)[1] in all_repos)
9891
+ or k.startswith(("workers ", "reviewer "))):
9892
+ continue
9893
+ out += ls
9894
+ while out and not out[-1].strip():
9895
+ out.pop()
9896
+ out.append(f"Workspace: {ws}")
9897
+ chk = get.get(f"check {repo}") or get.get("check command")
9898
+ if chk:
9899
+ out.append(f"Check command: {chk}")
9900
+ out.append(f"Setup command: {get.get(f'setup {repo}') or get.get('setup command') or 'none'}")
9901
+ out.append(f"Workers: {get.get(f'workers {repo}') or _prefix_agents(get.get('workers', ''), repo)}")
9902
+ rev = get.get(f"reviewer {repo}") or get.get("reviewer") or "none"
9903
+ out.append(f"Reviewer: {rev if rev.lower().startswith('none') or get.get(f'reviewer {repo}') else _prefix_agents(rev, repo)}")
9904
+ out.append("")
9905
+ sec, keep = [], True
9906
+
9907
+ def flush():
9908
+ if keep:
9909
+ out.extend(sec)
9910
+ for line in lines[first:]:
9911
+ if line.startswith("## "):
9912
+ flush()
9913
+ sec = [line]
9914
+ m = HEAD_RE.match(line)
9915
+ keep = not m or task_repo.get(m.group(2)) == repo
9916
+ continue
9917
+ sec.append(line)
9918
+ flush()
9919
+ # a dependency on a milestone of another repo: `M2` -> `backend:M2` (only inside `Depends on:`)
9920
+ res, in_dep = [], False
9921
+ for line in out:
9922
+ fm = FIELD_RE.match(line.strip())
9923
+ if fm and not line.startswith((" ", "\t", "-")):
9924
+ in_dep = fm.group(1).strip().lower() == "depends on"
9925
+ elif line.startswith("## "):
9926
+ in_dep = False
9927
+ if in_dep:
9928
+ line = re.sub(r"(?<![\w:])(M\d+)\b", lambda m: m.group(1) if task_repo.get(m.group(1), repo) == repo
9929
+ else f"{task_repo[m.group(1)]}:{m.group(1)}", line)
9930
+ res.append(line)
9931
+ return "\n".join(res).rstrip() + "\n"
9932
+
9933
+
9934
+ def ws_runs(ws):
9935
+ """[(name, path)] of the repos that have a run of this workspace (their plan says `Workspace: <ws>`)."""
9936
+ out = []
9937
+ for name, path in workspace_repos(ws).items():
9938
+ plan = Path(path) / ".orchestrate" / "plan.md"
9939
+ try:
9940
+ if f"Workspace: {ws}" in plan.read_text():
9941
+ out.append((name, path))
9942
+ except OSError:
9943
+ pass
9944
+ return out
9945
+
9946
+
9947
+ def ws_sync(ws):
9948
+ plan = Path(ws) / ".orchestrate" / "plan.md"
9949
+ text = plan.read_text()
9950
+ cfg, tasks = parse_plan(text)
9951
+ repos = ws_plan_repos(ws, cfg)
9952
+ errors = []
9953
+ for name, path in repos.items():
9954
+ if _git_top(path) != Path(path).resolve():
9955
+ errors.append(f"repo {name}: {path} is not the top folder of a git repo")
9956
+ task_repo = {}
9957
+ for t in tasks:
9958
+ r = field(t, "repo").split()[0].lower() if field(t, "repo") else None
9959
+ if not r:
9960
+ if t["enabled"]:
9961
+ errors.append(f"{t['id']} needs `Repo: <one of {', '.join(repos)}>`: in a workspace every milestone "
9962
+ f"belongs to one repo")
9963
+ continue
9964
+ if r not in repos:
9965
+ errors.append(f"{t['id']} has `Repo: {r}`, but `Repos:` names only {', '.join(repos)}")
9966
+ continue
9967
+ task_repo[t["id"]] = r
9968
+ ids = [t["id"] for t in tasks]
9969
+ for d in sorted({i for i in ids if ids.count(i) > 1}):
9970
+ errors.append(f"duplicate task id {d}: milestone ids are counted across the whole workspace")
9971
+ deps = {t["id"]: split_ids(re.sub(r"\([^)]*\)", "", field(t, "depends on", "none"))) for t in tasks}
9972
+ color = {}
9973
+
9974
+ def dfs(n, stack):
9975
+ color[n] = 1
9976
+ for d in deps.get(n, []):
9977
+ if d not in deps:
9978
+ errors.append(f"{n} depends on unknown task {d}")
9979
+ elif color.get(d) == 1:
9980
+ errors.append("dependency cycle across repos: " + " -> ".join(stack + [n, d]))
9981
+ elif not color.get(d):
9982
+ dfs(d, stack + [n])
9983
+ color[n] = 2
9984
+ for n in deps:
9985
+ if not color.get(n):
9986
+ dfs(n, [])
9987
+ used = sorted(set(task_repo.values()), key=list(repos).index)
9988
+ for name in used:
9989
+ p = Path(repos[name]) / ".orchestrate" / "plan.md"
9990
+ if p.exists() and f"Workspace: {ws}" not in p.read_text():
9991
+ try:
9992
+ ost = json.loads((p.parent / "state.json").read_text())
9993
+ left = [k for k, v in ost.get("tasks", {}).items() if v.get("status") not in ("merged", "skipped")]
9994
+ except (OSError, ValueError):
9995
+ left = []
9996
+ if left:
9997
+ errors.append(f"repo {name} has its own run going ({', '.join(left[:4])} not landed): finish it there "
9998
+ f"first (`orch status` in {repos[name]})")
9999
+ if errors:
10000
+ for e in errors:
10001
+ print("ERROR:", e)
10002
+ sys.exit(1)
10003
+ (Path(ws) / ".orchestrate" / "workspace.json").write_text(json.dumps(
10004
+ {"repos": repos, "tasks": task_repo, "plan": str(plan)}, indent=1) + "\n")
10005
+ for name in repos:
10006
+ if name not in used:
10007
+ print(f"WARN: repo {name} has no milestone in this plan, so it gets no run")
10008
+ code = 0
10009
+ for name in used:
10010
+ d = Path(repos[name]) / ".orchestrate"
10011
+ d.mkdir(exist_ok=True)
10012
+ p = d / "plan.md"
10013
+ if p.exists() and f"Workspace: {ws}" not in p.read_text():
10014
+ shutil.copyfile(p, d / "plan.before-workspace.md")
10015
+ print(f"SAVED {name}'s own old plan as {d / 'plan.before-workspace.md'}")
10016
+ p.write_text(ws_repo_plan(str(ws), text, name, task_repo, list(repos)))
10017
+ print(f"== {name} ({repos[name]}): " + ", ".join(k for k, v in task_repo.items() if v == name))
10018
+ sys.stdout.flush()
10019
+ r = subprocess.run([sys.executable, os.path.abspath(__file__), "sync"], cwd=repos[name])
10020
+ code = max(code, r.returncode)
10021
+ sys.exit(code)
10022
+
10023
+
10024
+ WS_TASK_FREE = {"autopilot", "events", "status", "start", "finish", "resume", "stop", "team", "report", "story",
10025
+ "manual", "doctor", "cleanup", "ready", "guard", "plan", "mode", "check"}
10026
+
10027
+
10028
+ def workspace_main(ws, cmd, args):
10029
+ """Carry out one orch command in a workspace: in the repo its milestone belongs to, or in every repo."""
10030
+ me = [sys.executable, os.path.abspath(__file__)]
10031
+ if cmd == "sync":
10032
+ ws_sync(ws)
10033
+ runs = ws_runs(ws)
10034
+ if not runs:
10035
+ die(f"{ws} is a workspace of several repos (its plan has `Repos:`), and no repo has a run of it yet — "
10036
+ f"run `orch sync` here")
10037
+ info = json.loads((Path(ws) / ".orchestrate" / "workspace.json").read_text())
10038
+ repo_of = info.get("tasks") or {}
10039
+ paths = dict(runs)
10040
+
10041
+ def one(name, a, header=True):
10042
+ if header:
10043
+ print(f"== {name} ({paths[name]})")
10044
+ sys.stdout.flush()
10045
+ return subprocess.run(me + [cmd, *a], cwd=paths[name]).returncode
10046
+ if cmd in ("view", "board"):
10047
+ die(f"`orch {cmd}` shows one repo's run: run it inside one of the repos ({', '.join(paths.values())})")
10048
+ if cmd == "sub":
10049
+ die("subagent mode works in one folder, one milestone at a time: a workspace of several repos runs in panes "
10050
+ f"mode. For subagent mode, plan and run inside one repo ({', '.join(paths.values())})")
10051
+ mids = [a for a in args if re.fullmatch(r"M\d+", a)]
10052
+ if mids:
10053
+ unknown = [m for m in mids if m not in repo_of]
10054
+ if unknown:
10055
+ die(f"{', '.join(unknown)}: no such milestone in the workspace plan (`orch status` lists them)")
10056
+ groups = {}
10057
+ for m in mids:
10058
+ groups.setdefault(repo_of[m], []).append(m)
10059
+ code = 0
10060
+ for name, ms in groups.items():
10061
+ a = [x for x in args if not re.fullmatch(r"M\d+", x) or x in ms]
10062
+ code = max(code, one(name, a, header=len(groups) > 1))
10063
+ sys.exit(code)
10064
+ if cmd == "bench" and args:
10065
+ for name, path in runs:
10066
+ got = run_names(path)
10067
+ if got and args[0] in got[0]:
10068
+ sys.exit(one(name, args, header=False))
10069
+ die(f"no repo of the workspace has a coder named {args[0]}")
10070
+ if cmd == "autopilot": # one event manager per repo, side by side
10071
+ procs = []
10072
+ for name, path in runs:
10073
+ print(f"== {name}: event manager started ({path})")
10074
+ sys.stdout.flush()
10075
+ procs.append(subprocess.Popen(me + [cmd, *args], cwd=path))
10076
+ sys.exit(max(p.wait() for p in procs))
10077
+ code = 0
10078
+ for name, _ in runs:
10079
+ code = max(code, one(name, args))
10080
+ if cmd == "events":
10081
+ left = {}
10082
+ for name, path in runs:
10083
+ try:
10084
+ st = json.loads((Path(path) / ".orchestrate" / "state.json").read_text())
10085
+ left[name] = [k for k, v in st["tasks"].items() if v["status"] not in ("merged", "skipped")]
10086
+ except (OSError, ValueError, KeyError):
10087
+ left[name] = ["?"]
10088
+ done = [n for n, l in left.items() if not l]
10089
+ if done and len(done) < len(left):
10090
+ print(f"\nWORKSPACE: {', '.join(done)} has landed every milestone; still going: "
10091
+ + ", ".join(f"{n} ({', '.join(l)})" for n, l in left.items() if l)
10092
+ + ". An ALL_DONE above is for that repo only: write the summaries when every repo is done.")
10093
+ elif done:
10094
+ print(f"\nWORKSPACE: every repo has landed all its milestones. Each repo gets its own PR: finish the "
10095
+ f"summary in each repo's .orchestrate/summary.md ({', '.join(paths.values())}), then `orch finish` "
10096
+ f"here runs it in every repo.")
10097
+ sys.exit(code)
10098
+
10099
+
9453
10100
  def subagent_ready_or_die(st):
9454
10101
  if run_mode(st) != "subagent":
9455
10102
  die("this run is in panes mode — `orch sub` is for subagent mode (`orch mode subagent`); "
@@ -9467,20 +10114,22 @@ def cmd_check(args):
9467
10114
  st = load()
9468
10115
  if args:
9469
10116
  task(st, args[0])
9470
- if not st.get("check"):
10117
+ tid = args[0] if args else None
10118
+ cmd = check_for(st, tid)
10119
+ if not cmd:
9471
10120
  print("CHECK NONE: the plan has no `Check command`")
9472
10121
  return
9473
- ok, tail, secs = run_check(st, ROOT)
10122
+ ok, tail, secs = run_check(st, ROOT, tid)
9474
10123
  if not driver_alive():
9475
10124
  with state_lock():
9476
10125
  st = load()
9477
- note_green(st, ROOT, ok) # `orch finish` reuses a pass on exactly these files
10126
+ note_green(st, ROOT, ok, tid) # `orch finish` reuses a pass on exactly these files
9478
10127
  save(st)
9479
10128
  label = f" {args[0]}" if args else ""
9480
10129
  if ok:
9481
- print(f"CHECK PASS{label} ({secs}s): {st['check']}")
10130
+ print(f"CHECK PASS{label} ({secs}s): {cmd}")
9482
10131
  return
9483
- print(f"CHECK FAIL{label} ({secs}s): {st['check']}\n" + "\n".join(tail.splitlines()[-30:]))
10132
+ print(f"CHECK FAIL{label} ({secs}s): {cmd}\n" + "\n".join(tail.splitlines()[-30:]))
9484
10133
  sys.exit(1)
9485
10134
 
9486
10135
 
@@ -9686,6 +10335,9 @@ if __name__ == "__main__":
9686
10335
  if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS:
9687
10336
  print(USAGE)
9688
10337
  sys.exit(0 if len(sys.argv) < 2 or sys.argv[1] in ("--help", "-h", "help") else 2)
10338
+ _ws = find_workspace(Path.cwd())
10339
+ if _ws is not None: # a workspace of several repos: each repo is its own run
10340
+ workspace_main(_ws, sys.argv[1], sys.argv[2:])
9689
10341
  ROOT = main_root()
9690
10342
  ORCH = ROOT / ".orchestrate"
9691
10343
  ORCH.mkdir(exist_ok=True)