herdr-orchestra 6.9.0 → 6.11.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
@@ -168,7 +168,8 @@ def state_lock():
168
168
 
169
169
  # usable while autopilot drives: reads, and the lead's requests (the event manager carries them out)
170
170
  LEASE_FREE = {"status", "ready", "pick", "report", "approve", "autopilot", "events", "dispatch", "answer", "defer",
171
- "fix", "team", "resume", "bench", "stop", "doctor", "plan", "story", "check", "free", "manual"}
171
+ "fix", "team", "resume", "bench", "stop", "doctor", "plan", "story", "check", "free", "manual", "view",
172
+ "board"}
172
173
  _LEASE = None
173
174
 
174
175
 
@@ -993,6 +994,192 @@ def ensure_excluded():
993
994
  exclude.write_text("\n".join(lines) + "\n")
994
995
 
995
996
 
997
+ # ---------------------------------------------------------------- main guard: no agent ever pushes to main
998
+ GUARD_MARK = "herdr-orchestra main guard"
999
+ GUARD_VERSION = 1
1000
+ GUARD_ALWAYS = ("main", "master")
1001
+ GUARD_RULE = ("No agent ever pushes to main (or master, or the repo's default branch), in any situation, even when "
1002
+ "the developer asks: work stays on the run's branch, and a person merges the PR by hand.")
1003
+ GUARD_HOOK = r"""#!/bin/sh
1004
+ # {mark} v{version}. Written by `orch guard` (orch start writes it too).
1005
+ # Refuses any push that would change main, master, the remote's default branch or a branch in
1006
+ # `git config orch.protected`: agents work on a branch and open a PR, and a person merges it.
1007
+ remote="$1"
1008
+ prot="main master"
1009
+ d=$(git symbolic-ref --short "refs/remotes/$remote/HEAD" 2>/dev/null) && prot="$prot ${{d#*/}}"
1010
+ prot="$prot $(git config --get-all orch.protected 2>/dev/null | tr '\n' ' ')"
1011
+ input=$(cat)
1012
+ blocked=""
1013
+ while read -r lref lsha rref rsha; do
1014
+ b=${{rref#refs/heads/}}
1015
+ [ -n "$b" ] && [ "$b" != "$rref" ] || continue
1016
+ for p in $prot; do [ "$b" = "$p" ] && blocked="$blocked $b"; done
1017
+ done <<EOF
1018
+ $input
1019
+ EOF
1020
+ if [ -n "$blocked" ]; then
1021
+ echo "orch guard: REFUSED push to$blocked on $remote." >&2
1022
+ echo "orch guard: no agent pushes to main, even when asked. Push the run's branch and open a PR;" >&2
1023
+ echo "orch guard: a person merges it on GitHub (or with \`orch finish\`, which pushes the branch and opens the PR)." >&2
1024
+ exit 1
1025
+ fi
1026
+ here=$(dirname "$0")
1027
+ if [ -x "$here/pre-push.orch-orig" ]; then
1028
+ printf '%s\n' "$input" | "$here/pre-push.orch-orig" "$@"
1029
+ exit $?
1030
+ fi
1031
+ exit 0
1032
+ """
1033
+
1034
+
1035
+ def guard_root():
1036
+ """The repo the guard is for: the run's repo, or (for commands that run outside a run) the one we are in."""
1037
+ if ROOT:
1038
+ return ROOT
1039
+ r = git("rev-parse", "--path-format=absolute", "--git-common-dir", check=False)
1040
+ return Path(r.stdout.strip()).parent if r.returncode == 0 else None
1041
+
1042
+
1043
+ def protected_branches():
1044
+ """Branches no agent may push to: main, master, origin's default branch, and any in `git config orch.protected`
1045
+ (the same list the pre-push guard reads)."""
1046
+ names = set(GUARD_ALWAYS)
1047
+ r = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=ROOT, check=False)
1048
+ if r.returncode == 0 and "/" in r.stdout.strip():
1049
+ names.add(r.stdout.strip().split("/", 1)[1])
1050
+ names |= set(git("config", "--get-all", "orch.protected", cwd=ROOT, check=False).stdout.split())
1051
+ return names
1052
+
1053
+
1054
+ def refuse_protected(branch, what):
1055
+ """Stop with the rule when `branch` is one nobody's agent may push to."""
1056
+ if branch in protected_branches():
1057
+ die(f"{what}: {branch} is a protected branch. {GUARD_RULE} Use `Branch: feature/<slug>` (or fix/<slug>).")
1058
+
1059
+
1060
+ def guard_hook_path():
1061
+ hooks = Path(git("rev-parse", "--path-format=absolute", "--git-path", "hooks", cwd=guard_root()).stdout.strip())
1062
+ return hooks / "pre-push"
1063
+
1064
+
1065
+ def guard_state():
1066
+ """(state, hook path, note): state is `on`, `old` (an older orch wrote it), `off` or `blocked` (the repo keeps
1067
+ its hooks inside the project, e.g. husky via core.hooksPath: orch doesn't write into the project's files)."""
1068
+ hook = guard_hook_path()
1069
+ root = guard_root()
1070
+ try:
1071
+ inside = hook.parent.resolve().is_relative_to(root.resolve()) and not hook.parent.resolve().is_relative_to(
1072
+ Path(git("rev-parse", "--path-format=absolute", "--git-common-dir", cwd=root).stdout.strip()).resolve())
1073
+ except (OSError, ValueError):
1074
+ inside = False
1075
+ text = hook.read_text(errors="replace") if hook.is_file() else ""
1076
+ if GUARD_MARK in text:
1077
+ m = re.search(rf"{re.escape(GUARD_MARK)} v(\d+)", text)
1078
+ ok = m and int(m.group(1)) >= GUARD_VERSION and os.access(hook, os.X_OK)
1079
+ return ("on" if ok else "old"), hook, ""
1080
+ if inside:
1081
+ return "blocked", hook, (f"this repo keeps its git hooks in {hook.parent} (core.hooksPath), inside the "
1082
+ f"project, so orch does not write there")
1083
+ return "off", hook, ("another pre-push hook is there; orch keeps it and runs it after its own check"
1084
+ if text else "")
1085
+
1086
+
1087
+ def guard_install():
1088
+ """Write the pre-push guard into the repo's hooks folder (shared by every worktree). Keeps a pre-push hook that
1089
+ was already there: it moves to pre-push.orch-orig and runs after orch's check. Returns (state, line)."""
1090
+ state, hook, note = guard_state()
1091
+ if state == "on":
1092
+ return state, f"GUARD on: {short(hook)} refuses pushes to {', '.join(sorted(protected_branches()))}"
1093
+ if state == "blocked":
1094
+ return state, f"WARN GUARD not installed: {note}. Save the output of `orch guard --print` as the pre-push hook there yourself."
1095
+ hook.parent.mkdir(parents=True, exist_ok=True)
1096
+ if state == "off" and hook.exists():
1097
+ os.replace(hook, hook.with_name("pre-push.orch-orig"))
1098
+ hook.write_text(GUARD_HOOK.format(mark=GUARD_MARK, version=GUARD_VERSION))
1099
+ hook.chmod(0o755)
1100
+ kept = " (your own pre-push hook still runs after it)" if hook.with_name("pre-push.orch-orig").exists() else ""
1101
+ return "on", (f"GUARD {'updated' if state == 'old' else 'installed'}: {short(hook)} refuses pushes to "
1102
+ f"{', '.join(sorted(protected_branches()))}{kept}")
1103
+
1104
+
1105
+ def guard_ensure(say_changes=True):
1106
+ """Install or refresh the guard (never fails the caller). Prints when it could not be installed, and when it
1107
+ installed or updated it (unless say_changes is False)."""
1108
+ if not guard_root():
1109
+ return
1110
+ with contextlib.suppress(Exception, SystemExit):
1111
+ before = guard_state()[0]
1112
+ state, line = guard_install()
1113
+ if state != "on" or (say_changes and before != "on"):
1114
+ print(line)
1115
+
1116
+
1117
+ def github_protection(branch):
1118
+ """'protected', 'open' or None (unknown: no gh, not GitHub, no network) for `branch` on origin, via gh."""
1119
+ if os.environ.get("ORCH_GUARD_GITHUB", "1") == "0" or not shutil.which("gh"):
1120
+ return None
1121
+ url = git("remote", "get-url", "origin", cwd=ROOT, check=False).stdout.strip()
1122
+ m = re.search(r"github\.com[:/]([^/]+)/([^/]+?)(?:\.git)?/?$", url)
1123
+ if not m:
1124
+ return None
1125
+ try:
1126
+ r = subprocess.run(["gh", "api", f"repos/{m[1]}/{m[2]}/branches/{branch}", "--jq", ".protected"],
1127
+ cwd=ROOT, text=True, capture_output=True, timeout=15)
1128
+ if r.returncode == 0 and r.stdout.strip() == "true":
1129
+ return "protected"
1130
+ r2 = subprocess.run(["gh", "api", f"repos/{m[1]}/{m[2]}/rules/branches/{branch}", "--jq", "length"],
1131
+ cwd=ROOT, text=True, capture_output=True, timeout=15)
1132
+ except (OSError, subprocess.TimeoutExpired):
1133
+ return None
1134
+ if r2.returncode == 0 and r2.stdout.strip().isdigit():
1135
+ return "protected" if int(r2.stdout.strip()) > 0 else "open"
1136
+ return "open" if r.returncode == 0 else None
1137
+
1138
+
1139
+ def guard_report():
1140
+ """Lines for `orch guard status` and `orch doctor`: (ok, text) pairs."""
1141
+ state, hook, note = guard_state()
1142
+ prot = ", ".join(sorted(protected_branches()))
1143
+ out = [(state == "on", {"on": f"pre-push guard is on ({short(hook)}): pushes to {prot} are refused",
1144
+ "old": f"pre-push guard is from an older orch ({short(hook)}): run `orch guard` to update it",
1145
+ "off": f"pre-push guard is missing ({short(hook)}): run `orch guard` (orch start also "
1146
+ f"installs it)" + (f"; {note}" if note else ""),
1147
+ "blocked": f"pre-push guard can't be installed: {note}. Save the output of "
1148
+ f"`orch guard --print` as the pre-push hook there yourself"}[state])]
1149
+ for b in sorted(protected_branches()):
1150
+ if not branch_exists(b):
1151
+ continue
1152
+ gh = github_protection(b)
1153
+ if gh == "open":
1154
+ out.append((False, f"GitHub does not protect {b}: a push that skips git hooks (--no-verify) would still "
1155
+ f"land. Turn on Settings > Rules > Rulesets > New branch ruleset > target {b} > "
1156
+ f"\"Require a pull request before merging\" and \"Block force pushes\""))
1157
+ elif gh == "protected":
1158
+ out.append((True, f"GitHub protects {b}: changes reach it only through a PR"))
1159
+ return out
1160
+
1161
+
1162
+ def cmd_guard(args):
1163
+ """orch guard [status | --print] -> install the pre-push guard that refuses pushes to main (status: report only;
1164
+ --print: the hook script, to add to a hooks folder orch can't write)."""
1165
+ sub = args[0] if args else ""
1166
+ if sub == "--print":
1167
+ print(GUARD_HOOK.format(mark=GUARD_MARK, version=GUARD_VERSION), end="")
1168
+ return
1169
+ if sub not in ("", "status"):
1170
+ die("usage: orch guard [status | --print]")
1171
+ if not guard_root():
1172
+ die("not inside a git repository: run `orch guard` in the project's folder")
1173
+ print(GUARD_RULE)
1174
+ if sub == "":
1175
+ print(guard_install()[1])
1176
+ bad = 0
1177
+ for ok, m in guard_report():
1178
+ print(f" {'ok ' if ok else 'BAD'} {m}")
1179
+ bad += not ok
1180
+ sys.exit(1 if bad else 0)
1181
+
1182
+
996
1183
  def is_dirty(path):
