herdr-orchestra 5.1.0 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  All notable changes. Versions follow [semantic versioning](https://semver.org).
4
4
 
5
+ ## [5.3.0] - 2026-11-13
6
+
7
+ ### Fixed
8
+ - **A wake-up that never became a turn is no longer lost.** In a real run the event manager logged `woke the lead` after a milestone merged, the lead never got a turn, and the run sat at ALL_DONE until the developer asked "status?". Two things in the code caused the silence. "Woke the lead" only meant the prompt was handed to herdr; nothing checked that the lead acted on it. And the only retry was after 5 minutes, by a process that exits at ALL_DONE: the ALL_DONE wake-up 4 seconds later was skipped because a wake-up for the same batch was "already pending", and then the event manager left, so nothing was ever sent again. (Why the first prompt did not become a turn could not be confirmed from the logs: most likely it landed in the pane's input box while the developer was typing there.) Now only the lead reading its events (`orch events`) counts. If the lead is idle again and the events are still unread, the wake-up is sent again after `ORCH_LEAD_CONFIRM_S` (30 seconds), then after twice that; after 3 wake-ups the developer gets a notification that says what to do. At ALL_DONE the event manager stays up until the lead has read the last events (at most `ORCH_LEAD_SETTLE_S`, 5 minutes, when the lead is busy). The log is honest about it: `woke the lead … (sent; it counts once the lead reads them)`, `the lead did not pick up its wake-up … -> sent it again (2 of 3)`, `the lead picked up its events`. `orch status` shows `wake-up sent 2x (last 0m40s ago), not picked up yet`. The lead's playbook also tells it to run `orch events` before it stops whenever the developer talks to it.
9
+
10
+ ### Changed
11
+ - **The manual checklist holds only what a person must check.** The summary used to ask the lead for a checklist "per user-facing behaviour", which filled it with things like reading code or comments. Now the summary has a "Checked automatically" section written by orch: the check command on the finished branch, each review, and every acceptance criterion with the coder's and the reviewer's recorded evidence. The lead then adds "Checked by the lead": whatever else a command or a look at the code can settle, it settles itself and writes the evidence (it may run the check command, single tests and read-only commands; it still never edits code; a check that fails is offered as an `orch fix`). The "Manual verification checklist" is left with what needs eyes or hands: how the UI looks and behaves in a real browser or on a real device, and anything that needs an outside account or hardware, each written as "where to go, what to do → what you should see". A change with nothing to look at says `Nothing to check by hand`. The plan playbook asks for acceptance criteria a test can prove, and to say plainly when one needs a person.
12
+
13
+ ### Added
14
+ - **A role for every coder.** Each milestone gets a `Role:` line from the lead: the specialist the work needs and what that specialist cares about in this milestone (for UI work: "senior frontend engineer with a designer's eye: matches the app's existing components and spacing, works on a small screen, has loading, empty and error states, usable by keyboard"). orch puts it at the top of the coder's task file ("For this task you are: …", work to that standard, review your own result as that specialist before finishing) and in `task.json` as `role`. An `orch fix` follow-up keeps the role of the milestone it fixes. The role sets the standard, never the method: the coder still owns the how. A plan without `Role:` works as before.
15
+
16
+ ## [5.2.0] - 2026-11-13
17
+
18
+ ### Added
19
+ - **Estimated vs actual time.** The lead now gives a time estimate when it plans: `Estimate:` on each milestone (dispatch to landed if nothing goes wrong: building on the model it picked, the checks, one review) and `Estimate:` in the plan header for the whole feature (milestones that run side by side count once). `orch sync` refuses a value that is not a time (`40m`, `1h30m`, `2h`) and warns when one is missing. orch measures the real time from what it already records (status changes, every coder and reviewer attempt with its model and job, check times), and now also the time an agent sits at a permission prompt or question in its pane (from herdr's `blocked` state). The summary has a new "Time: estimate vs actual" section, and `orch report` prints it first (`--json` adds it as `time`): the feature's estimate and real time, and one row per milestone with estimate, actual, difference and who built it. When a milestone or the feature took longer, it lists where the extra time went and who or what it waited on, e.g. `10m claude-1 (sonnet): fix rounds: the check command failed`, `20m developer / lead: paused, waiting for the lead or the developer (which currency?)`, `5m claude-1: stopped at a permission prompt or question in its pane`, a usage limit, a lost agent, the reviewer, a second review, merge conflicts, an escalation, or time when no milestone was running. Nothing is guessed: time orch can't place is shown as orch's own steps, and when the planned work alone took longer it says the estimate was too low. Time after every milestone landed and before an `orch fix` is not counted against the feature.
20
+
5
21
  ## [5.1.0] - 2026-11-13
6
22
 
7
23
  ### Changed
package/README.md CHANGED
@@ -37,7 +37,7 @@ Run a small team of AI coding agents inside [Herdr](https://herdr.dev). An AI **
37
37
 
38
38
  | Agent | Does | Never does |
39
39
  |---|---|---|
40
- | **Lead** (any agent; you pick it by starting the playbook in its pane) | Researches the codebase; writes 1–4 milestones as issues (goal, why, acceptance criteria, constraints, interfaces, context facts, dependencies with reasons); gives each a model tier with the reason; dispatches the work, pauses, and is woken to decide: what to start next, a coder's question (asking you when only you can answer), a failed or held milestone, the final summary | Writes code, tells coders how to implement or fix, prompts or polls agents |
40
+ | **Lead** (any agent; you pick it by starting the playbook in its pane) | Researches the codebase; writes 1–4 milestones as issues (goal, why, acceptance criteria, constraints, interfaces, context facts, dependencies with reasons); gives each a model tier with the reason and a time estimate; dispatches the work, pauses, and is woken to decide: what to start next, a coder's question (asking you when only you can answer), a failed or held milestone, the final summary | Writes code, tells coders how to implement or fix, prompts or polls agents |
41
41
  | **Coders** (any agents: Claude, Codex, Amp, OpenCode, Hermes, AGY…) | Own the how: design, code, tests, fixing failed checks, fixing review findings, resolving conflicts | Change scope or skip acceptance criteria |
42
42
  | **Reviewer** (any spare agent, or another pane of the same tool) | Reports problems: `BLOCKER: file:line — what — why` | Edits code or prescribes fixes |
43
43
  | **Event manager** (`orch autopilot`, a script) | Sends work to coders of the right tier, watches every agent, runs checks, sends fixes and reviews, merges; queues every event and wakes the lead when it is idle | Thinks, or decides anything the lead or you should |
@@ -126,7 +126,7 @@ Version choice, first match wins: `--version` flag › `ORCH_VERSION` env › `.
126
126
 
127
127
  You can also start the event manager yourself: `orch autopilot` in a spare terminal. It is the only driver of a run: while it runs, other `orch` commands that would change the run are refused (`orch status`, `orch report`, `orch approve` and the lead's `orch events` / `orch dispatch` / `orch answer` still work).
128
128
  4. **If the lead is away** (its pane is closed, or it never reads its events): nothing is lost, the events wait in the queue. Ready work starts by itself after 15 minutes, you get a desktop notification, and `orch events --peek` shows what is open. With `Lead mode: off` in the plan header there is no lead in the run at all: `orch autopilot` dispatches by itself and stops (exit 3) when it needs you.
129
- 5. **When it's done:** read `.orchestrate/summary.md` and test it. Want a change? Tell the lead (for example "the login button should be blue"). It runs `orch fix M1 "the login button should be blue"`: one small follow-up job goes straight to the coder who built M1, with the check and review as before, and no new plan. You can run `orch fix` yourself too. When you are happy, run `orch finish`. It re-runs the check, removes the worktrees, pushes `feature/<name>` and opens a PR into `main` (with `gh`, or prints the compare link).
129
+ 5. **When it's done:** read `.orchestrate/summary.md` and do its manual checklist. It holds only what needs your eyes or hands (how the UI looks and behaves, a real device); whatever a command or a look at the code can settle, the run and the lead have already checked and listed with the evidence. Want a change? Tell the lead (for example "the login button should be blue"). It runs `orch fix M1 "the login button should be blue"`: one small follow-up job goes straight to the coder who built M1, with the check and review as before, and no new plan. You can run `orch fix` yourself too. When you are happy, run `orch finish`. It re-runs the check, removes the worktrees, pushes `feature/<name>` and opens a PR into `main` (with `gh`, or prints the compare link).
130
130
 
131
131
  ### Git: one branch per run, real commits, one PR
132
132
  Planning touches no git at all. `orch start` creates the plan's `Branch:` (`feature/<slug>`) and that is the only branch a run makes: coders work on detached worktrees, and a milestone's work in progress (under review, parked, waiting for a fix) lives in hidden refs under `refs/orch/`, which `git branch` doesn't list and `git push` doesn't send. Each milestone lands as **one commit whose message says what changed** (the coder's `COMMIT:` line, e.g. `feat(api): add categories endpoint`, with a `Milestone: M2` trailer). `Commits: single` in the plan header squashes the run into one commit at finish.
@@ -157,6 +157,8 @@ Model why: one module, a clear contract, an existing endpoint to copy; no design
157
157
  - **One escalation.** A milestone that runs out of fix or review rounds gets one fresh round on a stronger model, with the work so far, before it fails.
158
158
  - **Policy.** Ultra-premium models (`*fable*`, `*astra*`) are kept out of runs: `orch sync` refuses a plan that names one. Everything else your agents reach is allowed, open-weight models included. Edit `[policy] deny` to change the list.
159
159
  - **Checked against reality.** `summary.md` has a table of planned tier against the model that really did each milestone, and `orch report` shows first-pass rate and escalations per model. When a model does worse than its rating, lower the rating.
160
+ - **A role for every coder.** The lead writes `Role:` on each milestone (for UI work, for example, "senior frontend engineer with a designer's eye: matches the existing components, works on a small screen, has loading, empty and error states"). The coder's task file starts with it, so the coder works to that standard.
161
+ - **Estimate vs actual time.** The lead writes `Estimate:` for each milestone and for the whole feature. orch measures the real time, and the summary shows both. When something took longer, it lists where the time went and who it waited on (for example "10m claude-1 (sonnet): fix rounds: the check command failed" or "20m developer / lead: paused, waiting for an answer"), only from what orch recorded.
160
162
  - **Yours to change.** Add or re-rate models in `~/.config/herdr-orchestra/models.toml` (merged over `models.default.toml`). The default ratings are starting points with their sources, not benchmarks run by this project. A model that is not in the catalog still works; it just has no tier.
161
163
 
162
164
  ### Choose your lead
@@ -233,6 +235,7 @@ When a milestone passes its checks it's saved to its hidden ref and the coder is
233
235
  | Autopilot is killed mid-step | the next run confirms or re-sends an unconfirmed prompt to the same agent, and finishes or undoes a half-done merge |
234
236
  | Lockfiles changed since a folder was set up | the setup command runs again there (and in your main folder before the merge check) |
235
237
  | Risky change (deleted file, migration, CI config, secrets file, unlisted dependency change, very large diff) | the milestone is **held** until you run `orch approve Mn`; the rest keeps going |
238
+ | The wake-up prompt never became a turn for the lead (it sat in the input box, or you were typing there) | sent again after 30s, then 1 min; after 3 tries you get a notification. The event manager does not leave at ALL_DONE before the lead has read the last events |
236
239
  | A coder changes files outside its `Likely files` | listed in the summary (`Scope: strict` sends it back instead) |
237
240
  | An orch step fails for one task | that task is paused with the error; the others keep running |
238
241
  | The final check fails on the branch | stops; the next run re-checks and carries on once it passes |
@@ -243,14 +246,14 @@ When a milestone passes its checks it's saved to its hidden ref and the coder is
243
246
  ### Contracts and reports
244
247
  `plan.md` stays the file you edit. From it `orch` generates a `task.json` for each milestone (numbered acceptance criteria `AC1…`, allowed files, interfaces, the commits of its dependencies). Coders answer with a `result-N.json` (status, commit message, files changed, the check they ran, each criterion met or not), and the reviewer with a `review-N.json` (a verdict per criterion plus findings). The old line formats (`COMMIT:`, `QUESTION:`, `BLOCKER:`) still work as a fallback. The shapes are in [docs/contracts.md](docs/contracts.md).
245
248
 
246
- Every status change is written to `.orchestrate/events.jsonl`, and `orch report [--json]` shows time per milestone, fix/review/conflict rounds, first-pass rate and wasted work, plus how each model did. Tokens and cost appear only when an agent reports `usage` in its result file.
249
+ Every status change is written to `.orchestrate/events.jsonl`, and `orch report [--json]` shows estimated vs actual time (and why anything took longer), time per milestone, fix/review/conflict rounds, first-pass rate and wasted work, plus how each model did. Tokens and cost appear only when an agent reports `usage` in its result file.
247
250
 
248
- Optional plan header lines: `Lead mode: events | off` (default `events` when the plan has a `Lead:` line) · `Scope: warn | strict` · `Risk hold: on | off` · `Budget: 3h` (autopilot stops when its running time is used up) · `Setup inputs: <globs>` (which files mean "run setup again"; default: lockfiles and manifests). Per milestone: `Why separate` (why it is its own milestone; needed when the plan has more than one) · `Tier`, `Needs`, `Model why` (see [Models and tiers](#models-and-tiers)) · `Parallel: allow` lets it run next to a milestone that shares its `Likely files`.
251
+ Optional plan header lines: `Lead mode: events | off` (default `events` when the plan has a `Lead:` line) · `Scope: warn | strict` · `Risk hold: on | off` · `Budget: 3h` (autopilot stops when its running time is used up) · `Estimate: 1h30m` (the lead's estimate for the feature) · `Setup inputs: <globs>` (which files mean "run setup again"; default: lockfiles and manifests). Per milestone: `Why separate` (why it is its own milestone; needed when the plan has more than one) · `Tier`, `Needs`, `Model why` (see [Models and tiers](#models-and-tiers)) · `Estimate: 40m` (dispatch to landed if nothing goes wrong) · `Parallel: allow` lets it run next to a milestone that shares its `Likely files`.
249
252
 
250
253
  ### Commands
251
254
  `orch status` · `orch report` · `orch approve Mn` · `orch models [show|check <id>]` · `orch events [--peek]` · `orch dispatch Mn... [--to <worker>] [--tier <tier>]` · `orch answer Mn "<answer>"` · `orch fix Mn "<change>" [--to <worker>]` · `orch doctor [kind]` · `orch ready` · `orch autopilot` · `orch lead plan|run|check|whoami` · `orch agents [launch <kind> [--model <id>]|sync|check]` · `orch handoff Mn` · `orch needs-fix Mn` · `orch set M3 pending` · `orch park M2 paused "why"` · `orch cooldown claude-1 60` · `orch cleanup` · `orch finish [--no-push]` · `orch version` · `orch` (full help)
252
255
 
253
- Tunables: `ORCH_CODER_BUDGET_MIN` (45) · `ORCH_REVIEW_BUDGET_MIN` (15) · `ORCH_CHECK_TIMEOUT_MIN` (30) · `ORCH_COOLDOWN_MIN` (60) · `ORCH_MAX_TASKS` (unset: no limit) · `ORCH_GONE_COOLDOWN_MIN` (10) · `ORCH_SEND_RETRY_S` (120) · `ORCH_HERDR_TIMEOUT_S` (30) · `ORCH_MAX_LOST` (4) · `ORCH_UNREACHABLE_MIN` (30) · `ORCH_CONFIRM_S` (30) · `ORCH_RISK_MAX_LINES` (1500) · `ORCH_LEAD_WAIT_MIN` (15: ready work the lead hasn't dispatched starts by itself) · `ORCH_LEAD_REWAKE_S` (300) · `ORCH_LEAD_MAX_WAKES` (3) · `ORCH_LEAD_IDLE_MAX_MIN` (720: how long the event manager waits for an answer) · `ORCH_NO_AUTOSTART=1` (the lead's commands never start the event manager)
256
+ Tunables: `ORCH_CODER_BUDGET_MIN` (45) · `ORCH_REVIEW_BUDGET_MIN` (15) · `ORCH_CHECK_TIMEOUT_MIN` (30) · `ORCH_COOLDOWN_MIN` (60) · `ORCH_MAX_TASKS` (unset: no limit) · `ORCH_GONE_COOLDOWN_MIN` (10) · `ORCH_SEND_RETRY_S` (120) · `ORCH_HERDR_TIMEOUT_S` (30) · `ORCH_MAX_LOST` (4) · `ORCH_UNREACHABLE_MIN` (30) · `ORCH_CONFIRM_S` (30) · `ORCH_RISK_MAX_LINES` (1500) · `ORCH_LEAD_WAIT_MIN` (15: ready work the lead hasn't dispatched starts by itself) · `ORCH_LEAD_CONFIRM_S` (30: a wake-up the lead did not pick up is sent again, doubling) · `ORCH_LEAD_REWAKE_S` (300) · `ORCH_LEAD_MAX_WAKES` (3) · `ORCH_LEAD_IDLE_MAX_MIN` (720: how long the event manager waits for an answer) · `ORCH_NO_AUTOSTART=1` (the lead's commands never start the event manager)
254
257
 
255
258
  ## Develop and release
256
259
 
package/VERSION CHANGED
@@ -1 +1 @@
1
- 5.1.0
1
+ 5.3.0
Binary file
package/bin/orch CHANGED
@@ -28,7 +28,9 @@ CONFIRM_S = int(os.environ.get("ORCH_CONFIRM_S", "30")) # a prompt not
28
28
  MAX_LOST = int(os.environ.get("ORCH_MAX_LOST", "4")) # lost attempts (unreachable, gone, rate limit)
29
29
  UNREACHABLE_AFTER = int(os.environ.get("ORCH_UNREACHABLE_AFTER", "3")) # failed prompts in a row before a long bench
30
30
  UNREACHABLE_MIN = int(os.environ.get("ORCH_UNREACHABLE_MIN", "30"))
31
- LEAD_REWAKE_S = int(os.environ.get("ORCH_LEAD_REWAKE_S", "300")) # wake the lead again if it never read its events
31
+ LEAD_REWAKE_S = int(os.environ.get("ORCH_LEAD_REWAKE_S", "300")) # longest wait before a wake-up is sent again
32
+ LEAD_CONFIRM_S = int(os.environ.get("ORCH_LEAD_CONFIRM_S", "30")) # a wake-up the lead did not pick up is sent again after this (doubling)
33
+ LEAD_SETTLE_S = int(os.environ.get("ORCH_LEAD_SETTLE_S", "300")) # at ALL_DONE, stay up this long for the lead to pick up its events
32
34
  LEAD_MAX_WAKES = int(os.environ.get("ORCH_LEAD_MAX_WAKES", "3")) # ...this many times, then tell the developer
33
35
  LEAD_WAIT_S = int(os.environ.get("ORCH_LEAD_WAIT_MIN", "15")) * 60 # ready work the lead never dispatched starts by itself
34
36
  LEAD_IDLE_MAX_S = int(os.environ.get("ORCH_LEAD_IDLE_MAX_MIN", "720")) * 60 # give up waiting for answers after this
@@ -637,6 +639,20 @@ def parse_plan(text):
637
639
  return cfg, tasks
638
640
 
639
641
 
642
+ DUR_RE = re.compile(r"(\d+(?:\.\d+)?)\s*(hours?|hrs|hr|h|minutes?|mins|min|m)", re.I)
643
+
644
+
645
+ def parse_dur(s):
646
+ """`45m`, `1h30m`, `1.5h`, `90 min`, `2 hours` -> seconds; None when empty or not a duration."""
647
+ s = (s or "").strip().lower()
648
+ if not s or s in ("none", "-", "n/a", "unknown"):
649
+ return None
650
+ parts = DUR_RE.findall(s)
651
+ if not parts or DUR_RE.sub("", s).strip(" ,+and") != "":
652
+ return None
653
+ return int(sum(float(n) * (3600 if u.startswith("h") else 60) for n, u in parts))
654
+
655
+
640
656
  def field(t, key, default=""):
641
657
  vals = t["fields"].get(key)
642
658
  return " ".join(vals).strip() if vals else default
@@ -889,6 +905,23 @@ def cmd_sync(args):
889
905
  warns.append(f"the lead runs {models[lead[0]]!r} ({tier_of(lead[0])} tier) — planning and coordination are "
890
906
  f"high-tier work")
891
907
 
908
+ # time estimates: the lead's guess per milestone and for the feature, held against the time orch measures
909
+ estimates = {}
910
+ for t in tasks:
911
+ raw = field(t, "estimate")
912
+ estimates[t["id"]] = parse_dur(raw)
913
+ if raw and estimates[t["id"]] is None and raw.lower() not in ("none", "-", "n/a", "unknown"):
914
+ errors.append(f"{t['id']}: Estimate must look like `40m`, `1h30m` or `2h`, got {raw!r}")
915
+ elif not raw and t["enabled"]:
916
+ warns.append(f"{t['id']} has no `Estimate:` — say how long it should take from dispatch to landed "
917
+ f"(e.g. `Estimate: 40m`), so the summary can compare it with the real time")
918
+ feature_est = parse_dur(get("estimate"))
919
+ if get("estimate") and feature_est is None:
920
+ errors.append(f"Estimate must look like `2h` or `1h30m`, got {get('estimate')!r}")
921
+ elif not get("estimate"):
922
+ warns.append("plan header has no `Estimate:` — how long the whole feature should take, with parallel "
923
+ "milestones counted once (e.g. `Estimate: 2h`)")
924
+
892
925
  # the feature decides how many milestones there are: every split has to say what it buys
893
926
  if len(enabled) > 1:
894
927
  for tid in enabled:
@@ -933,6 +966,7 @@ def cmd_sync(args):
933
966
  "scope": scope,
934
967
  "risk_hold": risk_hold,
935
968
  "budget_s": budget_s,
969
+ "estimate_s": feature_est,
936
970
  "check": get("check command"),
937
971
  "setup": get("setup command", "none"),
938
972
  "reviewer": reviewer,
@@ -989,7 +1023,8 @@ def cmd_sync(args):
989
1023
  "wait": o.get("wait"),
990
1024
  "files": sorted(files[tid]),
991
1025
  "parallel": field(t, "parallel", "").lower().startswith("allow"),
992
- "tier": tiers[tid], "needs": needs[tid], "model_why": field(t, "model why"),
1026
+ "tier": tiers[tid], "needs": needs[tid], "model_why": field(t, "model why"), "role": field(t, "role"),
1027
+ "estimate_s": estimates[tid],
993
1028
  }
994
1029
  if status != st["tasks"][tid]["status"]:
995
1030
  move(st, tid, status, {"skipped": "unticked in plan.md", "needs-answer": "open questions in plan.md"}
@@ -1536,6 +1571,9 @@ def record_attempt(t, outcome, usage=None):
1536
1571
  "secs": max(0, now() - start), "nudges": w.get("nudges", 0), "outcome": outcome}
1537
1572
  if w.get("model"):
1538
1573
  a["model"], a["tier"] = w["model"], w.get("tier")
1574
+ blocked = w.get("blocked_s", 0) + (now() - w["blocked_since"] if w.get("blocked_since") else 0)
1575
+ if blocked:
1576
+ a["blocked_s"] = min(blocked, a["secs"]) # time herdr showed the agent stopped at a prompt in its pane
1539
1577
  if usage:
1540
1578
  a["usage"] = usage
1541
1579
  t.setdefault("attempts", []).append(a)
@@ -1912,6 +1950,11 @@ def cmd_poll(args):
1912
1950
  events.append(f"TIMEOUT {tid} agent={agent} after {age // 60} min")
1913
1951
  continue
1914
1952
  s = herdr_state(agent)
1953
+ if s is not None and word(s, "blocked") and not w.get("blocked_since"):
1954
+ w["blocked_since"], changed = now(), True # stopped at a permission prompt / question
1955
+ elif w.get("blocked_since") and not (s is not None and word(s, "blocked")):
1956
+ w["blocked_s"] = w.get("blocked_s", 0) + now() - w.pop("blocked_since")
1957
+ changed = True
1915
1958
  if s is None:
1916
1959
  events.append(f"GONE {tid} agent={agent}")
1917
1960
  elif word(s, "blocked"):
@@ -2251,6 +2294,8 @@ def cmd_status(args):
2251
2294
  hold = undispatched(st)
2252
2295
  print(f" lead {st['lead']['name']}: {len(unread_events(st))} unread event(s), {len(ev)} open"
2253
2296
  + (f"; waiting for `orch dispatch`: {', '.join(hold)}" if hold else "")
2297
+ + (f"; wake-up sent {lw['n']}x (last {_fmt_secs(now() - lw.get('ts', now()))} ago), not picked up yet"
2298
+ if unread_events(st) and (lw := st.get("lead_wake") or {}).get("n") else "")
2254
2299
  + ("" if driver_alive() else "; the event manager is NOT running (`orch autopilot`)"))
2255
2300
  if all(t["status"] in ("merged", "skipped") for t in st["tasks"].values()):
2256
2301
  print(f"ALL_DONE — run `orch finish` to push {st['branch']} and open a PR into {st.get('base')}")
@@ -2396,7 +2441,14 @@ def cmd_write_task(args):
2396
2441
  secs, glob = plan_sections()
2397
2442
  if tid not in secs:
2398
2443
  die(f"{tid} not found in plan.md")
2399
- parts = [f"# Task {tid}: {t['title']}", "", secs[tid].replace(f"## [x] {tid}:", "Title:", 1), ""]
2444
+ parts = [f"# Task {tid}: {t['title']}", ""]
2445
+ if t.get("role"):
2446
+ parts += ["## Your role", f"For this task you are: **{t['role']}**.",
2447
+ "Work the way that person would. Before you write anything, read the code around the change and "
2448
+ "the patterns it already follows. Then build it to the standard that specialist would put their "
2449
+ "name on: \"the check passes\" is the floor, not the goal. Before you finish, look at your own "
2450
+ "result as that specialist reviewing someone else's work, and fix what they would send back.", ""]
2451
+ parts += [secs[tid].replace(f"## [x] {tid}:", "Title:", 1), ""]
2400
2452
  if glob and glob.lower() not in ("none", "<empty — user may fill in>"):
2401
2453
  parts += ["## Global instructions", glob, ""]
2402
2454
  ctx = []
@@ -2445,7 +2497,7 @@ def task_contract(st, tid):
2445
2497
  "goal": field(pt, "goal"), "why": field(pt, "why"),
2446
2498
  "acceptance_criteria": [{"id": f"AC{i}", "text": c} for i, c in enumerate(items("acceptance criteria"), 1)],
2447
2499
  "files_allowed": t.get("files") or [], "scope": st.get("scope", "warn"),
2448
- "tier": t.get("tier"), "needs": t.get("needs") or [],
2500
+ "tier": t.get("tier"), "needs": t.get("needs") or [], "role": t.get("role") or None,
2449
2501
  "interfaces": items("interfaces"), "constraints": items("constraints"), "out_of_scope": items("out of scope"),
2450
2502
  "depends_on": deps, "check": st["check"], "attempt": t.get("attempt", 0) + 1, "lost_attempts": t.get("lost", 0),
2451
2503
  "previous_work": {"by": t.get("last_worker")} if work_ref(st, tid) else None,
@@ -2595,7 +2647,10 @@ def cmd_fix(args):
2595
2647
  title = f"Fix for {tid}: {text[:60]}" + ("..." if len(text) > 60 else "")
2596
2648
  review = field(src, "review", "no")
2597
2649
  sec = [f"## [x] {new}: {title}", f"Depends on: {tid} (a fix to what {tid} built)",
2598
- f"Why separate: a change the developer asked for after {tid} landed.", f"Review: {review}"]
2650
+ f"Why separate: a change the developer asked for after {tid} landed.", f"Review: {review}",
2651
+ "Estimate: none"]
2652
+ if field(src, "role"):
2653
+ sec.append(f"Role: {field(src, 'role')}")
2599
2654
  if field(src, "likely files"):
2600
2655
  sec.append(f"Likely files: {field(src, 'likely files')}")
2601
2656
  if t.get("tier"):
@@ -2612,7 +2667,7 @@ def cmd_fix(args):
2612
2667
  "status": "pending", "reason": f"fix for {tid}", "worker": None, "dir": None, "attempt": 0, "fix": 0,
2613
2668
  "review_round": 0, "wait": None, "files": list(t.get("files") or []), "parallel": False,
2614
2669
  "tier": t.get("tier"), "needs": [], "model_why": f"a fix to {tid}, for the coder who built it." if t.get("tier") else "",
2615
- "go": True, "fix_of": tid,
2670
+ "go": True, "fix_of": tid, "role": field(src, "role"),
2616
2671
  }
2617
2672
  if who:
2618
2673
  st["tasks"][new]["assign"] = who
@@ -2734,6 +2789,43 @@ def cmd_nudge(args):
2734
2789
  print(f"NUDGED {tid} -> {w['agent']}")
2735
2790
 
2736
2791
 
2792
+ def auto_checked(st, final_ok):
2793
+ """What the run already verified without a person, for the summary: the check command, the reviews, and each
2794
+ acceptance criterion with the coder's and the reviewer's evidence. The lead builds on this, so the manual
2795
+ checklist holds only what a person must look at. Only recorded facts; a criterion nobody gave evidence for says so."""
2796
+ try:
2797
+ _, ptasks = parse_plan((ORCH / "plan.md").read_text())
2798
+ except OSError:
2799
+ ptasks = []
2800
+ out = [f"- Check command `{st['check']}` on the finished branch: {'PASS' if final_ok else 'FAIL'}"]
2801
+ for tid in st["order"]:
2802
+ t = st["tasks"][tid]
2803
+ if t["status"] != "merged":
2804
+ continue
2805
+ pt = next((x for x in ptasks if x["id"] == tid), {"fields": {}})
2806
+ crit = [v.lstrip("- ").strip() for v in pt["fields"].get("acceptance criteria", [])]
2807
+ crit = [v for v in crit if v and v.lower() != "none"]
2808
+ res, _ = read_result(t.get("last_result"))
2809
+ coder = {str(c.get("id")): c for c in (res or {}).get("criteria", []) if isinstance(c, dict)}
2810
+ k = t.get("review_round", 0)
2811
+ rev, _ = read_json(ORCH / "review" / tid / f"review-{k}.json") if k else (None, None)
2812
+ rcrit = rev.get("criteria", []) if isinstance(rev, dict) and isinstance(rev.get("criteria", []), list) else []
2813
+ reviewer = {str(c.get("id")): c for c in rcrit if isinstance(c, dict)}
2814
+ passed = sum(1 for c in t.get("checks") or [] if c.get("ok"))
2815
+ out.append(f"- {tid} \"{t['title']}\": check command passed" + (f" {passed}x" if passed > 1 else "")
2816
+ + (f"; review passed (round {k})" if t.get("review") and k else "; no review planned"))
2817
+ for i, text in enumerate(crit, 1):
2818
+ cid, ev = f"AC{i}", []
2819
+ c, r = coder.get(cid), reviewer.get(cid)
2820
+ if c and c.get("met") is not None:
2821
+ ev.append(f"coder: {'met' if c['met'] else 'NOT met'}" + (f" ({c['evidence']})" if c.get("evidence") else ""))
2822
+ if r and r.get("met") is not None:
2823
+ ev.append(f"reviewer: {'met' if r['met'] else 'NOT met'}" + (f" ({r['note']})" if r.get("note") else ""))
2824
+ out.append(f" - {cid} {text} — " + ("; ".join(ev) if ev else "no evidence recorded: the lead checks it, "
2825
+ "or it goes on the manual list"))
2826
+ return "\n".join(out)
2827
+
2828
+
2737
2829
  RATE_RE = re.compile(r"usage limit|rate.?limit|quota|too many requests|\b429\b|limit reached|try again (in|at)|out of credits",
2738
2830
  re.I)
2739
2831
 
@@ -2792,25 +2884,31 @@ def cmd_autopilot(args):
2792
2884
  park(tid, "failed", reason)
2793
2885
 
2794
2886
  def wake_lead(force=False):
2795
- """Tell the lead it has unread events: only when it is idle, once per batch, again after LEAD_REWAKE_S if it
2796
- never read them (up to LEAD_MAX_WAKES). The events themselves are already safe in state.json."""
2887
+ """Tell the lead it has unread events, and make sure the wake-up became a turn. Sending the prompt proves
2888
+ nothing: it can sit in the pane's input box or collide with what the developer is typing. Only the lead
2889
+ reading its events (`orch events`) counts. A lead that is idle again with the events still unread did not
2890
+ pick the wake-up up, so it is sent again: after LEAD_CONFIRM_S, then twice that, and so on (never longer
2891
+ than LEAD_REWAKE_S), up to LEAD_MAX_WAKES; then the developer is told. A lead herdr can't watch is woken
2892
+ again every LEAD_REWAKE_S. The events themselves are already safe in state.json."""
2797
2893
  s_ = load()
2798
2894
  if not lead_on(s_):
2799
2895
  return
2800
2896
  un = unread_events(s_)
2897
+ lw = s_.get("lead_wake") or {}
2898
+ lead = s_["lead"]["name"]
2801
2899
  if not un:
2900
+ if lw.get("n") and not lw.get("ack"):
2901
+ patch_state(lambda s2: s2.update(lead_wake={**(s2.get("lead_wake") or {}), "ack": True}))
2902
+ say(f"the lead ({lead}) picked up its events")
2802
2903
  return
2803
- lead, newest = s_["lead"]["name"], max(e["id"] for e in un)
2804
- lw = s_.get("lead_wake") or {}
2904
+ newest = max(e["id"] for e in un)
2805
2905
  # a wake the lead has not acted on yet covers newer events too: it reads the whole queue when it comes
2806
2906
  same = any(e["id"] <= lw.get("upto", 0) for e in un)
2807
- if same and (now() - lw.get("ts", 0) < LEAD_REWAKE_S or lw.get("n", 0) >= LEAD_MAX_WAKES):
2808
- if lw.get("n", 0) >= LEAD_MAX_WAKES and now() - lw.get("ts", 0) >= LEAD_REWAKE_S and not lw.get("told"):
2809
- patch_state(lambda s2: s2["lead_wake"].update(told=True))
2810
- say(f"the lead ({lead}) has not read its events after {LEAD_MAX_WAKES} wake-ups — look at its pane, "
2811
- f"or run `orch events --peek` yourself", True)
2907
+ n = lw.get("n", 0) if same else 0
2908
+ if same and now() - lw.get("ts", 0) < lw.get("wait", LEAD_REWAKE_S):
2812
2909
  return
2813
- if watched(s_, lead) and not force:
2910
+ watch = watched(s_, lead)
2911
+ if watch and not force:
2814
2912
  hs = herdr_state(lead)
2815
2913
  if hs is None:
2816
2914
  if not lw.get("gone"):
@@ -2819,19 +2917,31 @@ def cmd_autopilot(args):
2819
2917
  f"for it (`orch events --peek` shows them)", True)
2820
2918
  return
2821
2919
  if word(hs, "working", "blocked"):
2822
- return # busy: the events wait in the queue, one wake when it is idle
2920
+ return # in a turn: the events wait in the queue, one wake when it is idle
2921
+ if n >= LEAD_MAX_WAKES:
2922
+ if not lw.get("told"):
2923
+ patch_state(lambda s2: s2["lead_wake"].update(told=True))
2924
+ say(f"the lead ({lead}) has not read its events after {LEAD_MAX_WAKES} wake-ups — look at its pane "
2925
+ f"(if the wake-up text sits in its input box, press Enter), or tell it: run `orch events`. "
2926
+ f"{len(un)} event(s) wait for it (`orch events --peek` shows them)", True)
2927
+ return
2823
2928
  text = (f"orch: {len(un)} new event(s) in the run on {s_['branch']} need the lead. Run `orch events` and "
2824
2929
  f"handle what it prints, then stop.")
2825
2930
  try:
2826
2931
  deliver(s_, lead, text)
2827
2932
  except DeliveryError as e:
2828
2933
  say(f"could not wake the lead ({lead}): {e} — will retry; the events are kept")
2829
- patch_state(lambda s2: s2.update(lead_wake={"upto": newest, "ts": now() - LEAD_REWAKE_S + SEND_RETRY_S,
2830
- "n": lw.get("n", 0) if same else 0}))
2934
+ patch_state(lambda s2: s2.update(lead_wake={"upto": newest, "ts": now(), "n": n, "wait": SEND_RETRY_S}))
2831
2935
  return
2832
- patch_state(lambda s2: s2.update(lead_wake={"upto": newest, "ts": now(), "n": (lw.get("n", 0) if same else 0) + 1}))
2833
- say(f"woke the lead ({lead}): {len(un)} event(s) — " + ", ".join(
2834
- f"{e['kind']}{' ' + e['task'] if e.get('task') else ''}" for e in un[:6]))
2936
+ wait = min(LEAD_REWAKE_S, LEAD_CONFIRM_S * 2 ** n) if watch else LEAD_REWAKE_S
2937
+ patch_state(lambda s2: s2.update(lead_wake={"upto": newest, "ts": now(), "n": n + 1, "wait": wait}))
2938
+ what = ", ".join(f"{e['kind']}{' ' + e['task'] if e.get('task') else ''}" for e in un[:6])
2939
+ if n:
2940
+ say(f"the lead ({lead}) did not pick up its wake-up (" + ("idle again, " if watch else "")
2941
+ + f"events still unread after {now() - lw.get('ts', now())}s) -> sent it again "
2942
+ f"({n + 1} of {LEAD_MAX_WAKES}): {len(un)} event(s) — {what}")
2943
+ else:
2944
+ say(f"woke the lead ({lead}): {len(un)} event(s) — {what} (sent; it counts once the lead reads them)")
2835
2945
 
2836
2946
  def lead_ready():
2837
2947
  """Ready milestones the lead has not dispatched: tell it once per set; start them ourselves after LEAD_WAIT_S."""
@@ -3221,7 +3331,8 @@ def cmd_autopilot(args):
3221
3331
  sugg += [f"- {k}: {s}" for s in review_findings(k, rnd)[1]]
3222
3332
  if v.get("out_of_scope"):
3223
3333
  scope.append(f"- {k}: {', '.join(v['out_of_scope'])}")
3224
- _, report = run("report", ok=(0, 1, 2))
3334
+ _, report = run("report", "--no-time", ok=(0, 1, 2))
3335
+ timing = "\n".join(time_lines(time_account(load())))
3225
3336
  models = []
3226
3337
  for k, v in tasks.items():
3227
3338
  used = [a for a in v.get("attempts") or [] if a.get("kind") == "coder" and a.get("model")]
@@ -3243,10 +3354,17 @@ def cmd_autopilot(args):
3243
3354
  "## Reviewer suggestions not applied\n" + ("\n".join(sugg) or "none") + "\n\n"
3244
3355
  + ("## Models: planned and actual\n| Milestone | Planned tier | Ran on | Escalated | Why this tier |\n"
3245
3356
  "|---|---|---|---|---|\n" + "\n".join(models) + "\n\n" if models else "") +
3357
+ f"## Time: estimate vs actual\n{timing}\n\n"
3358
+ f"## Checked automatically\nAlready verified by the run; nobody needs to redo these by hand.\n"
3359
+ f"{auto_checked(st, ok)}\n\n"
3246
3360
  f"## Run report\n```\n{report}\n```\n\n"
3247
3361
  + ("## Still to write (the lead was woken to write these)\n" if lead_ else
3248
3362
  "## Still to write (ask the lead: 'use the orch-run skill' to finish the summary)\n") +
3249
- "- Design decisions & study notes\n- Manual verification checklist\n"
3363
+ "- Design decisions & study notes\n"
3364
+ "- Checked by the lead: what you verified yourself by running a command or reading the code, with the "
3365
+ "evidence\n"
3366
+ "- Manual verification checklist: only what a person must see or do (how the UI looks and behaves, a "
3367
+ "real device, an outside account). Nothing a command or a look at the code can settle.\n"
3250
3368
  + ("\nThe summary before this one is in `.orchestrate/summary.prev.md`: carry its notes and checklist "
3251
3369
  "over, and add what the new work changed.\n" if prev.exists() else ""))
3252
3370
  if lead_:
@@ -3260,6 +3378,20 @@ def cmd_autopilot(args):
3260
3378
  wake_lead(force=True)
3261
3379
  say(f"ALL_DONE on {st['branch']} — final check {'PASS' if ok else 'FAIL'}. See .orchestrate/summary.md, "
3262
3380
  f"then run `orch finish` to push {st['branch']} and open a PR into {base}", True)
3381
+ if lead_:
3382
+ # don't leave with a wake-up nobody confirmed: after this exit nothing would send it again
3383
+ end = time.time() + LEAD_SETTLE_S
3384
+ while True:
3385
+ wake_lead()
3386
+ s_ = load()
3387
+ lw_ = s_.get("lead_wake") or {}
3388
+ if not unread_events(s_) or lw_.get("told") or lw_.get("gone"):
3389
+ break
3390
+ if time.time() > end:
3391
+ say(f"the lead ({st['lead']['name']}) still has not read ALL_DONE — tell it: run `orch events`",
3392
+ True)
3393
+ break
3394
+ time.sleep(POLL_STEP_S)
3263
3395
  sys.exit(0 if ok else 3)
3264
3396
  active = [k for k, v in tasks.items() if v["status"] in ACTIVE and v["status"] != "held"]
3265
3397
  ready = [k for k, v in tasks.items() if v["status"] == "pending" and deps_met(st, v)]
@@ -3370,12 +3502,241 @@ def run_report(st):
3370
3502
  return {"branch": st["branch"], "tasks": rows, "totals": tot, "models": list(by_model.values())}
3371
3503
 
3372
3504
 
3505
+ # ---------------------------------------------------------------- estimate vs actual time
3506
+ CODER_JOBS = [ # prompt file -> what the coder was doing (anything but task.md is extra work)
3507
+ ("review-fix", "fixing the reviewer's blockers"),
3508
+ ("integration-fix", "fixing the check that failed once merged onto the branch"),
3509
+ ("criteria-fix", "fix rounds: acceptance criteria not met"),
3510
+ ("scope-fix", "fix rounds: changed files outside Likely files"),
3511
+ ("result-fix", "rewriting a result file orch could not read"),
3512
+ ("conflict", "resolving merge conflicts"),
3513
+ ("fix", "fix rounds: the check command failed"),
3514
+ ]
3515
+
3516
+
3517
+ def _transitions(st):
3518
+ """Every status change of every milestone in this run, oldest first: events.jsonl, or the history in
3519
+ state.json when the log is missing."""
3520
+ since = (st.get("run") or {}).get("started") or 0
3521
+ by = {tid: [] for tid in st["tasks"]}
3522
+ p = ORCH / "events.jsonl"
3523
+ if p.exists():
3524
+ for line in p.read_text().splitlines():
3525
+ try:
3526
+ ev = json.loads(line)
3527
+ except ValueError:
3528
+ continue
3529
+ if ev.get("task") in by and ev.get("ts", 0) >= since:
3530
+ by[ev["task"]].append(ev)
3531
+ for tid, t in st["tasks"].items():
3532
+ if not by[tid]:
3533
+ by[tid] = [dict(h, task=tid) for h in t.get("history") or []]
3534
+ by[tid].sort(key=lambda e: e.get("ts", 0))
3535
+ return by
3536
+
3537
+
3538
+ def _wait_part(st, status, why, agent):
3539
+ """A milestone sat in `status` after it had started: what it was waiting for and on whom. None = busy."""
3540
+ why = why or ""
3541
+ if status == "awaiting-review":
3542
+ return "waiting for the reviewer (busy with other work or unreachable)", st.get("reviewer") or "reviewer"
3543
+ if status == "needs-fix":
3544
+ return "waiting for a free coder to take its fix job", "the coders (all busy)"
3545
+ if status == "paused":
3546
+ return f"paused, waiting for the lead or the developer ({why[:80]})" if why else \
3547
+ "paused, waiting for the lead or the developer", "developer / lead"
3548
+ if status == "needs-answer":
3549
+ return "open questions waiting for the developer's answer", "developer"
3550
+ if status == "held":
3551
+ return "risky change waiting for the developer's `orch approve`", "developer"
3552
+ if status == "failed":
3553
+ return "failed, waiting for the lead to dispatch it again", "lead / developer"
3554
+ if status == "pending":
3555
+ if RATE_RE.search(why):
3556
+ return "agent hit a usage limit: benched, work waited for another coder", agent or "agent"
3557
+ if "disappeared" in why or "gone" in why:
3558
+ return "agent disappeared from herdr: work waited for another coder", agent or "agent"
3559
+ if why.startswith("escalated"):
3560
+ return "waiting for a stronger coder after escalation", "the coders (all busy)"
3561
+ if why.startswith("answered"):
3562
+ return "waiting for the coder to pick up the answer", agent or "coder"
3563
+ return "waiting for a free coder" + (f" ({why[:60]})" if why else ""), "the coders (all busy)"
3564
+ return None
3565
+
3566
+
3567
+ def _who(a):
3568
+ return f"{a.get('agent') or '?'} ({a['model']})" if a.get("model") else (a.get("agent") or "?")
3569
+
3570
+
3571
+ def time_account(st, at=None):
3572
+ """Estimated vs actual time per milestone and for the feature, from what orch recorded: status changes,
3573
+ attempts (who, which model, which job), check times and time agents sat at a prompt. Nothing is guessed:
3574
+ time orch can't place is shown as orch's own steps, and a missing estimate stays missing."""
3575
+ at = at or now()
3576
+ trans, rows = _transitions(st), []
3577
+ for tid in st["order"]:
3578
+ t = st["tasks"][tid]
3579
+ if t["status"] == "skipped":
3580
+ continue
3581
+ evs = trans.get(tid, [])
3582
+ first = next((i for i, e in enumerate(evs) if e.get("to") == "coding"), None)
3583
+ row = {"task": tid, "title": t.get("title", ""), "estimate_s": t.get("estimate_s"), "actual_s": None,
3584
+ "landed": t["status"] == "merged", "start": None, "end": None, "parts": [], "over_s": None}
3585
+ rows.append(row)
3586
+ if first is None:
3587
+ continue
3588
+ start = evs[first]["ts"]
3589
+ end = next((e["ts"] for e in evs[first:] if e.get("to") == "merged"), None)
3590
+ if end is None:
3591
+ end = at
3592
+ parts = {}
3593
+
3594
+ def add(what, who, secs, extra):
3595
+ if secs <= 0:
3596
+ return
3597
+ p = parts.setdefault((what, who), {"what": what, "who": who, "secs": 0, "extra": extra})
3598
+ p["secs"] += secs
3599
+ # waiting: from the status changes
3600
+ for i in range(first, len(evs)):
3601
+ a_, b_ = max(evs[i]["ts"], start), min(evs[i + 1]["ts"] if i + 1 < len(evs) else end, end)
3602
+ w = _wait_part(st, evs[i].get("to"), evs[i].get("why"), evs[i].get("agent"))
3603
+ if w and b_ > a_:
3604
+ add(w[0], w[1], b_ - a_, True)
3605
+ # working: from the attempts
3606
+ esc = next((e["ts"] for e in evs[first:] if (e.get("why") or "").startswith("escalated")), None)
3607
+ built = reviewed = False
3608
+ for a in t.get("attempts") or []:
3609
+ if a.get("start", 0) < start or a.get("start", 0) >= end:
3610
+ continue
3611
+ secs, blocked = a.get("secs", 0), a.get("blocked_s", 0)
3612
+ if blocked:
3613
+ add("stopped at a permission prompt or question in its pane", a.get("agent") or "?", blocked, True)
3614
+ secs -= blocked
3615
+ if a.get("outcome") != "done":
3616
+ why = re.sub(r"^parked as \w[\w-]*:?\s*", "", a.get("outcome") or "")
3617
+ add(f"work cut short ({why[:60] or 'stopped'}); the next attempt carried on from it", _who(a), secs, True)
3618
+ elif a.get("kind") == "reviewer":
3619
+ add("review" if not reviewed else "review again after fixes", _who(a), secs, reviewed)
3620
+ reviewed = True
3621
+ else:
3622
+ f = a.get("file") or "task.md"
3623
+ job = next((d for k, d in CODER_JOBS if f.startswith(k + "-")), None)
3624
+ if job:
3625
+ add(job, _who(a), secs, True)
3626
+ elif esc and a["start"] >= esc:
3627
+ add("building again on a stronger model (escalated)", _who(a), secs, True)
3628
+ else:
3629
+ add("building it", _who(a), secs, False)
3630
+ built = True
3631
+ seen = set()
3632
+ for c in t.get("checks") or []:
3633
+ if start <= c.get("ts", 0) <= end:
3634
+ again = c.get("where") in seen
3635
+ seen.add(c.get("where"))
3636
+ add("checks run again after fixes" if again else "checks", "check command", c.get("secs", 0), again)
3637
+ total = end - start
3638
+ placed = sum(p["secs"] for p in parts.values())
3639
+ add("orch's own steps (setup, prompts, merge)", "orch", max(0, total - placed), False)
3640
+ row.update(start=start, end=end, actual_s=total,
3641
+ parts=sorted(parts.values(), key=lambda p: (p["extra"], -p["secs"])))
3642
+ if row["estimate_s"]:
3643
+ row["over_s"] = total - row["estimate_s"]
3644
+ # the feature: from the first milestone starting to the last one landing; time after every milestone had
3645
+ # landed and before a fix asked with `orch fix` is not counted, time with nothing running is
3646
+ started = sorted((r for r in rows if r["start"]), key=lambda r: r["start"])
3647
+ feat = {"estimate_s": st.get("estimate_s"), "actual_s": None, "over_s": None, "idle_s": 0, "after_done_s": 0,
3648
+ "landed": bool(rows) and all(r["landed"] for r in rows), "why": []}
3649
+ if started:
3650
+ fstart = started[0]["start"]
3651
+ fend = max(r["end"] for r in started)
3652
+ reach, idle, after = started[0]["end"], 0, 0
3653
+ for r in started[1:]:
3654
+ if r["start"] > reach:
3655
+ gap = r["start"] - reach
3656
+ if st["tasks"][r["task"]].get("fix_of") and all(x["landed"] and x["end"] <= reach
3657
+ for x in started if x["start"] < r["start"]):
3658
+ after += gap
3659
+ else:
3660
+ idle += gap
3661
+ reach = max(reach, r["end"])
3662
+ feat.update(actual_s=fend - fstart - after, idle_s=idle, after_done_s=after)
3663
+ if feat["estimate_s"]:
3664
+ feat["over_s"] = feat["actual_s"] - feat["estimate_s"]
3665
+ agg = {}
3666
+ for r in started:
3667
+ for p in r["parts"]:
3668
+ if p["extra"]:
3669
+ k = (p["what"], p["who"])
3670
+ g = agg.setdefault(k, {"what": p["what"], "who": p["who"], "secs": 0, "tasks": []})
3671
+ g["secs"] += p["secs"]
3672
+ g["tasks"].append(r["task"])
3673
+ if idle:
3674
+ agg[("idle", "")] = {"what": "no milestone was running (waiting for the lead's `orch dispatch`, or the "
3675
+ "event manager was stopped)", "who": "lead / event manager", "secs": idle,
3676
+ "tasks": []}
3677
+ feat["why"] = sorted(agg.values(), key=lambda g: -g["secs"])
3678
+ return {"feature": feat, "tasks": rows}
3679
+
3680
+
3681
+ def _dur(s):
3682
+ """Short and readable: 45s, 40m, 1h05m."""
3683
+ if s is None:
3684
+ return "-"
3685
+ s = abs(int(s))
3686
+ if s < 60:
3687
+ return f"{s}s"
3688
+ h, m = divmod(round(s / 60), 60)
3689
+ return f"{h}h{m:02d}m" if h else f"{m}m"
3690
+
3691
+
3692
+ def time_lines(acct):
3693
+ """Estimate vs actual as markdown: a table, then, for whatever took longer than planned, why and who."""
3694
+ f, out = acct["feature"], []
3695
+ est, act = f["estimate_s"], f["actual_s"]
3696
+ head = (f"Whole feature: estimated {_dur(est) if est else 'not given'}, actual "
3697
+ f"{_dur(act) if act is not None else 'not started'}" + ("" if f["landed"] else " so far (not all landed)"))
3698
+ if est and act is not None:
3699
+ head += (f", {_dur(f['over_s'])} longer than estimated" if f["over_s"] > 0 else
3700
+ f", {_dur(f['over_s'])} quicker than estimated" if f["over_s"] < 0 else ", on time")
3701
+ out += [head, "", "| Milestone | Estimate | Actual | Difference | Built by |", "|---|---|---|---|---|"]
3702
+ for r in acct["tasks"]:
3703
+ diff = "-" if r["over_s"] is None else ("on time" if r["over_s"] == 0 else
3704
+ f"{'+' if r['over_s'] > 0 else '-'}{_dur(r['over_s'])}")
3705
+ who = ", ".join(dict.fromkeys(p["who"] for p in r["parts"] if p["what"] == "building it")) or "-"
3706
+ act_ = "not started" if r["actual_s"] is None else _dur(r["actual_s"]) + ("" if r["landed"] else " so far")
3707
+ out.append(f"| {r['task']} | {_dur(r['estimate_s']) if r['estimate_s'] else 'none'} | {act_} | {diff} | {who} |")
3708
+ late = [r for r in acct["tasks"] if r["over_s"] and r["over_s"] > 0]
3709
+ if est and f["over_s"] and f["over_s"] > 0 and f["why"]:
3710
+ out += ["", f"Why the feature took {_dur(f['over_s'])} longer (time added up per milestone; milestones that "
3711
+ "ran side by side overlap, so this can add up to more):"]
3712
+ out += [f"- {_dur(g['secs'])} {g['who']}: {g['what']}"
3713
+ + (f" ({', '.join(dict.fromkeys(g['tasks']))})" if g["tasks"] else "") for g in f["why"]]
3714
+ for r in late:
3715
+ out += ["", f"Why {r['task']} took {_dur(r['over_s'])} longer than its {_dur(r['estimate_s'])} estimate:"]
3716
+ extra = [p for p in r["parts"] if p["extra"]]
3717
+ planned = sum(p["secs"] for p in r["parts"] if not p["extra"])
3718
+ out += [f"- {_dur(p['secs'])} {p['who']}: {p['what']}" for p in extra]
3719
+ if planned > r["estimate_s"]:
3720
+ out.append(f"- the planned work alone took {_dur(planned)}: " + ", ".join(
3721
+ f"{p['what']} {_dur(p['secs'])} ({p['who']})" for p in r["parts"] if not p["extra"])
3722
+ + " (the estimate itself was too low for this work)")
3723
+ if not est and not any(r["estimate_s"] for r in acct["tasks"]):
3724
+ out += ["", "No estimates in plan.md (`Estimate:` in the header and in each milestone), so only the actual "
3725
+ "time is shown."]
3726
+ return out
3727
+
3728
+
3373
3729
  def cmd_report(args):
3374
- """orch report [--json] -> time, rounds, first-pass rate and wasted work for this run."""
3375
- rep_ = run_report(load())
3730
+ """orch report [--json] [--no-time] -> estimated vs actual time (and why it took longer), rounds, first-pass
3731
+ rate and wasted work for this run."""
3732
+ st = load()
3733
+ rep_ = run_report(st)
3376
3734
  if "--json" in args:
3735
+ rep_["time"] = time_account(st)
3377
3736
  print(json.dumps(rep_, indent=2))
3378
3737
  return
3738
+ if "--no-time" not in args:
3739
+ print("Estimate vs actual\n" + "\n".join(time_lines(time_account(st))) + "\n")
3379
3740
  tot = rep_["totals"]
3380
3741
  print(f"{'task':<5} {'status':<15} {'tries':>5} {'fix':>4} {'review':>6} {'confl':>5} {'lost':>4} "
3381
3742
  f"{'agent time':>10} {'wasted':>8} {'checks':>8} first pass")
@@ -3648,7 +4009,7 @@ USAGE = """usage: orch <command> [args]
3648
4009
  sync parse .orchestrate/plan.md -> state.json (validates deps, cycles, overlaps)
3649
4010
  start create/switch to the feature branch (plan `Branch:`); create worker worktrees (worktree mode)
3650
4011
  status table of workers + tasks; prints ALL_DONE or STUCK when relevant
3651
- report [--json] time, rounds, first-pass rate, wasted work (and tokens/cost when agents report them)
4012
+ report [--json] estimate vs actual time (why longer, who), rounds, first-pass rate, wasted work, tokens/cost
3652
4013
  ready free coder slots, FIX jobs (do these first), then READY milestones
3653
4014
  pick <Mn> first available worker for the task (respects Tier, then Prefer), or NONE (exit 3)
3654
4015
  escalate <Mn> [reason] out of rounds: one more go on a stronger model, if the team has one (exit 3 if not)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-orchestra",
3
- "version": "5.1.0",
3
+ "version": "5.3.0",
4
4
  "description": "Orchestrate AI coding agents (Claude Code, Codex, OpenCode, Amp) as one team in Herdr: a lead plans, coders build in parallel, a reviewer checks, you get one PR.",
5
5
  "license": "MIT",
6
6
  "bin": {
package/playbooks/plan.md CHANGED
@@ -8,7 +8,8 @@ Load the `herdr` skill for exact CLI syntax if you have it (otherwise `herdr --s
8
8
  - Research findings go in as **facts**, not instructions:
9
9
  - ✅ "Uploads are handled in `server/routes/upload.ts`; categories live in the `categories` table."
10
10
  - ❌ "Add a `matchCategory()` function to upload.ts that loops over rows."
11
- - You also decide **which level of model each milestone needs** (small, medium or high) and say why (step 6).
11
+ - You give every milestone a **role**: the specialist the coder should work as, and what that specialist cares about here (step 6, Role). That sets the standard, not the method.
12
+ - You also decide **which level of model each milestone needs** (small, medium or high) and say why (step 6), and **how long each milestone and the whole feature should take** (step 6, Estimate).
12
13
  - You never edit application code, and you never prompt worker agents: you hand out work with `orch dispatch`, and the event manager (`orch autopilot`, a plain script) prompts the agents, watches them and wakes you when something needs a decision.
13
14
 
14
15
  Feature request = the user's message that asked you to run this playbook.
@@ -92,6 +93,16 @@ Then:
92
93
  - Don't put everything on `high`: a small model on small work is faster and cheaper, and that is the point. Don't put design work on `small` to save money either: a milestone that runs out of fix rounds is moved up to a stronger model once, and that costs more than starting right.
93
94
  - orch gives a milestone to a free coder of its tier, or a stronger one when none is free; never to a weaker one while a suitable coder exists.
94
95
 
96
+ **Give the coder a role.** Every milestone gets `Role:`: one line naming the specialist this work needs and the two or three things that specialist would care about in THIS milestone. orch puts it at the top of the coder's task file ("For this task you are: …"), so the coder aims at that standard instead of at "the check passes". It says who and how good, never how: no steps, no function names.
97
+ - UI work: `Role: senior frontend engineer with a designer's eye: matches the app's existing components and spacing, works on a small screen, has loading, empty and error states, usable by keyboard`
98
+ - An API: `Role: backend engineer who designs APIs other teams depend on: clear error responses, input validated at the edge, every acceptance criterion covered by a test`
99
+ - A schema change: `Role: database engineer who has been burned by migrations: reversible, safe on a table with real data, no long locks`
100
+ - A bug nobody has diagnosed: `Role: debugging specialist: finds and proves the root cause before changing anything, and leaves a test that fails without the fix`
101
+ - Docs: `Role: technical writer for developers new to this project: short sentences, every command copy-pasteable and tested`
102
+ Write the role from what you learned in research (the design system the app uses, the test style of the module), not a generic title: "senior engineer" alone tells the coder nothing.
103
+
104
+ **Estimate the time.** Every milestone gets `Estimate:` (e.g. `Estimate: 40m`, `Estimate: 1h30m`): how long from dispatch until it has landed if nothing goes wrong, which is the coder building it on the model you picked, the checks, and one review when it has `Review: yes`. Don't add time for fix rounds, questions or waiting: those are exactly what the summary measures against your estimate. The header gets `Estimate:` for the whole feature: milestones that run side by side count once, milestones that wait for another add up (M1 30m, then M2 40m ∥ M3 30m, makes `Estimate: 1h10m`). orch records the real time of every step, and the summary shows estimate vs actual; when a milestone or the feature took longer, it lists where the extra time went and who it was waiting on (a coder's fix rounds, the reviewer, a question waiting for the developer, a permission prompt, a usage limit, a lost agent), using only what orch measured.
105
+
95
106
  ## 7. Choose the isolation mode (ask if the user hasn't said)
96
107
  - **worktree**: needed whenever 2+ milestones are independent. Each coder gets its own folder `../<repo>-wt/<worker>` (on a detached HEAD, no extra branch), so they can't overwrite each other. A coder whose milestone is under review is freed to take other work. Needs a **Setup command** for fresh folders (`npm ci`, `pnpm install`, `flutter pub get`, `go mod download`…). Keep the check command free of fixed ports (no dev server); run e2e after merging.
97
108
  - **shared**: one folder, so one milestone at a time (two agents in one folder would overwrite each other's files and mix their changes). Fine when every milestone depends on the previous one.
@@ -114,6 +125,7 @@ Isolation: worktree | shared
114
125
  Max parallel: <number of coders>
115
126
  Scope: warn | strict
116
127
  Budget: <e.g. 3h — optional>
128
+ Estimate: <how long the whole feature should take, e.g. 1h30m>
117
129
  Lead: lead (<your kind>: <your model>)
118
130
  Workers: claude-1 (claude: sonnet), claude-2 (claude: haiku), codex-1 (codex: gpt-6-sol)
119
131
  Reviewer: reviewer (claude: opus) | none
@@ -132,6 +144,8 @@ Prefer: any | <worker kind> | <worker name>
132
144
  Tier: small | medium | high
133
145
  Needs: <any of: reasoning, coding, architecture, long-context, tool-use, planning, speed>
134
146
  Model why: <one line: what in this milestone makes it that tier>
147
+ Estimate: <e.g. 40m: dispatch to landed if nothing goes wrong>
148
+ Role: <the specialist the coder works as, and what they care about in this milestone>
135
149
  Review: yes | no
136
150
  Likely files: src/a.ts, src/b.ts, src/feature/
137
151
  Parallel: <leave this line out | allow>
@@ -157,10 +171,12 @@ Git: the run makes ONE branch, `Branch:` (use `feature/<slug>`, or `fix/<slug>`
157
171
  Optional header lines: `Scope: strict` sends a milestone back when its coder changes files outside `Likely files` (default `warn`: listed in the summary); `Budget: 3h` stops autopilot when its running time is used up; `Risk hold: off` lets risky changes (deleted files, migrations, CI config, secrets files, unlisted dependency changes, very large diffs) land without `orch approve`; `Setup inputs: <globs>` names the files that mean "run the setup command again" (default: lockfiles and manifests); `Lead mode: off` makes the event manager dispatch by itself and stop for the developer instead of waking you (default with a `Lead:` line: `events`).
158
172
 
159
173
  Rules for every milestone:
160
- - **Acceptance criteria are observable**: "POST /upload returns 400 when the amount column is missing", not "handles errors well". One per line: orch numbers them AC1, AC2… in the milestone's `task.json`, the coder says for each whether it is met, and the reviewer checks each one. A milestone without any gets a warning.
174
+ - **Role**: from step 6, on every milestone. The standard to work to, never a how-to.
175
+ - **Acceptance criteria are observable**: "POST /upload returns 400 when the amount column is missing", not "handles errors well". Prefer criteria a test or a command can prove; say so plainly when one needs a person's eyes ("the upload button matches the other primary buttons, seen in the browser"), because at the end only those go on the developer's manual checklist. One per line: orch numbers them AC1, AC2… in the milestone's `task.json`, the coder says for each whether it is met, and the reviewer checks each one. A milestone without any gets a warning.
161
176
  - **Likely files is the scope**: list every file or folder (`src/feature/`, globs work) the milestone should change, including dependency files (`package.json`, lockfiles) when it adds packages. orch compares the coder's real diff with it, runs milestones that share a listed file one after the other, and holds an unlisted dependency change for approval. `Parallel: allow` lets a milestone run next to one it shares files with (expect a merge conflict).
162
177
  - **Why separate**: from step 4, on every milestone when the plan has more than one. The reason is about the feature (parallel work, a foundation others build on, too big for one sitting), never about filling coders.
163
178
  - **No how**: no code blocks, no function names to create, no numbered implementation steps. `orch sync` warns if it sees them.
179
+ - **Estimate**: from step 6, on every milestone and in the header. `orch sync` refuses a value that is not a time (`40m`, `1h30m`, `2h`) and warns when one is missing.
164
180
  - **Tier, Needs, Model why**: from step 6, on every milestone. The model in `Workers:` is what the pane really runs, never a wish. `orch sync` refuses a denied model and warns when no coder reaches a milestone's tier or the reviewer is weaker than the work.
165
181
  - **Prefer**: a worker kind or name from `Workers:` when a tool (not a model) suits the work better, otherwise `any`. A preference, not a lock; the tier comes first.
166
182
  - **Review**: `yes` for UI, API contracts, auth, payments and schema; `no` for mechanical milestones.
@@ -168,10 +184,10 @@ Rules for every milestone:
168
184
  - Each section must stand alone: autopilot hands it to the coder verbatim, together with the global instructions and the reports of merged dependencies.
169
185
 
170
186
  ## 10. Validate and show the plan
171
- - Run `orch sync`. Fix every ERROR. Fix or consciously accept every WARN: missing dependency reasons, hotspot files in parallel milestones, "how" in a milestone, overlap, a milestone without `Why separate`, independent milestones in shared mode, coders left idle by a fully sequential plan, a tier no coder reaches, a model outside the catalog.
187
+ - Run `orch sync`. Fix every ERROR. Fix or consciously accept every WARN: missing dependency reasons, hotspot files in parallel milestones, "how" in a milestone, overlap, a milestone without `Why separate` or `Estimate`, independent milestones in shared mode, coders left idle by a fully sequential plan, a tier no coder reaches, a model outside the catalog.
172
188
  - Run `orch status`. Show the developer:
173
189
  - the feature breakdown, the milestones with each one's `Why separate`, and the parallel shape (which run together);
174
- - **the team and model table**: each milestone, its tier, which coder and model it will go to, and the `Model why`;
190
+ - **the team and model table**: each milestone, its tier, which coder and model it will go to, the `Model why`, and its estimate, plus the estimate for the whole feature;
175
191
  - the research facts that shaped the plan, and all open questions.
176
192
  - Then say: "Plan written to .orchestrate/plan.md. Edit it if you like: untick `[x]` to skip a milestone, change `Tier` / `Depends on` / `Prefer`, answer open questions under 'Notes from user' and set 'Open questions: - none'. Say **go** (or `/orch-run`, "use the orch-run skill", "Run `orch lead run` and follow it") and I will start the run: I dispatch the milestones, the event manager runs them, and I come back when one finishes, asks a question or needs a decision."
177
193
  - STOP and wait for the developer. Do not dispatch before they say so.
package/playbooks/run.md CHANGED
@@ -5,7 +5,7 @@ Extra user input = whatever the user wrote alongside asking you to run this play
5
5
  A run behaves like a call stack. You **dispatch** work and **pause**. The **event manager** (`orch autopilot`, a plain script with no AI in it) prompts the coders and the reviewer, watches them, runs checks, sends fixes, merges, and keeps every event in a queue on disk. When something needs you (a milestone finished, a coder asked a question, a milestone failed or is held, new work is ready) it **wakes you** with one line: run `orch events`. You handle what it prints and pause again. This repeats until every milestone has landed.
6
6
 
7
7
  - You never watch, wait for or poll the agents. Between wake-ups you do nothing and cost nothing.
8
- - No event is lost while you are paused or busy: it waits in the queue, and you get the whole batch in one wake-up. Reading `orch events` is your acknowledgement.
8
+ - No event is lost while you are paused or busy: it waits in the queue, and you get the whole batch in one wake-up. Reading `orch events` is your acknowledgement, and the only thing that counts as "the lead was woken": if you are idle and the events are still unread, the event manager sends the wake-up again (after 30 seconds, then 1 minute, then it tells the developer). So when the developer talks to you and you have not run `orch events` in this turn, run it before you stop.
9
9
  - Only the event manager sends prompts, moves tasks and merges. Your commands (`orch dispatch`, `orch answer`) are requests it carries out, so two processes never act on the run at once. While it runs, `orch` refuses every other command that would change the run from your shell.
10
10
  - Routine recovery is not your job: a failed check goes back to its coder, a rate-limited or vanished agent is benched and its work moves on, a milestone out of fix rounds gets one fresh round on a stronger model. You hear about results, not about every retry.
11
11
 
@@ -52,9 +52,12 @@ If you changed plan.md by hand, run `orch sync` (it works once the event manager
52
52
  **Red baseline.** The event manager needs the check command to pass before any work. If it says the baseline fails: run the check yourself (`<check cmd> 2>&1 | tail -40`), tell the developer exactly what fails, and propose a narrower `Check command` that passes today and still covers the feature. Write it into the plan header only when the developer agrees, then `orch sync` and dispatch again. Never judge "no new failures" by eye.
53
53
 
54
54
  ## 3. ALL_DONE
55
- 1. The event manager already wrote `.orchestrate/summary.md`: tasks, commits, files changed, files changed outside each milestone's Likely files, reviewer suggestions not applied, **the model table (planned tier, the model that really did the work, escalations)** and the run report (time, rounds, first-pass rate, wasted work, how each model did; `orch report` prints it again).
56
- 2. You add two sections: "Design decisions & study notes" for the developer (include any milestone that needed a stronger model than planned, and what that says about the plan), and a "Manual verification checklist" (`- [ ]` per user-facing behaviour).
57
- 3. Tell the developer: "All tasks landed on <branch>. Review .orchestrate/summary.md and test the checklist. Then run `orch finish`: it re-runs the check, removes the worktrees and hidden refs, pushes <branch> and opens a PR into <base> (`orch finish --no-push` to only clean up)." Run `orch finish` yourself only when the developer says so: it pushes. **STOP.**
55
+ 1. The event manager already wrote `.orchestrate/summary.md`: tasks, commits, files changed, files changed outside each milestone's Likely files, reviewer suggestions not applied, **the model table (planned tier, the model that really did the work, escalations)**, **"Checked automatically"** (the check command on the finished branch, each review, and every acceptance criterion with the coder's and the reviewer's evidence) and the run report (time, rounds, first-pass rate, wasted work, how each model did; `orch report` prints it again).
56
+ 2. You add three sections, in this order:
57
+ - **"Design decisions & study notes"** for the developer (include any milestone that needed a stronger model than planned, and what that says about the plan).
58
+ - **"Checked by the lead"**. Go through every acceptance criterion and every behaviour the feature promised. Whatever can be settled by running a command or by reading the code, YOU settle now, and write one line each with the evidence: the command and its result, or `file:line`. This covers: a criterion "Checked automatically" marks `no evidence recorded` or `NOT met`, "the comment / doc / config says X", "the endpoint returns 400 for Y" (run its test, or read the test that covers it), "the migration adds column Z", "no leftover TODO or debug output". You may run the check command, single tests and read-only commands (`grep`, `git log`, `git diff --stat`), and open the few files you need; you still never edit application code. If a check of yours fails, it is a defect, not a checklist item: tell the developer and offer `orch fix Mn "<what is wrong>"`.
59
+ - **"Manual verification checklist"**: ONLY what a person must see or do, because no command and no reading of code can settle it. That is: how the UI looks (layout, spacing, colours, dark mode, a small screen), how it behaves in a real browser or on a real device (click-through flows, focus, animation, how fast it feels), and anything that needs an outside account or hardware (a real email arriving, a payment in the provider's test mode, a push notification, a printer). Write each item so the developer can do it without reading code: `- [ ] <where to go and what to do> → <what they should see>`. Test for every item: "could I, or a test, have checked this?" If yes, it does not belong here: check it and move it to "Checked by the lead". Never write "review the code", "read the comments", "confirm the tests pass" or "check the function handles X" as a manual item. If nothing needs a person (a pure backend, CLI or docs change), write `Nothing to check by hand: <one line why>` instead of inventing items.
60
+ 3. Tell the developer: "All tasks landed on <branch>. Review .orchestrate/summary.md. I checked <n> things myself; <m> need your eyes (the manual checklist), or: nothing needs checking by hand. Then run `orch finish`: it re-runs the check, removes the worktrees and hidden refs, pushes <branch> and opens a PR into <base> (`orch finish --no-push` to only clean up)." Run `orch finish` yourself only when the developer says so: it pushes. **STOP.**
58
61
  4. **The developer asks for a change after the summary** (for example "the login button should be blue"). Do not plan again. Find the milestone that built that part (the summary's Tasks list and Likely files tell you), then run `orch fix Mn "<the change, in the developer's words>"`. It adds one small follow-up milestone to `plan.md`, sends it straight to the coder who built Mn, and starts the event manager; the check and the review (when Mn had one) still run. Name another coder only when the developer asks: `--to <worker>`. Then **STOP**: you are woken with ALL_DONE again, and the new summary keeps the old one in `.orchestrate/summary.prev.md`, so carry your notes and checklist over and add what changed. Never type into a coder's pane yourself.
59
62
 
60
63
  ## Runs without a lead (`Lead mode: off`)