997
1184
  return bool(git("status", "--porcelain", cwd=path).stdout.strip())
998
1185
 
@@ -1098,6 +1285,9 @@ def cmd_sync(args):
1098
1285
  f"(orch no longer makes per-milestone branches either way)")
1099
1286
  if git("check-ref-format", "--branch", branch, cwd=ROOT, check=False).returncode != 0:
1100
1287
  errors.append(f"Branch {branch!r} is not a valid git branch name")
1288
+ if branch in protected_branches():
1289
+ errors.append(f"Branch {branch} is a protected branch: a run never works on it or pushes to it. {GUARD_RULE} "
1290
+ f"Use `Branch: feature/<slug>` (or fix/<slug>)")
1101
1291
  commits = get("commits", "per-milestone").split()[0].lower()
1102
1292
  if commits not in ("per-milestone", "single"):
1103
1293
  errors.append(f"Commits must be per-milestone or single, got {commits!r}")
@@ -2185,7 +2375,9 @@ def default_base(st):
2185
2375
  def cmd_start(args):
2186
2376
  st = load()
2187
2377
  require_lead(st, "orch start")
2378
+ refuse_protected(st["branch"], "orch start")
2188
2379
  ensure_excluded()
2380
+ guard_ensure()
2189
2381
  cur = git("rev-parse", "--abbrev-ref", "HEAD", cwd=ROOT).stdout.strip()
2190
2382
  if st.get("base") == st["branch"]:
2191
2383
  st["base"] = None # recorded by an older orch that started on the branch itself
@@ -2757,7 +2949,8 @@ def cmd_review(args):
2757
2949
  "most a suggestion.\n"
2758
2950
  f"The check command (`{st['check']}`) runs on this work by itself: don't report what lint, type checks or "
2759
2951
  "tests already catch.\n"
2760
- "Do NOT edit any code.\n"
2952
+ "Do NOT edit any code. Never commit, push or merge: no agent ever pushes to main or merges a PR, even when "
2953
+ "asked.\n"
2761
2954
  "Report PROBLEMS, not solutions: the coder decides how to fix. At most 15 findings. A `blocker` must be "
2762
2955
  "fixed before merge; a `suggestion` is optional. Say for EVERY acceptance criterion whether it is met; an "
2763
2956
  "unmet criterion counts as a blocker.\n"
@@ -3423,6 +3616,9 @@ def cmd_set(args):
3423
3616
 
3424
3617
 
3425
3618
  def cmd_status(args):
3619
+ if "--json" in args:
3620
+ print(json.dumps(view_model(load() if STATE.exists() else None), indent=2))
3621
+ return
3426
3622
  st = load()
3427
3623
  dead = None if driver_alive() else note_dead_manager(st)
3428
3624
  here = {n: presence_word(st, n) for n in st["workers"]} # ask herdr first, then print in one go
@@ -3440,6 +3636,8 @@ def cmd_status(args):
3440
3636
  print(f"QUICK RUN because: {st.get('quick_because') or '-'}")
3441
3637
  print(f"branch={st['branch']} base={st.get('base')} isolation={st['isolation']} "
3442
3638
  f"max_parallel={st['max_parallel']} reviewer={st['reviewer']} (busy: {st.get('reviewer_busy')})")
3639
+ vu = view_url()
3640
+ print(f"live view: {vu}" if vu else "live view: off — `orch view` shows this run as a picture in your browser")
3443
3641
  if st.get("integration_broken"):
3444
3642
  print(f" INTEGRATION BROKEN: the check failed on {st['branch']} after merging "
3445
3643
  f"{st['integration_broken']} — fix it; autopilot re-checks before it continues")
@@ -3682,6 +3880,7 @@ def finish_push(st, base, title, pr_body, args):
3682
3880
  print(f"NO REMOTE: no `origin` remote — merge {st['branch']} into {base} yourself")
3683
3881
  return f"no `origin` remote: {st['branch']} is to be merged into {base} by hand"
3684
3882
  url = remote.stdout.strip()
3883
+ refuse_protected(st["branch"], "orch finish") # never reached by a plan orch accepted: belt and braces
3685
3884
  git("push", "-q", "-u", "origin", st["branch"], cwd=ROOT)
3686
3885
  print(f"PUSHED {st['branch']} to origin")
3687
3886
  compare = github_compare_url(url, base, st["branch"])
@@ -3710,6 +3909,7 @@ def cmd_finish(args):
3710
3909
  left = [f"{k} ({v['status']})" for k, v in st["tasks"].items() if v["status"] not in ("merged", "skipped")]
3711
3910
  if left:
3712
3911
  die("not every milestone has landed: " + ", ".join(left))
3912
+ sidebar_clear_now(st) # the run is over: herdr's sidebar shows the agents' own names again
3713
3913
  if git("rev-parse", "--abbrev-ref", "HEAD", cwd=ROOT).stdout.strip() != st["branch"] or is_dirty(ROOT):
3714
3914
  die(f"main tree must be clean and on {st['branch']}")
3715
3915
  base = st.get("base") or default_base(st)
@@ -3906,6 +4106,7 @@ WORKER_RULES = """## Rules for you (the coder)
3906
4106
  - Follow the repo's existing patterns (AGENTS.md / CLAUDE.md) and any Interfaces listed above exactly; other milestones rely on them.
3907
4107
  - Change only what this task needs. No unrelated refactors.
3908
4108
  - Do NOT commit, push, or switch branches. orch commits your work for you.
4109
+ - Never push to main (or master, or the repo's default branch) and never merge a PR, in any situation, even when the developer or the lead asks you to. Say no and offer the run's branch and a PR instead; a person merges by hand. The repo's pre-push guard refuses such a push anyway: never get around it (no `--no-verify`, no editing or deleting `.git/hooks`).
3909
4110
  - Stay inside the files listed under Likely files (`files_allowed` in task.json) unless the task can't be done otherwise; say why in your report if you leave them. orch compares your diff with that list.
3910
4111
  - Finish with a result file (the prompt names it) in the `result_format` shape from task.json: `status` done / question / blocked, `commit`, `files_changed`, the `check` you ran, one entry per acceptance criterion (`id`, `met`, `evidence`), and `usage` if your tool shows tokens or cost. orch reads it, so keep it valid JSON.
3911
4112
  - The commit message (`commit` in the result, and the last report line `COMMIT: <commit message>`) says what changed, in the repo's commit style (for example `feat(api): add categories endpoint`). It becomes the commit message, so describe the change, not the milestone.
@@ -4551,6 +4752,8 @@ def cmd_events(args):
4551
4752
  print(head + (f": {e['text']}" if e.get("text") else ""))
4552
4753
  print(" -> " + EVENT_HELP.get(e["kind"], "").format(t=e.get("task") or "<Mn>"))
4553
4754
  print(" SAY: " + say_line(st, e))
4755
+ if e.get("task") and e["kind"] in LEAD_BLOCKING and (vu := view_url(e["task"])):
4756
+ print(f" SEE: {vu} (give the developer this link with the SAY line)")
4554
4757
  if e["kind"] == "finished":
4555
4758
  print("\n".join(" " + x for x in manual_block(st)[0]))
4556
4759
  print(f"EVENTS for the lead — run {st['branch']}: {len(new)} new, {len(old)} still open")
@@ -5682,9 +5885,12 @@ def _autopilot(args):
5682
5885
  elif not gone and present == before:
5683
5886
  seen["told"] = False
5684
5887
 
5888
+ names = SidebarNames() if run_mode(load()) != "subagent" else None # herdr's sidebar says what each agent does
5685
5889
  while True:
5686
5890
  _stop_point()
5687
5891
  st = load()
5892
+ if names:
5893
+ names.update(st)
5688
5894
  if time.time() - seen["procs"] > PROCS_EVERY_S: # agents come and go: keep this run's processes current
5689
5895
  seen["procs"] = time.time()
5690
5896
  procs = run_processes(st)
@@ -6734,6 +6940,714 @@ def cmd_resume(args):
6734
6940
  print("The lead is woken with `orch events` when something needs it.")
6735
6941
 
6736
6942
 
6943
+ # ---------------------------------------------------------------- views: run summary, `orch view`, `orch board`
6944
+ # Both views (and anything else) read one small, stable summary of the run: view_model(). It is built from state.json
6945
+ # and events.jsonl only, never asks herdr, never takes the state lock and never writes, so a view can't slow or break
6946
+ # a run. `orch status --json` prints it; `orch view` serves it to a browser page; `orch board` draws it as text.
6947
+ VIEW_SCHEMA = 1
6948
+ VIEW_GROUPS = {"pending": "waiting", "coding": "building", "needs-fix": "building", "conflict": "building",
6949
+ "verifying": "checking", "awaiting-review": "review", "reviewing": "review", "reviewed": "review",
6950
+ "committed": "landing", "held": "needs_you", "paused": "needs_you", "needs-answer": "needs_you",
6951
+ "failed": "needs_you", "merged": "landed", "skipped": "skipped"}
6952
+ VIEW_WORDS = {"pending": "waiting", "coding": "building", "needs-fix": "fix round", "conflict": "fixing a conflict",
6953
+ "verifying": "checks running", "awaiting-review": "waiting for review", "reviewing": "in review",
6954
+ "reviewed": "reviewed", "committed": "landing", "held": "waits for your OK", "paused": "paused",
6955
+ "needs-answer": "needs your answer", "failed": "failed", "merged": "landed", "skipped": "skipped"}
6956
+ VIEW_PORT = int(os.environ.get("ORCH_VIEW_PORT", "47231"))
6957
+
6958
+
6959
+ def _usage_sum(rows):
6960
+ tok = cost = 0
6961
+ known = False
6962
+ for u in rows:
6963
+ if not isinstance(u, dict):
6964
+ continue
6965
+ known = True
6966
+ tok += int(u.get("input_tokens") or 0) + int(u.get("output_tokens") or 0)
6967
+ cost += float(u.get("cost_usd") or 0)
6968
+ return {"tokens": tok, "cost_usd": round(cost, 2)} if known else None
6969
+
6970
+
6971
+ def view_events(limit=None):
6972
+ """events.jsonl as a list (oldest first); the last `limit` lines when given. Bad lines are skipped."""
6973
+ p = ORCH / "events.jsonl"
6974
+ try:
6975
+ lines = p.read_text().splitlines()
6976
+ except OSError:
6977
+ return []
6978
+ out = []
6979
+ for ln in (lines[-limit:] if limit else lines):
6980
+ with contextlib.suppress(ValueError):
6981
+ e = json.loads(ln)
6982
+ if isinstance(e, dict) and e.get("task"):
6983
+ out.append({k: e.get(k) for k in ("ts", "task", "from", "to", "why", "agent", "attempt")})
6984
+ return out
6985
+
6986
+
6987
+ def view_model(st=None, recent=40):
6988
+ """The run in one stable shape ("view": 1). Adding fields is fine; renaming one needs "view": 2."""
6989
+ if st is None:
6990
+ try:
6991
+ st = json.loads(STATE.read_text())
6992
+ except (OSError, ValueError):
6993
+ return {"view": VIEW_SCHEMA, "empty": True, "repo": ROOT.name,
6994
+ "text": "No run in this repo yet: the lead writes the plan, then `orch sync` / `orch start`."}
6995
+ tasks, t_now = st.get("tasks", {}), now()
6996
+ ms, by_model = [], {}
6997
+ for tid in st.get("order", []):
6998
+ t = tasks.get(tid) or {}
6999
+ w = t.get("wait") or {}
7000
+ atts = [a for a in t.get("attempts", []) if isinstance(a, dict)]
7001
+ cur = max(0, t_now - w.get("started", w.get("since", t_now))) if w and t.get("status") in ACTIVE else 0
7002
+ for a in atts:
7003
+ if a.get("usage") and a.get("model"):
7004
+ by_model.setdefault(a["model"], []).append(a["usage"])
7005
+ open_ev = [e for e in st.get("lead_events", []) if e.get("task") == tid and e["kind"] in LEAD_BLOCKING
7006
+ and event_open(st, e)]
7007
+ ms.append({
7008
+ "id": tid, "title": t.get("title", tid), "plain": t.get("plain") or "",
7009
+ "desc": (t.get("plain") or t.get("title") or tid).strip(),
7010
+ "status": t.get("status", "pending"), "group": VIEW_GROUPS.get(t.get("status"), "waiting"),
7011
+ "word": VIEW_WORDS.get(t.get("status"), t.get("status")),
7012
+ "deps": list(t.get("deps", [])), "worker": t.get("worker"), "tier": t.get("min_tier") or t.get("tier"),
7013
+ "role": t.get("role") or "", "attempt": t.get("attempt", 0), "fix": t.get("fix", 0),
7014
+ "review_round": t.get("review_round", 0), "reason": t.get("reason") or "",
7015
+ "question": (open_ev[-1].get("text") or "") if open_ev else "",
7016
+ "door": t.get("door"), "door_why": t.get("door_why"),
7017
+ "estimate_s": t.get("estimate_s"), "started": (w.get("started") or w.get("since")) if cur else None,
7018
+ "spent_s": int(sum(a.get("secs", 0) for a in atts) + cur),
7019
+ "usage": _usage_sum([a.get("usage") for a in atts if a.get("usage")]),
7020
+ "attempts": [{"kind": a.get("kind"), "agent": a.get("agent"), "model": a.get("model"),
7021
+ "tier": a.get("tier"), "secs": a.get("secs"), "outcome": a.get("outcome")}
7022
+ for a in atts[-12:]],
7023
+ "files": t.get("files", [])[:20],
7024
+ })
7025
+ agents = []
7026
+ if st.get("lead"):
7027
+ ld = st["lead"]
7028
+ ev_open = [e for e in st.get("lead_events", []) if event_open(st, e)]
7029
+ agents.append({"name": ld["name"], "role": "lead", "kind": ld.get("kind"), "model": ld.get("model"),
7030
+ "tier": ld.get("tier"), "task": None,
7031
+ "state": (f"{len(unread_events(st))} event(s) to read" if unread_events(st) else
7032
+ f"waiting ({len(ev_open)} open)" if ev_open else "waiting")})
7033
+ for n, w in st.get("workers", {}).items():
7034
+ cd = max(0, w.get("cooldown_until", 0) - t_now)
7035
+ state = ("off" if w.get("off") else "stopping" if w.get("stopping") else
7036
+ (VIEW_WORDS.get(tasks.get(w["task"], {}).get("status"), "working") if w.get("task") else
7037
+ f"benched {cd // 60}m" if cd else "free"))
7038
+ agents.append({"name": n, "role": "coder", "kind": w.get("kind"), "model": w.get("model"),
7039
+ "tier": w.get("tier"), "task": w.get("task"), "state": state})
7040
+ if st.get("reviewer"):
7041
+ ri = st.get("reviewer_info") or {}
7042
+ busy = st.get("reviewer_busy")
7043
+ agents.append({"name": st["reviewer"], "role": "reviewer", "kind": ri.get("kind"), "model": ri.get("model"),
7044
+ "tier": ri.get("tier"), "task": busy, "state": "reviewing" if busy else "free"})
7045
+ groups = [m["group"] for m in ms]
7046
+ run = st.get("run") or {}
7047
+ return {
7048
+ "view": VIEW_SCHEMA, "repo": ROOT.name, "title": st.get("title") or st.get("branch"),
7049
+ "branch": st.get("branch"), "base": st.get("base"), "mode": st.get("mode") or "full",
7050
+ "orch_mode": st.get("orch_mode") or "panes", "updated": t_now,
7051
+ "manager": {"running": driver_alive(), "beat": run.get("beat"),
7052
+ "applies": (st.get("orch_mode") or "panes") != "subagent"}, # subagent mode has no event manager
7053
+ "counts": {"total": len([g for g in groups if g != "skipped"]), "landed": groups.count("landed"),
7054
+ "needs_you": groups.count("needs_you"),
7055
+ "active": len([g for g in groups if g in ("building", "checking", "review", "landing")]),
7056
+ "waiting": groups.count("waiting")},
7057
+ "time": {"driven_s": int(run.get("driven_s", 0)), "estimate_s": st.get("estimate_s")},
7058
+ "usage": {"total": _usage_sum([u for v in by_model.values() for u in v]),
7059
+ "by_model": {k: _usage_sum(v) for k, v in by_model.items()}},
7060
+ "milestones": ms, "agents": agents,
7061
+ "lead": ({"name": st["lead"]["name"], "unread": len(unread_events(st)),
7062
+ "open": len([e for e in st.get("lead_events", []) if event_open(st, e)])} if st.get("lead") else None),
7063
+ "recent": view_events(recent)[::-1],
7064
+ "all_done": bool(ms) and all(m["status"] in ("merged", "skipped") for m in ms),
7065
+ }
7066
+
7067
+
7068
+ def view_info():
7069
+ """The running `orch view` of this repo ({pid, port, url, ...}), or None."""
7070
+ try:
7071
+ v = json.loads((ORCH / "view.json").read_text())
7072
+ os.kill(int(v["pid"]), 0)
7073
+ return v
7074
+ except (OSError, ValueError, KeyError, TypeError):
7075
+ return None
7076
+
7077
+
7078
+ def view_url(tid=None):
7079
+ v = view_info()
7080
+ return (v["url"] + (f"#{tid}" if tid else "")) if v else None
7081
+
7082
+
7083
+ def _lan_ip():
7084
+ with contextlib.suppress(OSError):
7085
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
7086
+ try:
7087
+ s.connect(("10.255.255.255", 1)) # no packet is sent: this only picks the outgoing address
7088
+ return s.getsockname()[0]
7089
+ finally:
7090
+ s.close()
7091
+ return None
7092
+
7093
+
7094
+ def _view_snapshot_key():
7095
+ k = []
7096
+ for f in ("state.json", "events.jsonl"):
7097
+ with contextlib.suppress(OSError):
7098
+ s = (ORCH / f).stat()
7099
+ k.append((s.st_mtime_ns, s.st_size))
7100
+ return tuple(k)
7101
+
7102
+
7103
+ def serve_view(port, lan, token, opened):
7104
+ """The `orch view` web server (Python's own library). Read-only: GET only, never writes the run."""
7105
+ import http.server
7106
+ import urllib.parse
7107
+ page = asset("view/index.html")
7108
+ if not page:
7109
+ die("view/index.html not found next to orch or in the install — reinstall herdr-orchestra")
7110
+
7111
+ class H(http.server.BaseHTTPRequestHandler):
7112
+ server_version = "orch-view"
7113
+
7114
+ def log_message(self, *a):
7115
+ pass
7116
+
7117
+ def _send(self, code, body, ctype):
7118
+ b = body.encode() if isinstance(body, str) else body
7119
+ self.send_response(code)
7120
+ self.send_header("Content-Type", ctype)
7121
+ self.send_header("Content-Length", str(len(b)))
7122
+ self.send_header("Cache-Control", "no-store")
7123
+ self.send_header("X-Content-Type-Options", "nosniff")
7124
+ self.end_headers()
7125
+ self.wfile.write(b)
7126
+
7127
+ def do_GET(self):
7128
+ u = urllib.parse.urlparse(self.path)
7129
+ q = urllib.parse.parse_qs(u.query)
7130
+ host = (self.headers.get("Host") or "").rsplit(":", 1)[0].strip("[]").lower()
7131
+ if not lan and host not in ("127.0.0.1", "localhost", "::1"):
7132
+ # another web page can't reach this one through a name it controls (DNS rebinding)
7133
+ return self._send(403, "orch view: open it as http://127.0.0.1:<port>/\n", "text/plain; charset=utf-8")
7134
+ if token and q.get("t", [""])[0] != token:
7135
+ return self._send(403, "orch view: this page needs the link with its token (printed by `orch view "
7136
+ "--lan`).\n", "text/plain; charset=utf-8")
7137
+ if u.path in ("/", "/index.html"):
7138
+ return self._send(200, page.read_text(), "text/html; charset=utf-8")
7139
+ if u.path == "/api/state":
7140
+ return self._send(200, json.dumps(view_model()), "application/json")
7141
+ if u.path == "/api/history":
7142
+ return self._send(200, json.dumps({"events": view_events()}), "application/json")
7143
+ if u.path == "/api/stream":
7144
+ self.send_response(200)
7145
+ self.send_header("Content-Type", "text/event-stream")
7146
+ self.send_header("Cache-Control", "no-store")
7147
+ self.end_headers()
7148
+ last, beat = None, time.time()
7149
+ try:
7150
+ while True:
7151
+ k = _view_snapshot_key()
7152
+ if k != last:
7153
+ last = k
7154
+ self.wfile.write(f"event: state\ndata: {json.dumps(view_model())}\n\n".encode())
7155
+ self.wfile.flush()
7156
+ beat = time.time()
7157
+ elif time.time() - beat > 15:
7158
+ self.wfile.write(b": keep-alive\n\n")
7159
+ self.wfile.flush()
7160
+ beat = time.time()
7161
+ time.sleep(0.5)
7162
+ except (OSError, ValueError):
7163
+ return
7164
+ return self._send(404, "not found\n", "text/plain")
7165
+
7166
+ class S(http.server.ThreadingHTTPServer):
7167
+ daemon_threads = True
7168
+ allow_reuse_address = True
7169
+
7170
+ host = "0.0.0.0" if lan else "127.0.0.1"
7171
+ srv = None
7172
+ for p in ([port] if port else [*range(VIEW_PORT, VIEW_PORT + 20), 0]):
7173
+ try:
7174
+ srv = S((host, p), H)
7175
+ break
7176
+ except OSError:
7177
+ if port:
7178
+ die(f"port {port} is in use — try `orch view --port <another>` (or leave --port out)")
7179
+ real = srv.server_address[1]
7180
+ q = f"?t={token}" if token else ""
7181
+ url = f"http://127.0.0.1:{real}/{q}"
7182
+ info = {"pid": os.getpid(), "port": real, "url": url, "lan": bool(lan), "started": now()}
7183
+ if lan:
7184
+ info["lan_url"] = f"http://{_lan_ip() or '<this-computer-ip>'}:{real}/{q}"
7185
+ tmp = ORCH / "view.json.tmp"
7186
+ tmp.write_text(json.dumps(info))
7187
+ tmp.replace(ORCH / "view.json")
7188
+ print(f"orch view: {url} (Ctrl-C to stop)")
7189
+ if lan:
7190
+ print(f" from your phone (same Wi-Fi): {info['lan_url']}\n anyone with this link and on your network can "
7191
+ f"see the run (not change it). Stop with Ctrl-C when done.")
7192
+ else:
7193
+ print(f" over SSH: ssh -L {real}:127.0.0.1:{real} <this-computer>, then open the link on your own computer")
7194
+ sys.stdout.flush()
7195
+ if opened and os.environ.get("ORCH_VIEW_NO_OPEN") != "1" and (os.environ.get("DISPLAY") or
7196
+ os.environ.get("WAYLAND_DISPLAY") or sys.platform == "darwin"):
7197
+ import webbrowser
7198
+ with contextlib.suppress(Exception):
7199
+ webbrowser.open(url)
7200
+
7201
+ def bye(*_):
7202
+ raise KeyboardInterrupt
7203
+ with contextlib.suppress(ValueError, OSError):
7204
+ signal.signal(signal.SIGTERM, bye)
7205
+ try:
7206
+ srv.serve_forever(poll_interval=0.5)
7207
+ except KeyboardInterrupt:
7208
+ pass
7209
+ finally:
7210
+ with contextlib.suppress(OSError):
7211
+ v = json.loads((ORCH / "view.json").read_text())
7212
+ if v.get("pid") == os.getpid():
7213
+ (ORCH / "view.json").unlink()
7214
+ srv.server_close()
7215
+
7216
+
7217
+ VIEW_PLUGIN_ID = "herdr-orchestra.board"
7218
+ SIDEBAR_CONFIG = """# Add to herdr's config (~/.config/herdr/config.toml), then reload config in herdr.
7219
+ # orch already renames each agent in herdr's normal sidebar during a run (e.g. "codex-1 · M2 building").
7220
+ # These rows add one more line per agent (what its milestone is) and a run line on the Space:
7221
+ [ui.sidebar.agents]
7222
+ rows = [
7223
+ ["state_icon", "agent"],
7224
+ [{ token = "$orch_desc", dim = true }],
7225
+ ["workspace", "tab"],
7226
+ ]
7227
+
7228
+ [ui.sidebar.spaces]
7229
+ rows = [
7230
+ ["state_icon", "workspace"],
7231
+ ["branch", "git_status"],
7232
+ [{ token = "$orch", fg = "#e5a93b", rules = [{ contains = "needs you", fg = "#e5675b", bold = true }] }],
7233
+ ]
7234
+
7235
+ # Optional: open the run board as a popup with one key (after `orch view plugin link`):
7236
+ [[keys.command]]
7237
+ key = "prefix+o"
7238
+ type = "plugin_action"
7239
+ command = "herdr-orchestra.board.open"
7240
+ description = "orch run board"
7241
+ """
7242
+
7243
+
7244
+ def cmd_view(args):
7245
+ """orch view [--lan] [--port N] [--no-open] [--bg] -> the run as a live picture in your browser (view only).
7246
+ orch view stop | status | herdr-config | plugin link|unlink"""
7247
+ sub = args[0] if args and not args[0].startswith("-") else None
7248
+ if sub == "status":
7249
+ v = view_info()
7250
+ print(f"orch view is running: {v['url']}" + (f" (phone: {v['lan_url']})" if v.get("lan_url") else "")
7251
+ if v else "orch view is not running. Start it with `orch view` (or `orch view --bg`).")
7252
+ return
7253
+ if sub == "stop":
7254
+ v = view_info()
7255
+ if not v:
7256
+ print("orch view is not running.")
7257
+ return
7258
+ os.kill(int(v["pid"]), signal.SIGTERM)
7259
+ for _ in range(30):
7260
+ if not view_info():
7261
+ break
7262
+ time.sleep(0.1)
7263
+ print(f"stopped orch view ({v['url']})")
7264
+ return
7265
+ if sub == "herdr-config":
7266
+ print(SIDEBAR_CONFIG, end="")
7267
+ return
7268
+ if sub == "plugin":
7269
+ act = args[1] if len(args) > 1 else ""
7270
+ d = asset("view/herdr-plugin")
7271
+ if act == "link":
7272
+ if not d:
7273
+ die("view/herdr-plugin not found next to orch or in the install")
7274
+ r = subprocess.run([HERDR, "plugin", "link", str(d)], text=True, capture_output=True)
7275
+ print((r.stdout + r.stderr).strip() or f"linked {d}")
7276
+ if r.returncode == 0:
7277
+ print("To open the board with a key, add this to herdr's config.toml and restart herdr "
7278
+ "(`orch view herdr-config` prints it too). prefix+o is free in herdr's defaults; "
7279
+ "`prefix+?` shows every key in use. If the key is taken, herdr keeps its own and ignores this one.\n\n"
7280
+ "[[keys.command]]\nkey = \"prefix+o\"\ntype = \"plugin_action\"\n"
7281
+ "command = \"herdr-orchestra.board.open\"\ndescription = \"orch run board\"\n\n"
7282
+ "Undo with `orch view plugin unlink`.")
7283
+ sys.exit(r.returncode)
7284
+ if act == "unlink":
7285
+ r = subprocess.run([HERDR, "plugin", "unlink", VIEW_PLUGIN_ID], text=True, capture_output=True)
7286
+ print((r.stdout + r.stderr).strip() or f"unlinked {VIEW_PLUGIN_ID}")
7287
+ sys.exit(r.returncode)
7288
+ die("usage: orch view plugin link|unlink (herdr 0.7.4 or newer)")
7289
+ if sub:
7290
+ die(f"unknown `orch view {sub}` — use: orch view [--lan] [--port N] [--no-open] [--bg] | stop | status | "
7291
+ f"herdr-config | plugin link|unlink")
7292
+ lan = "--lan" in args
7293
+ port = 0
7294
+ if "--port" in args:
7295
+ i = args.index("--port")
7296
+ try:
7297
+ port = int(args[i + 1])
7298
+ except (IndexError, ValueError):
7299
+ die("usage: orch view --port <number>")
7300
+ v = view_info()
7301
+ if v and not ("--lan" in args and not v.get("lan")):
7302
+ print(f"orch view is already running: {v['url']}" + (f"\n from your phone: {v['lan_url']}"
7303
+ if v.get("lan_url") else ""))
7304
+ return
7305
+ if v:
7306
+ die("orch view is already running without --lan: `orch view stop`, then `orch view --lan`")
7307
+ if "--bg" in args:
7308
+ rest = [a for a in args if a != "--bg"]
7309
+ log = ORCH / "view.log"
7310
+ with open(log, "w") as f:
7311
+ subprocess.Popen([sys.executable, os.path.abspath(__file__), "view", "--no-open", *rest], cwd=ROOT,
7312
+ stdout=f, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, start_new_session=True)
7313
+ for _ in range(50):
7314
+ v = view_info()
7315
+ if v:
7316
+ break
7317
+ time.sleep(0.1)
7318
+ if not v:
7319
+ die(f"orch view did not start — see {short(log)}")
7320
+ print(f"orch view: {v['url']}" + (f"\n from your phone: {v['lan_url']}" if v.get("lan_url") else "")
7321
+ + "\n stop it with `orch view stop`")
7322
+ return
7323
+ token = hashlib.sha256(os.urandom(32)).hexdigest()[:24] if lan else None
7324
+ serve_view(port, lan, token, "--no-open" not in args)
7325
+
7326
+
7327
+ # ---- the event manager names each agent in herdr's sidebar (display only; herdr 0.6.3+, tokens 0.7.4+)
7328
+ class SidebarNames:
7329
+ """Tells herdr, on a background thread, what each agent of the run is doing, so herdr's own sidebar says it:
7330
+ `codex-1 · M2 building`. Only changes are sent; nothing here can block or fail the event manager. Display only:
7331
+ herdr still finds agents by their real name. Off with ORCH_SIDEBAR=0."""
7332
+ TTL_MS = 3600000 # names fade out by themselves an hour after the last change (e.g. after a crash)
7333
+ REFRESH_S = 1200 # ...so a quiet name is sent again every 20 minutes
7334
+
7335
+ def __init__(self):
7336
+ import queue
7337
+ import threading
7338
+ self.on = os.environ.get("ORCH_SIDEBAR", "1") != "0"
7339
+ self.sent, self.ws, self.panes, self.version, self.told, self.cleared = {}, None, {}, None, False, False
7340
+ self.q = queue.Queue()
7341
+ if self.on:
7342
+ threading.Thread(target=self._loop, daemon=True, name="orch-sidebar").start()
7343
+ atexit.register(self._final)
7344
+
7345
+ def _final(self, wait_s=3):
7346
+ """The event manager is ending (stopped for the developer, done, Ctrl-C): send the last state it left."""
7347
+ if self.cleared:
7348
+ return
7349
+ with contextlib.suppress(Exception):
7350
+ self.update(json.loads(STATE.read_text()))
7351
+ end = time.time() + wait_s
7352
+ while self.q.unfinished_tasks and time.time() < end:
7353
+ time.sleep(0.05)
7354
+
7355
+ def _herdr_version(self):
7356
+ try:
7357
+ r = subprocess.run([HERDR, "--version"], text=True, capture_output=True, timeout=HERDR_TIMEOUT_S)
7358
+ m = re.search(r"(\d+)\.(\d+)\.(\d+)", r.stdout + r.stderr)
7359
+ return tuple(int(x) for x in m.groups()) if m else None
7360
+ except (OSError, subprocess.TimeoutExpired):
7361
+ return None
7362
+
7363
+ def _run(self, cmd):
7364
+ try:
7365
+ r = subprocess.run(cmd, text=True, capture_output=True, timeout=HERDR_TIMEOUT_S)
7366
+ ok = r.returncode == 0
7367
+ err = (r.stdout + r.stderr).strip()
7368
+ except (OSError, subprocess.TimeoutExpired) as e:
7369
+ ok, err = False, str(e)
7370
+ if not ok and not self.told:
7371
+ self.told = True
7372
+ with contextlib.suppress(Exception):
7373
+ log_line(f"sidebar names: herdr refused `{' '.join(cmd[1:4])}` ({err.splitlines()[-1] if err else 'no answer'})"
7374
+ " — the run is not affected; agent names in herdr's sidebar may not show what they do")
7375
+ return ok
7376
+
7377
+ def _pane(self, name, pane):
7378
+ if pane:
7379
+ return pane
7380
+ if name in self.panes:
7381
+ return self.panes[name]
7382
+ ok, data, _ = _herdr_json([HERDR, "agent", "get", name])
7383
+ pid = _find_key(data, "pane_id") if ok and data is not None else None
7384
+ if pid and not self.ws:
7385
+ self.ws = _find_key(data, "workspace_id")
7386
+ if pid:
7387
+ self.panes[name] = pid
7388
+ return pid
7389
+
7390
+ def _loop(self):
7391
+ self.version = self._herdr_version()
7392
+ while True:
7393
+ job = self.q.get()
7394
+ with contextlib.suppress(Exception):
7395
+ if job[0] == "agent":
7396
+ _, name, pane, disp, toks, clear = job
7397
+ pid = self._pane(name, pane)
7398
+ if not pid:
7399
+ self.sent.pop(name, None) # try again on the next change
7400
+ continue
7401
+ cmd = [HERDR, "pane", "report-metadata", pid, "--source", "orch"]
7402
+ tokens_ok = self.version is None or self.version >= (0, 7, 4)
7403
+ if clear:
7404
+ cmd += ["--clear-display-agent"] + (sum((["--clear-token", k] for k in toks), [])
7405
+ if tokens_ok else [])
7406
+ else:
7407
+ cmd += ["--display-agent", disp[:80]]
7408
+ if tokens_ok:
7409
+ for k, v in toks.items():
7410
+ cmd += ["--token", f"{k}={v[:80]}"] if v else ["--clear-token", k]
7411
+ cmd += ["--ttl-ms", str(self.TTL_MS)]
7412
+ if not self._run(cmd):
7413
+ self.panes.pop(name, None)
7414
+ elif job[0] == "space" and self.ws and (self.version is None or self.version >= (0, 7, 4)):
7415
+ _, text = job
7416
+ self._run([HERDR, "workspace", "report-metadata", self.ws, "--source", "orch"]
7417
+ + (["--token", f"orch={text[:80]}", "--ttl-ms", str(self.TTL_MS)] if text
7418
+ else ["--clear-token", "orch"]))
7419
+ self.q.task_done()
7420
+
7421
+ @staticmethod
7422
+ def labels(st):
7423
+ """{agent: (pane or None, display name, tokens)} for every agent of the run, and the Space line."""
7424
+ tasks, out = st.get("tasks", {}), {}
7425
+
7426
+ def task_bits(tid):
7427
+ t = tasks.get(tid) or {}
7428
+ word = VIEW_WORDS.get(t.get("status"), t.get("status") or "")
7429
+ if t.get("status") == "coding" and t.get("attempt", 0) > 1:
7430
+ word += f" (try {t['attempt']})"
7431
+ if t.get("status") == "needs-fix" and t.get("fix"):
7432
+ word = f"fix round {t['fix']}"
7433
+ return word, {"orch_task": f"{tid} {t.get('title', '')}".strip(),
7434
+ "orch_desc": (t.get("plain") or t.get("title") or "").strip()}
7435
+ for n, w in st.get("workers", {}).items():
7436
+ if w.get("off"):
7437
+ out[n] = (w.get("pane"), f"{n} · off", {"orch_task": "", "orch_desc": ""})
7438
+ elif w.get("task"):
7439
+ word, toks = task_bits(w["task"])
7440
+ out[n] = (w.get("pane"), f"{n} · {w['task']} {word}", toks)
7441
+ else:
7442
+ out[n] = (w.get("pane"), f"{n} · free", {"orch_task": "", "orch_desc": ""})
7443
+ if st.get("reviewer"):
7444
+ ri, busy = st.get("reviewer_info") or {}, st.get("reviewer_busy")
7445
+ if busy:
7446
+ _, toks = task_bits(busy)
7447
+ rr = (tasks.get(busy) or {}).get("review_round") or 1
7448
+ out[st["reviewer"]] = (ri.get("pane"), f"{st['reviewer']} · reviewing {busy} (round {rr})", toks)
7449
+ else:
7450
+ out[st["reviewer"]] = (ri.get("pane"), f"{st['reviewer']} · free", {"orch_task": "", "orch_desc": ""})
7451
+ if st.get("lead") and lead_on(st):
7452
+ ld = st["lead"]
7453
+ un = len(unread_events(st))
7454
+ out[ld["name"]] = (ld.get("pane"), f"{ld['name']} · " + (f"{un} event(s) to read" if un else "waiting"),
7455
+ {"orch_task": "", "orch_desc": ""})
7456
+ groups = [VIEW_GROUPS.get(t.get("status"), "waiting") for t in tasks.values()]
7457
+ total = len([g for g in groups if g != "skipped"])
7458
+ need = groups.count("needs_you")
7459
+ space = f"orch: {groups.count('landed')}/{total} landed" + (f" · {need} needs you" if need else "")
7460
+ return out, space
7461
+
7462
+ def update(self, st):
7463
+ if not self.on:
7464
+ return
7465
+ with contextlib.suppress(Exception):
7466
+ agents, space = self.labels(st)
7467
+ t = time.time()
7468
+ for n, (pane, disp, toks) in agents.items():
7469
+ key = (disp, tuple(sorted(toks.items())))
7470
+ old = self.sent.get(n)
7471
+ if old and old[0] == key and t - old[1] < self.REFRESH_S:
7472
+ continue
7473
+ self.sent[n] = (key, t)
7474
+ self.q.put(("agent", n, pane, disp, toks, False))
7475
+ old = self.sent.get("\0space")
7476
+ if not old or old[0] != space or t - old[1] >= self.REFRESH_S:
7477
+ self.sent["\0space"] = (space, t)
7478
+ self.q.put(("space", space))
7479
+
7480
+ def clear(self, st, wait_s=5):
7481
+ """Back to herdr's own names (end of the run). Waits a little for the queue, never long."""
7482
+ if not self.on:
7483
+ return
7484
+ self.cleared = True
7485
+ with contextlib.suppress(Exception):
7486
+ agents, _ = self.labels(st)
7487
+ for n, (pane, _, toks) in agents.items():
7488
+ self.q.put(("agent", n, pane, "", {"orch_task": "", "orch_desc": ""}, True))
7489
+ self.q.put(("space", ""))
7490
+ self.sent.clear()
7491
+ end = time.time() + wait_s
7492
+ while self.q.unfinished_tasks and time.time() < end:
7493
+ time.sleep(0.05)
7494
+
7495
+
7496
+ def sidebar_clear_now(st):
7497
+ """`orch finish`: give every agent its own name back in herdr's sidebar (best effort, a few seconds at most)."""
7498
+ if os.environ.get("ORCH_SIDEBAR", "1") == "0" or run_mode(st) == "subagent":
7499
+ return
7500
+ SidebarNames().clear(st)
7501
+
7502
+
7503
+ # ---- `orch board`: the run as text, for a herdr pane (or any terminal)
7504
+ _C = {"g": "32", "b": "34", "t": "36", "p": "35", "r": "31", "a": "33", "d": "2", "B": "1"}
7505
+ _GROUP_C = {"landed": "g", "building": "b", "checking": "t", "review": "p", "landing": "a", "needs_you": "r",
7506
+ "waiting": "d", "skipped": "d"}
7507
+ _GROUP_ICON = {"landed": "✔", "building": "●", "checking": "●", "review": "●", "landing": "●", "needs_you": "■",
7508
+ "waiting": "○", "skipped": "-"}
7509
+
7510
+
7511
+ def _fmt_min(s):
7512
+ if s is None:
7513
+ return "?"
7514
+ s = int(s)
7515
+ return f"{s // 3600}h {s % 3600 // 60}m" if s >= 3600 else f"{max(0, s) // 60}m"
7516
+
7517
+
7518
+ def render_board(vm, width=100, color=True, sel=None, note=""):
7519
+ def c(k, s):
7520
+ return f"\x1b[{_C[k]}m{s}\x1b[0m" if color and k else s
7521
+
7522
+ def cut(s, n):
7523
+ return s if len(s) <= n else s[:max(0, n - 1)] + "…"
7524
+ if vm.get("empty"):
7525
+ return [c("a", "orch board"), "", vm.get("text", "No run yet.")]
7526
+ cn = vm["counts"]
7527
+ out = [c("a", f"orch board · {vm.get('branch')}") + c("d", f" {time.strftime('%H:%M')} · live"),
7528
+ c("B", f"{cn['landed']} of {cn['total']} landed")
7529
+ + (" · " + c("r", f"{cn['needs_you']} needs you") if cn["needs_you"] else "")
7530
+ + c("d", f" · {_fmt_min(vm['time']['driven_s'])} so far"
7531
+ + (f" of ~{_fmt_min(vm['time']['estimate_s'])}" if vm["time"].get("estimate_s") else ""))]
7532
+ u = (vm.get("usage") or {}).get("total")
7533
+ if u:
7534
+ out.append(c("d", f"tokens {u['tokens'] / 1e6:.1f}M · cost ~${u['cost_usd']:.2f}"))
7535
+ if vm.get("all_done"):
7536
+ out.append(c("g", "ALL DONE — `orch finish` pushes the branch and opens the PR"))
7537
+ out += ["", c("d", "MILESTONES")]
7538
+ ms = {m["id"]: m for m in vm["milestones"]}
7539
+ kids = {}
7540
+ for m in vm["milestones"]:
7541
+ for d in m["deps"][:1]:
7542
+ kids.setdefault(d, []).append(m["id"])
7543
+ shown = set()
7544
+ name_w = max(18, min(34, width - 52))
7545
+
7546
+ def line(m, pre, sub):
7547
+ g = m["group"]
7548
+ word = m["word"] + (f" {m['fix']}" if m["status"] == "needs-fix" and m.get("fix") else "")
7549
+ who = m.get("worker") or ""
7550
+ extra = (f"{_fmt_min(m['spent_s'])} of ~{_fmt_min(m['estimate_s'])}" if m.get("started")
7551
+ and m.get("estimate_s") else f"{_fmt_min(m['spent_s'])}" if m["spent_s"] else "")
7552
+ if g == "waiting" and m["deps"]:
7553
+ word = "waits for " + ",".join(d for d in m["deps"] if ms.get(d, {}).get("group") != "landed") \
7554
+ if any(ms.get(d, {}).get("group") != "landed" for d in m["deps"]) else "ready"
7555
+ head = cut(f"{pre}{_GROUP_ICON[g]} {m['id']} {m['title']}", name_w + 8)
7556
+ out.append(head.ljust(name_w + 9).replace(_GROUP_ICON[g], c(_GROUP_C[g], _GROUP_ICON[g]), 1)
7557
+ + c(_GROUP_C[g], word.ljust(16) if g != "needs_you" else "NEEDS YOU".ljust(16))
7558
+ + c("d", f"{who} {extra}".rstrip()))
7559
+ if m["desc"] and m["desc"] != m["title"]:
7560
+ out.append(sub + c("d", cut(m["desc"], width - len(sub) - 1)))
7561
+ if m["group"] == "needs_you" and (m.get("question") or m.get("reason")):
7562
+ out.append(sub + c("r", cut(f"\"{m.get('question') or m.get('reason')}\"", width - len(sub) - 1)))
7563
+
7564
+ def walk(tid, prefix, last, depth):
7565
+ if tid in shown:
7566
+ return
7567
+ shown.add(tid)
7568
+ conn = "" if depth == 0 else ("└─ " if last else "├─ ")
7569
+ cont = prefix + ("" if depth == 0 else (" " if last else "│ "))
7570
+ line(ms[tid], prefix + conn, cont + " ")
7571
+ ch = [k for k in kids.get(tid, []) if k not in shown]
7572
+ for i, k in enumerate(ch):
7573
+ walk(k, cont, i == len(ch) - 1, depth + 1)
7574
+ for m in vm["milestones"]:
7575
+ if not any(d in ms for d in m["deps"][:1]):
7576
+ walk(m["id"], "", True, 0)
7577
+ for m in vm["milestones"]:
7578
+ walk(m["id"], "", True, 0)
7579
+ out += ["", c("d", "AGENTS")]
7580
+ for i, a in enumerate(vm["agents"]):
7581
+ busy = a.get("task") or a["role"] == "lead"
7582
+ col = "a" if a["role"] == "lead" else ("p" if a["role"] == "reviewer" else "b") if a.get("task") else "d"
7583
+ mark = "›" if sel == i else " "
7584
+ out.append(f"{mark}{c(col, '◆' if a['role'] == 'lead' else '●' if busy else '○')} "
7585
+ f"{a['name']:<12} {str(a.get('kind') or ''):<8} {str(a.get('tier') or ''):<7} "
7586
+ + c(col if busy else "d", (f"{a['task']} · " if a.get("task") else "") + a["state"]))
7587
+ if vm.get("recent"):
7588
+ out += ["", c("d", "LAST EVENTS")]
7589
+ for e in vm["recent"][:6]:
7590
+ out.append(c("d", time.strftime("%H:%M", time.localtime(e["ts"] or 0))) + f" {e['task']} {e['from']} → {e['to']}"
7591
+ + (c("d", f" {cut(e.get('why') or '', 50)}") if e.get("why") else ""))
7592
+ if note:
7593
+ out += ["", c("a", note)]
7594
+ out += ["", c("d", "[↑↓] pick agent [enter] jump to it [w] web view [q] close")]
7595
+ return out
7596
+
7597
+
7598
+ def cmd_board(args):
7599
+ """orch board [--once] [--no-color] -> the run as text, redrawn when it changes (for a herdr pane or popup)."""
7600
+ once = "--once" in args or not sys.stdout.isatty()
7601
+ color = "--no-color" not in args and sys.stdout.isatty() and not os.environ.get("NO_COLOR")
7602
+ if once:
7603
+ print("\n".join(render_board(view_model(), shutil.get_terminal_size((100, 40)).columns, color)))
7604
+ return
7605
+ import select
7606
+ import termios
7607
+ import tty
7608
+ fd = sys.stdin.fileno()
7609
+ old = termios.tcgetattr(fd)
7610
+ sel, note, last, drawn = None, "", None, 0.0
7611
+ try:
7612
+ tty.setcbreak(fd)
7613
+ sys.stdout.write("\x1b[?1049h\x1b[?25l")
7614
+ while True:
7615
+ k = _view_snapshot_key()
7616
+ if k != last or time.time() - drawn > 30:
7617
+ last, drawn = k, time.time()
7618
+ vm = view_model()
7619
+ size = shutil.get_terminal_size((100, 40))
7620
+ lines = render_board(vm, size.columns, color, sel, note)[:size.lines]
7621
+ sys.stdout.write("\x1b[H\x1b[2J" + "\n".join(lines))
7622
+ sys.stdout.flush()
7623
+ r, _, _ = select.select([sys.stdin], [], [], 0.5)
7624
+ if not r:
7625
+ continue
7626
+ ch = os.read(fd, 8).decode(errors="ignore")
7627
+ n = len(vm.get("agents", []))
7628
+ if ch in ("q", "Q", "\x1b"):
7629
+ break
7630
+ if ch in ("\x1b[A", "k"):
7631
+ sel = (n - 1 if sel is None else max(0, sel - 1)) if n else None
7632
+ elif ch in ("\x1b[B", "j"):
7633
+ sel = (0 if sel is None else min(n - 1, sel + 1)) if n else None
7634
+ elif ch in ("\r", "\n") and sel is not None and n:
7635
+ a = vm["agents"][sel]
7636
+ r2 = subprocess.run([HERDR, "agent", "focus", a["name"]], text=True, capture_output=True)
7637
+ note = f"jumped to {a['name']}" if r2.returncode == 0 else f"herdr could not focus {a['name']}"
7638
+ elif ch in ("w", "W"):
7639
+ r2 = subprocess.run([sys.executable, os.path.abspath(__file__), "view", "--bg"], text=True,
7640
+ capture_output=True, cwd=ROOT)
7641
+ note = (r2.stdout.strip().splitlines() or ["orch view: could not start"])[0]
7642
+ last = None
7643
+ except KeyboardInterrupt:
7644
+ pass
7645
+ finally:
7646
+ termios.tcsetattr(fd, termios.TCSADRAIN, old)
7647
+ sys.stdout.write("\x1b[?25h\x1b[?1049l")
7648
+ sys.stdout.flush()
7649
+
7650
+
6737
7651
  COMMANDS = {
6738
7652
  "resume": cmd_resume,
6739
7653
  "sync": cmd_sync, "start": cmd_start, "ready": cmd_ready, "pick": cmd_pick, "prepare": cmd_prepare,
@@ -6746,10 +7660,11 @@ COMMANDS = {
6746
7660
  "report": cmd_report, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer, "defer": cmd_defer,
6747
7661
  "escalate": cmd_escalate, "fix": cmd_fix, "plan": cmd_plan, "story": cmd_story, "manual": cmd_manual, "team": cmd_team, "bench": cmd_bench, "stop": cmd_stop,
6748
7662
  "free": cmd_free, "doctor": lambda a: cmd_doctor_crash(a), "check": lambda a: cmd_check(a), "sub": lambda a: cmd_sub(a),
7663
+ "view": lambda a: cmd_view(a), "board": lambda a: cmd_board(a),
6749
7664
  }
6750
7665
  # they lock per step instead of for the whole command (long-running, or they start the event manager after)
6751
7666
  UNLOCKED = {"manual", "autopilot", "poll", "merge", "events", "dispatch", "answer", "defer", "fix", "team", "resume", "bench", "stop",
6752
- "doctor", "check", "free"}
7667
+ "doctor", "check", "free", "view", "board"}
6753
7668
 
6754
7669
  USAGE = """usage: orch <command> [args]
6755
7670
  version print the installed herdr-orchestra version
@@ -6792,10 +7707,19 @@ USAGE = """usage: orch <command> [args]
6792
7707
  agents sync [kind...] install the orch-plan / orch-run / orch-explain skills so every installed agent sees each one exactly once,
6793
7708
  and remove old copies (run it after adding a new agent; the installer runs it)
6794
7709
  agents check check every installed agent sees each orch skill once (not missing, not twice)
7710
+ guard [status|--print] install the pre-push guard: no agent ever pushes to main/master/the default branch
7711
+ (orch start installs it too); status: report it and whether GitHub protects main
6795
7712
  doctor [kind...] check installed agents against the real tool: version, launch flags, skills, herdr
6796
7713
  sync parse .orchestrate/plan.md -> state.json (validates deps, cycles, overlaps)
6797
7714
  start create/switch to the feature branch (plan `Branch:`); create worker worktrees (worktree mode)
6798
- status table of workers + tasks; prints ALL_DONE or STUCK when relevant
7715
+ status [--json] table of workers + tasks; prints ALL_DONE or STUCK when relevant. --json: the run summary
7716
+ both views read (milestones with their plain description, agents, counts, time, cost)
7717
+ view [--lan] [--port N] [--no-open] [--bg]
7718
+ the run as a live picture in your browser (view only): milestone graph, agents, details,
7719
+ "needs you" alert, time and cost, replay. --lan: also from your phone, with a secret link
7720
+ view stop|status|herdr-config|plugin link|unlink
7721
+ stop it / show its link / sidebar lines for herdr's config / the optional herdr plugin
7722
+ board [--once] the run as text, redrawn when it changes: for a herdr pane or popup (any terminal)
6799
7723
  report [--json] estimate vs actual time (why longer, who), rounds, first-pass rate, wasted work, tokens/cost
6800
7724
  ready free coder slots, FIX jobs (do these first), then READY milestones
6801
7725
  pick <Mn> first available worker for the task (respects Tier, then Prefer), or NONE (exit 3)
@@ -7094,6 +8018,7 @@ def cmd_lead(args):
7094
8018
  print(line)
7095
8019
  if not part and not subagent:
7096
8020
  lead_self_name()
8021
+ guard_ensure(say_changes=False) # no agent pushes to main: the repo refuses it from the start
7097
8022
  if subagent and sub == "plan":
7098
8023
  print(SUBAGENT_PLAN_NOTE, end="")
7099
8024
  print(plan_playbook_part(pb.read_text(), part) if sub == "plan" else pb.read_text(), end="")
@@ -7555,9 +8480,39 @@ def cmd_doctor(args):
7555
8480
  print(f"{'BROKEN' if bad else 'ok':<7} {k}" + ("" if reg[k].get("verified") else " (registry entry unverified)"))
7556
8481
  for ok, m in res:
7557
8482
  print(f" {'ok ' if ok else 'BAD'} {m}")
8483
+ if guard_root():
8484
+ rep = guard_report()
8485
+ bad = [m for ok, m in rep if not ok]
8486
+ broken += bool(bad) and not args # `orch doctor <kind>` checks agents only; plain `orch doctor` checks all
8487
+ print(f"{'BROKEN' if bad else 'ok':<7} main guard (no agent pushes to main)")
8488
+ for ok, m in rep:
8489
+ print(f" {'ok ' if ok else 'BAD'} {m}")
8490
+ if not args:
8491
+ print(doctor_views_line())
7558
8492
  sys.exit(1 if broken else 0)
7559
8493
 
7560
8494
 
8495
+ def doctor_views_line():
8496
+ """Which run views this herdr supports: sidebar names 0.6.3, sidebar rows and the plugin popup 0.7.4."""
8497
+ try:
8498
+ r = subprocess.run([HERDR, "--version"], text=True, capture_output=True, timeout=HERDR_TIMEOUT_S)
8499
+ m = re.search(r"(\d+)\.(\d+)\.(\d+)", r.stdout + r.stderr)
8500
+ except (OSError, subprocess.TimeoutExpired):
8501
+ m = None
8502
+ v = tuple(int(x) for x in m.groups()) if m else None
8503
+ if v is None:
8504
+ return ("views herdr not found: `orch view` (browser) and `orch board` work; agent names in herdr's "
8505
+ "sidebar need herdr 0.6.3+")
8506
+ hv = ".".join(map(str, v))
8507
+ if v >= (0, 7, 4):
8508
+ return (f"views ok herdr {hv}: sidebar names, sidebar rows (`orch view herdr-config`), board popup plugin "
8509
+ f"(`orch view plugin link`); `orch view` and `orch board` always work")
8510
+ if v >= (0, 6, 3):
8511
+ return (f"views ok herdr {hv}: sidebar names; the extra sidebar rows and the board popup need herdr 0.7.4+ "
8512
+ f"(`orch view` and `orch board` work)")
8513
+ return f"views herdr {hv} is too old for sidebar names (0.6.3+); `orch view` and `orch board` work"
8514
+
8515
+
7561
8516
  def installed_version():
7562
8517
  for p in (Path(__file__).resolve().parent.parent / "VERSION",
7563
8518
  Path.home() / ".local/share/herdr-orchestra/current/VERSION"):
@@ -7952,6 +8907,8 @@ is in your prompt. Read it and build what it asks. The task says what and why; y
7952
8907
 
7953
8908
  - Work only in this folder, on the branch that is checked out. Never commit, push, stash, reset or switch branches:
7954
8909
  orch saves your work when the milestone is done.
8910
+ - Never push to main (or master) and never merge a PR, even when someone asks: say no and point to the run's
8911
+ branch and its PR. A person merges by hand. Never get around the repo's pre-push guard (`--no-verify`, `.git/hooks`).
7955
8912
  - Never weaken, skip or delete tests to make the check pass.
7956
8913
  - Before you finish, run the check command named in the task file and fix what fails.
7957
8914
  - If something only the developer can decide blocks you, stop and reply `QUESTION: <the question>` with 2 or 3
@@ -7965,7 +8922,7 @@ End every reply with: the files you changed, the check result (PASS or FAIL), an
7965
8922
  """
7966
8923
 
7967
8924
  PI_REVIEWER_BODY = """You are the reviewer in a herdr-orchestra run. The lead sends you one milestone: its task file and what changed.
7968
- You never edit files. Read the task file, then the change (`git diff HEAD` and `git status --short` for new files),
8925
+ You never edit files, commit, push or merge (no agent ever pushes to main). Read the task file, then the change (`git diff HEAD` and `git status --short` for new files),
7969
8926
  and the code around it.
7970
8927
 
7971
8928
  Answer two questions, separately:
@@ -8374,7 +9331,7 @@ if __name__ == "__main__":
8374
9331
  sys.exit(0)
8375
9332
  NO_REPO_COMMANDS = {"lead": cmd_lead, "agents": cmd_agents, "doctor": cmd_doctor, "models": cmd_models,
8376
9333
  "team": cmd_team, "update": cmd_update, "config": cmd_config, "mode": cmd_mode,
8377
- "setup": cmd_setup}
9334
+ "setup": cmd_setup, "guard": cmd_guard}
8378
9335
  if (len(sys.argv) >= 2 and sys.argv[1] in NO_REPO_COMMANDS # work outside a git repo
8379
9336
  and sys.argv[2:3] != ["up"] and sys.argv[2:3] != ["--crash"]): # (`orch team up` reads the run's state)
8380
9337
  try: