herdr-orchestra 6.13.0 → 6.17.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,49 @@
2
2
 
3
3
  All notable changes. Versions follow [semantic versioning](https://semver.org).
4
4
 
5
+ ## [6.17.0] - 2026-11-26
6
+
7
+ A compact that ended quickly always gets its line in `orch story` now. Nothing else about compacting changed.
8
+
9
+ Example: `claude-1` finishes M1, gets `/compact`, and is idle again before the event manager looks at it. The next job (M5) was sent at once, and the line `claude-1's chat after M1 is now a short summary (/compact)` was never written (about 1 run in 10 in the tests). Now whichever step sees the compact end first writes that line, exactly once.
10
+
11
+ ### Fixed
12
+ - **The "compact is over" line could go missing.** When the next job reached the agent before the event manager noticed the compact had ended, `orch send` / `orch review` dropped the compact silently. Both now write the story line (`<agent>'s chat after Mn is now a short summary`), and the event manager writes it only when it is the one that ends the compact. The work itself was never affected: the agent was idle and got its job.
13
+ - The test for it no longer depends on timing: section 60 checks the story lines, and a new check sends the next job before the event manager looks (it failed on 6.14.0).
14
+
15
+ ## [6.15.0] - 2026-11-26
16
+
17
+ The lead's questions before planning now open in your agent's own question picker, so you click your answers instead of typing `1 a, 2 both, 3 no`. This works in every agent that has a picker, and chat stays the fallback.
18
+
19
+ Example: `/orch-plan add discounts` in Pi shows `Discount on the whole order or on each item?` with `(a) Whole order [Recommended]`, `(b) Each item` and `Custom answer...`. You pick, the answers are saved to `.orchestrate/questions.md`, and the plan follows straight away.
20
+
21
+ ### Added
22
+ - **Native question rule** in the plan playbook (step 2a), for every lead: use your question picker when you have one (Claude Code `AskUserQuestion`, OpenCode `question`, Codex `request_user_input`, Pi `orch_ask`, Antigravity's picker), save questions and answers to `.orchestrate/questions.md`, and go straight on to the plan. If you close the picker, planning pauses and the lead never guesses. With no picker, the lead asks in chat as before. `grill:` is still one question at a time.
23
+ - **Pi: `orch_ask` tool** in orch's Pi package (Pi has no question tool of its own). It shows one picker per question, marks the suggestion `[Recommended]`, offers a custom answer, and saves the file in the main checkout's `.orchestrate/`, also from a worktree. Escape returns `cancelled`, and a Pi with no screen returns `no_ui`. A second round in the same planning is added to the file, and questions from an earlier plan are replaced.
24
+ - **Codex lead with its picker on.** New registry key `lead_flags`, added only to the lead's start command. For Codex it is `-c features.default_mode_request_user_input=true`, which codex-cli 0.172 lists as an "under development" feature. `orch team codex` and `orch agents launch codex --role lead` include it. Coders and the reviewer never get it, because a picker in an unattended pane would wait for nobody.
25
+
26
+ ### Notes
27
+ - The real pickers were not tried by hand in Claude Code, Codex, OpenCode, Antigravity or Pi. The tests drive `orch_ask` with a stand-in for Pi's screen, and the extension type-checks against `@earendil-works/pi-coding-agent` 1.6.1. Antigravity's picker tool name is not documented, so the rule describes the tool instead of naming it.
28
+ - A Codex lead that is already open keeps working as before: it asks in chat. Start it again with `orch agents launch codex --role lead` to get the picker.
29
+ - `.orchestrate/questions.md` is no longer listed as "a plan file orch does not read" in the views and `orch sync` (orch reads it to tell planning from a run).
30
+
31
+ ## [6.14.0] - 2026-11-26
32
+
33
+ A coder's and the reviewer's chat no longer keeps growing from milestone to milestone. When one is done with a milestone, orch types its tool's `/compact` into its pane while it is idle, so the tool swaps the long chat for a short summary. Every job orch gives an agent is already written down in files (`task.md`, `task.json`, fix and review files), so the next milestone loses nothing it needs.
34
+
35
+ Example: `claude-1` builds M2 and M2 lands. `claude-1` is idle, so orch sends `/compact`. When herdr shows it idle again, it gets `Read .orch-task/M4/task.md ...`. `orch story` reads `the event manager did: claude-1 finished M2: orch sent /compact so its chat does not keep growing`.
36
+
37
+ ### Added
38
+ - **`/compact` between milestones**, on by default for Claude Code, Codex and AGY. orch sends it only while herdr shows the agent idle and it holds no job: as soon as its milestone lands, or just before it starts a different milestone (then that milestone waits until the compact is done). Never in the middle of work, never for a fix or review round of the same milestone, and never for the lead.
39
+ - While it compacts, the agent shows as `compacting` in `orch status`, `orch status --json`, `orch view` and `orch board`, and gets no new work. It is free again once herdr shows it idle for `ORCH_COMPACT_SETTLE_S` (10 s). Still working after `ORCH_COMPACT_MAX_S` (5 min): orch stops waiting and says so.
40
+ - **`orch config compact on|off`** (and `ORCH_COMPACT=0|1`) turns it on or off for this machine. `orch config` shows it.
41
+ - Registry keys **`compact`** (the command, `/compact`) and **`compact_min_version`**. AGY added `/compact` in 1.2.15: an older or unreadable `agy --version` means no compacting, said once in `orch story`, and `orch doctor agy` shows it. OpenCode, amp, Pi and Hermes stay off until their command is checked; `compact = "/compact"` in your `agents.toml` turns it on for a kind, `compact = ""` turns it off.
42
+ - Restart recovery: what each agent's chat holds and a compact in progress are kept across `orch sync` and `orch resume`. A compact that was cut short by a restart does no harm: the agent just gets its next job.
43
+ - Docs: [Compact between milestones](https://herdr-orchestra.vercel.app/docs/agents/#compact-between-milestones), the new keys and variables in Configuration, the command in Commands.
44
+
45
+ ### Not yet tried
46
+ - With real Claude Code, Codex and AGY windows. It was tested with orch's simulated agents and herdr. The command name was checked in each tool's docs (AGY: from 1.2.15).
47
+
5
48
  ## [6.13.0] - 2026-11-26
6
49
 
7
50
  The views no longer pass an old run off as the current one, and orch says when a plan file has a name it does not read.
package/README.md CHANGED
@@ -85,6 +85,7 @@ orch update --check # only say whether a new version is out
85
85
  orch update --version v5.8.0 # install that exact version (this is also how you go back)
86
86
  orch config # auto-update on/off, the installed version, the last check
87
87
  orch config auto-update off # or: on
88
+ orch config compact off # or: on (coders and the reviewer get /compact between milestones)
88
89
  ```
89
90
 
90
91
  - **The check.** At most once a day, at `orch lead plan` or `orch version`, orch asks GitHub for the latest release (3 seconds at most; nothing about you or your project is sent). With no internet it stays silent and asks again the next day. `ORCH_NO_UPDATE_CHECK=1` turns the check off.
@@ -341,6 +342,7 @@ Three views show a run while it goes; none of them changes it.
341
342
  | Attempts keep getting lost (unreachable, gone, rate-limited) | after 4 (`ORCH_MAX_LOST`) the task fails with the history instead of looping |
342
343
  | 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 |
343
344
  | The computer was off, herdr was closed, or the event manager died | `orch status` says so in its first lines. `orch resume` carries on: the time orch was down is not counted against any task, the agents' panes get their names back, unsaved work is saved and the tasks in progress are sent again (see [After a restart](#after-a-restart)) |
345
+ | A coder's or the reviewer's chat keeps growing, milestone after milestone | between milestones, while herdr shows it idle, orch types the tool's `/compact` (Claude Code, Codex, AGY 1.2.15+): its chat becomes a short summary, and `orch story` says so. Never mid-work, never for a fix round of the same milestone, never the lead. `orch config compact off` turns it off |
344
346
  | A milestone is paused or moved while its coder still works | orch presses the agent's interrupt key (Esc; set per agent kind as `interrupt_keys` in the registry), then types the STOP note. The coder shows as `stopping M7` in `orch status` and gets no new work until herdr shows it idle; the event manager presses the key again if it keeps going. `orch free <worker>` frees it once you have checked its pane |
345
347
  | A paused coder keeps writing files | whatever it writes anyway is saved into the milestone the next time the milestone or that folder is used. orch never refuses a task because a folder has unsaved files |
346
348
  | plan.md changed while a coder works on that milestone | its task.md is not rewritten mid-work; `orch sync` warns and says how to send the new text (`orch set Mn paused`, then `orch dispatch Mn`) |
package/VERSION CHANGED
@@ -1 +1 @@
1
- 6.13.0
1
+ 6.17.0
@@ -10,12 +10,19 @@
10
10
  # out when the tool has none or it is unverified, and choose the model inside the tool
11
11
  # effort_flag the launch option that sets how hard the model thinks, with {effort} where the level goes. A model
12
12
  # id written `<model>@<level>` (e.g. gpt-6.2-sol@low) starts on <model> with this option
13
+ # lead_flags optional: options added only to the LEAD's start command (`orch team <kind>`, `orch agents launch
14
+ # <kind> --role lead`), never to coders or the reviewer, whose panes run unattended
13
15
  # launch_needs parts the launch command must keep for orch to work in that tool; `orch doctor` says when your
14
16
  # own launch drops one. In `launch`, {git_dir} is the repo's .git folder (filled in by orch)
15
17
  # herdr_detect herdr can tell idle / working / blocked for it (false: orch relies on the done file only)
16
18
  # interrupt_keys the keys that stop its current step, as `herdr agent send-keys` names them (default ["esc"]).
17
19
  # orch presses them when a milestone is paused or moved while the coder still works, before the
18
20
  # STOP note: a typed message is only read after the current step (agy queues it)
21
+ # compact the command that shrinks the tool's chat to a short summary (e.g. "/compact"). orch types it into a
22
+ # coder's or the reviewer's pane when its milestone is done, before it starts another one, while
23
+ # herdr shows it idle (never the lead). Leave it out (or "") for a tool where it is not known to work
24
+ # compact_min_version the first version of the tool that has that command: an older (or unreadable)
25
+ # `<binary> --version` means no compacting, said once in `orch story`
19
26
  # roles any of "lead", "coder", "reviewer"
20
27
  # skills_dirs global SKILL.md folders the installer may put the orch-plan / orch-run / orch-explain skills into
21
28
  # (first = preferred)
@@ -43,6 +50,7 @@ review_launch = "claude --permission-mode acceptEdits --disallowedTools Edit,Not
43
50
  model_flag = "--model"
44
51
  herdr_detect = true
45
52
  interrupt_keys = ["esc"]
53
+ compact = "/compact"
46
54
  roles = ["lead", "coder", "reviewer"]
47
55
  skills_dirs = ["~/.claude/skills"]
48
56
  skills_one_wins = true
@@ -59,16 +67,20 @@ binary = "codex"
59
67
  # waiting for an approval review.
60
68
  launch = "codex --approve-for-me -c sandbox_workspace_write.network_access=true -c 'sandbox_workspace_write.writable_roots=[\"{git_dir}\"]'"
61
69
  launch_needs = ["sandbox_workspace_write.network_access=true", "sandbox_workspace_write.writable_roots"]
70
+ # The lead only: Codex's question picker (request_user_input) outside Plan mode, so /orch-plan asks its questions
71
+ # in a picker. Coders never get it: a picker in an unattended pane would wait for nobody.
72
+ lead_flags = "-c features.default_mode_request_user_input=true"
62
73
  model_flag = "--model"
63
74
  effort_flag = "-c model_reasoning_effort={effort}"
64
75
  herdr_detect = true
65
76
  interrupt_keys = ["esc"]
77
+ compact = "/compact"
66
78
  roles = ["lead", "coder", "reviewer"]
67
79
  skills_dirs = ["~/.agents/skills", "~/.codex/skills"]
68
80
  skills_reads = ["~/.agents/skills", "~/.codex/skills"]
69
81
  invoke = "$orch-plan <feature> (or: use the orch-plan skill: <feature>)"
70
82
  verified = true
71
- notes = "codex-cli 0.167: --full-auto is gone; --approve-for-me routes approvals to automatic review in the workspace-write sandbox. Reads ~/.codex/skills and ~/.agents/skills (its docs name ~/.agents/skills as the user folder, and say two skills with the same name both show up, so orch keeps one copy). codex-cli 0.172 (checked with `codex sandbox`): in workspace-write, .git is read-only and connecting to a local socket is refused; sandbox_workspace_write.network_access=true lets the herdr socket through (it also allows the internet) and writable_roots with the repo's .git lets git work. Thinking level: -c model_reasoning_effort=low|medium|high|xhigh|max. `codex debug models` lists the models this Codex has (see [discover.codex] in models.default.toml)."
83
+ notes = "codex-cli 0.167: --full-auto is gone; --approve-for-me routes approvals to automatic review in the workspace-write sandbox. Reads ~/.codex/skills and ~/.agents/skills (its docs name ~/.agents/skills as the user folder, and say two skills with the same name both show up, so orch keeps one copy). codex-cli 0.172 (checked with `codex sandbox`): in workspace-write, .git is read-only and connecting to a local socket is refused; sandbox_workspace_write.network_access=true lets the herdr socket through (it also allows the internet) and writable_roots with the repo's .git lets git work. Thinking level: -c model_reasoning_effort=low|medium|high|xhigh|max. `codex debug models` lists the models this Codex has (see [discover.codex] in models.default.toml). codex-cli 0.172 (checked with `codex features list`): default_mode_request_user_input is an 'under development' feature, off by default; -c features.default_mode_request_user_input=true turns it on (request_user_input is refused in `codex exec`)."
72
84
 
73
85
  [amp]
74
86
  binary = "amp"
@@ -116,6 +128,8 @@ binary = "agy"
116
128
  launch = "agy --mode accept-edits"
117
129
  herdr_detect = true
118
130
  interrupt_keys = ["esc"]
131
+ compact = "/compact"
132
+ compact_min_version = "1.2.15"
119
133
  roles = ["lead", "coder", "reviewer"]
120
134
  skills_dirs = ["~/.gemini/config/skills"]
121
135
  invoke = "use the orch-plan skill: <feature>"
Binary file
package/bin/orch CHANGED
@@ -41,6 +41,10 @@ STOP_WAIT_S = float(os.environ.get("ORCH_STOP_WAIT_S", "60")) # `orch stop` wa
41
41
  HALT_WAIT_S = float(os.environ.get("ORCH_HALT_WAIT_S", "5")) # `orch set/park` waits this long for it to go idle
42
42
  HALT_SETTLE_S = float(os.environ.get("ORCH_HALT_SETTLE_S", "10")) # idle at least this long after the stop note
43
43
  HALT_REPEAT_S = float(os.environ.get("ORCH_HALT_REPEAT_S", "90")) # still working after this: interrupt it again
44
+ # a coder or reviewer whose milestone is done gets its tool's compact command (`/compact`), so its chat does not keep
45
+ # growing from milestone to milestone. It counts as busy until herdr shows it idle for COMPACT_SETTLE_S
46
+ COMPACT_SETTLE_S = float(os.environ.get("ORCH_COMPACT_SETTLE_S", "10"))
47
+ COMPACT_MAX_S = float(os.environ.get("ORCH_COMPACT_MAX_S", "300")) # still working after this: stop waiting for it
44
48
  TEAM_CONFIRM_S = float(os.environ.get("ORCH_TEAM_CONFIRM_S", "5")) # `team up` looks again after this: still running?
45
49
  LOG_MAX_B = int(float(os.environ.get("ORCH_LOG_MAX_MB", "2")) * 1024 * 1024) # autopilot.log; one old copy is kept
46
50
  CRASH_KEEP = int(os.environ.get("ORCH_CRASH_KEEP", "20")) # saved agent screens in .orchestrate/crash/
@@ -1666,7 +1670,7 @@ def cmd_sync(args):
1666
1670
  "reviewer_info": ({"kind": rev_kind, "pane": rev_pane, "detect": detect(rev_kind, rev_pane, "Reviewer"),
1667
1671
  "model": models.get(reviewer), "tier": tier_of(reviewer),
1668
1672
  **({k: v for k, v in (old.get("reviewer_info") or {}).items()
1669
- if k in ("cooldown_until", "cooldown_reason") and v is not None}
1673
+ if k in ("cooldown_until", "cooldown_reason", "ctx", "compacting") and v is not None}
1670
1674
  if old.get("reviewer") == reviewer else {})}
1671
1675
  if reviewer else None),
1672
1676
  "reviewer_busy": old.get("reviewer_busy") if old.get("reviewer") == reviewer else None,
@@ -1681,6 +1685,7 @@ def cmd_sync(args):
1681
1685
  "lead_seq": old.get("lead_seq", 0),
1682
1686
  "lead_wake": old.get("lead_wake"),
1683
1687
  "lead_ready_told": old.get("lead_ready_told"),
1688
+ "compact_told": old.get("compact_told") or [],
1684
1689
  "tree_task": old.get("tree_task"),
1685
1690
  "workers": {},
1686
1691
  "order": ids,
@@ -1692,6 +1697,8 @@ def cmd_sync(args):
1692
1697
  "cooldown_reason": ow.get("cooldown_reason", ""),
1693
1698
  **({"off": ow["off"]} if ow.get("off") else {}), # kept until `orch bench <w> on`
1694
1699
  **({"stopping": ow["stopping"]} if ow.get("stopping") else {}), # told to stop
1700
+ **({k: ow[k] for k in ("ctx", "compacting") if ow.get(k)}
1701
+ if ow.get("kind") in (None, kind) else {}), # what its chat holds
1695
1702
  "dir": ow.get("dir"), "setup_done": ow.get("setup_done", False),
1696
1703
  "setup_hash": ow.get("setup_hash"), "delivery_fails": ow.get("delivery_fails", 0),
1697
1704
  "pane": pane, "detect": detect(kind, pane, "Workers"),
@@ -1986,6 +1993,146 @@ def stopping_line(st, name, w):
1986
1993
  f"it gets no new work until herdr shows it idle — `orch free {name}` if you checked its pane)")
1987
1994
 
1988
1995
 
1996
+ # ---------------------------------------------------------------- compacting a coder's or the reviewer's chat
1997
+ # Every job orch gives a coder or the reviewer is written down in files (task.md, task.json, fix and review files),
1998
+ # so the chat itself only holds what the agent did on its LAST milestone. Before the agent starts a different
1999
+ # milestone (and as soon as the milestone it worked on has landed) orch types its tool's compact command
2000
+ # (`/compact` in Claude Code, Codex and AGY): the tool replaces the long chat with a short summary. Only when herdr
2001
+ # shows the agent idle, never while it works, and never the lead. A fix or review round of the SAME milestone keeps
2002
+ # the chat. `orch config compact off` (or ORCH_COMPACT=0) turns it off; `compact = ""` in agents.toml turns it off
2003
+ # for one tool.
2004
+
2005
+ def compact_on():
2006
+ env = os.environ.get("ORCH_COMPACT")
2007
+ if env in ("0", "1"):
2008
+ return env == "1"
2009
+ return settings_load().get("compact", True) is not False
2010
+
2011
+
2012
+ _VERSIONS = {}
2013
+
2014
+
2015
+ def _version_of(binary):
2016
+ """The x.y.z version `<binary> --version` prints, or None (asked once per process)."""
2017
+ if binary not in _VERSIONS:
2018
+ _VERSIONS[binary] = _ask_version(binary)
2019
+ return _VERSIONS[binary]
2020
+
2021
+
2022
+ def _ask_version(binary):
2023
+ try:
2024
+ r = subprocess.run([binary, "--version"], text=True, capture_output=True, timeout=10)
2025
+ except (OSError, subprocess.SubprocessError):
2026
+ return None
2027
+ m = re.search(r"(\d+)\.(\d+)\.(\d+)", (r.stdout or "") + (r.stderr or ""))
2028
+ return tuple(int(x) for x in m.groups()) if m else None
2029
+
2030
+
2031
+ def compact_command(st, kind):
2032
+ """(command, None) when orch can compact this kind of agent, else (None, why). A tool whose registry entry has
2033
+ `compact_min_version` is asked its version (once per process); too old or unknown: no compacting."""
2034
+ if not compact_on():
2035
+ return None, "turned off (`orch config compact on` turns it on)"
2036
+ v = (registry(required=False) or {}).get(kind) or {}
2037
+ cmd = str(v.get("compact") or "").strip()
2038
+ if not cmd:
2039
+ return None, f"{kind} has no compact command in the agent list"
2040
+ need_v = str(v.get("compact_min_version") or "").strip()
2041
+ if need_v:
2042
+ have = _version_of(v.get("binary", kind))
2043
+ want = tuple(int(x) for x in re.findall(r"\d+", need_v)[:3])
2044
+ if not have or have < want:
2045
+ return None, (f"{kind} {'.'.join(map(str, have))} is older than {need_v}, the first version with {cmd}"
2046
+ if have else f"could not read {kind}'s version (`{v.get('binary', kind)} --version`); "
2047
+ f"{cmd} needs {need_v} or newer")
2048
+ return cmd, None
2049
+
2050
+
2051
+ def compact_unsupported(st, name, kind):
2052
+ """Why this agent's chat can't be compacted although its tool has a compact command (an old version), or None."""
2053
+ v = (registry(required=False) or {}).get(kind) or {}
2054
+ if not compact_on() or not str(v.get("compact") or "").strip():
2055
+ return None
2056
+ return compact_command(st, kind)[1]
2057
+
2058
+
2059
+ def compact_agents(st):
2060
+ """(name, info dict, holds a job) for every coder and the reviewer. The lead is never compacted."""
2061
+ out = [(n, w, bool(w.get("task"))) for n, w in st.get("workers", {}).items()]
2062
+ if st.get("reviewer") and st.get("reviewer_info") is not None:
2063
+ out.append((st["reviewer"], st["reviewer_info"], bool(st.get("reviewer_busy"))))
2064
+ return out
2065
+
2066
+
2067
+ def still_compacting(st, name, w=None):
2068
+ """True while an agent that got the compact command may still be compacting: herdr shows it working, or it has
2069
+ been idle for less than COMPACT_SETTLE_S. Such an agent is busy: it gets no new work."""
2070
+ w = w if w is not None else agent_info(st, name)
2071
+ h = (w or {}).get("compacting")
2072
+ if not h or not w.get("detect", True):
2073
+ return False
2074
+ if now() - h.get("ts", 0) > COMPACT_MAX_S:
2075
+ return False
2076
+ s = herdr_state(name)
2077
+ if s is None:
2078
+ return False
2079
+ if busy_word(s):
2080
+ return True
2081
+ return now() - (h.get("idle_since") or h.get("ts", 0)) < COMPACT_SETTLE_S
2082
+
2083
+
2084
+ def compact_due(st, name, w, next_tid=None):
2085
+ """The compact command to send now, or None. Due when the agent's chat holds another milestone than next_tid
2086
+ (or, with no next_tid, a milestone that has landed), it holds no job, and herdr shows it idle."""
2087
+ ctx = w.get("ctx")
2088
+ if not ctx or ctx == next_tid or w.get("compacting") or not w.get("detect", True) or w.get("off"):
2089
+ return None
2090
+ if next_tid is None and (st["tasks"].get(ctx) or {}).get("status", "merged") not in ("merged", "skipped"):
2091
+ return None
2092
+ if w.get("stopping") or cooling(name, w):
2093
+ return None
2094
+ cmd, _ = compact_command(st, w.get("kind"))
2095
+ if not cmd:
2096
+ return None
2097
+ s = herdr_state(name)
2098
+ if s is None or busy_word(s):
2099
+ return None
2100
+ return cmd
2101
+
2102
+
2103
+ def start_compact(st, name, w, cmd, before=None):
2104
+ """Type the compact command into the agent's pane. The caller saves the state. Returns True when it was sent."""
2105
+ after = w.get("ctx")
2106
+ try:
2107
+ deliver(st, name, cmd)
2108
+ except DeliveryError:
2109
+ return False
2110
+ w["compacting"] = {"ts": now(), "after": after, "cmd": cmd, "before": before}
2111
+ story_note(st, f"{name} finished {after}: orch sent {cmd} so its chat does not keep growing"
2112
+ + (f" (before it starts {before})" if before else ""), who="event manager")
2113
+ return True
2114
+
2115
+
2116
+ def end_compact(st, name, w, note=True):
2117
+ """The agent's compact is over: forget it, and say so once in `orch story`. Whichever step sees it first calls
2118
+ this: the event manager (herdr shows the agent idle again) or the next job sent to the agent (`orch send`,
2119
+ `orch review`), so the story line never depends on which of the two came first. Returns the record or None."""
2120
+ h = (w or {}).pop("compacting", None)
2121
+ if not h:
2122
+ return None
2123
+ w["ctx"] = None
2124
+ if note:
2125
+ story_note(st, f"{name}'s chat after {h.get('after') or 'its last milestone'} is now a short summary "
2126
+ f"({h.get('cmd') or '/compact'})", who="event manager")
2127
+ return h
2128
+
2129
+
2130
+ def compacting_line(st, name, w):
2131
+ h = w.get("compacting") or {}
2132
+ return (f"compacting its chat after {h.get('after') or '?'} ({h.get('cmd') or '/compact'}, sent "
2133
+ f"{_fmt_secs(now() - h.get('ts', now()))} ago; it gets new work once herdr shows it idle)")
2134
+
2135
+
1989
2136
  def commit_message(st, tid):
1990
2137
  """Commit message for a landed milestone: the coder's `COMMIT:` line (what changed), else the title.
1991
2138
  The milestone id is a trailer, never the subject."""
@@ -2509,7 +2656,7 @@ def cmd_ready(args):
2509
2656
  slots = 1 # shared mode: a queued fix job IS the active milestone, and it needs a coder
2510
2657
  # only coders herdr can see count as free: a coder with no agent can't take work, whatever its task field says
2511
2658
  present = [n for n, w in st["workers"].items() if not w.get("task") and not w.get("off") and not cooling(n, w)
2512
- and not still_stopping(st, n, w)
2659
+ and not still_stopping(st, n, w) and not still_compacting(st, n, w)
2513
2660
  and (not w.get("detect", True) or w.get("pane") or herdr_state(n) is not None)]
2514
2661
  gone = [n for n, w in st["workers"].items() if not w.get("task") and not w.get("off") and w.get("detect", True)
2515
2662
  and not w.get("pane") and herdr_state(n) is None]
@@ -2535,7 +2682,8 @@ def cooling(name, info):
2535
2682
 
2536
2683
 
2537
2684
  def worker_free(st, name, w):
2538
- if w.get("task") or w.get("off") or cooling(name, w) or still_stopping(st, name, w):
2685
+ if w.get("task") or w.get("off") or cooling(name, w) or still_stopping(st, name, w) \
2686
+ or still_compacting(st, name, w):
2539
2687
  return False
2540
2688
  if not w.get("detect", True): # herdr can't watch it: no task + no cooldown = free
2541
2689
  return True
@@ -2580,6 +2728,15 @@ def cmd_prepare(args):
2580
2728
  f"(or `orch free {worker}` after you checked its pane)")
2581
2729
  sys.exit(3)
2582
2730
  w.pop("stopping", None)
2731
+ if still_compacting(st, worker, w):
2732
+ print(f"BUSY {worker} is {compacting_line(st, worker, w)}")
2733
+ sys.exit(3)
2734
+ squash = None if w.get("task") == tid else compact_due(st, worker, w, tid)
2735
+ if squash and start_compact(st, worker, w, squash, tid):
2736
+ save(st)
2737
+ print(f"BUSY {worker} is compacting its chat after {w['compacting']['after']} first ({squash}); {tid} starts "
2738
+ f"there once herdr shows it idle")
2739
+ sys.exit(3)
2583
2740
  if not holds(st, tid) and free_slots(st) <= 0 and not (st["isolation"] == "shared" and t["status"] in ("conflict", "needs-fix")):
2584
2741
  die("no free slot (max parallel reached)")
2585
2742
  d = Path(w["dir"] or ROOT)
@@ -2802,6 +2959,8 @@ def cmd_send(args):
2802
2959
  "result": str(d / rel / f"result-{k}.json"), "since": now(), "started": now(), "kind": "coder",
2803
2960
  "prompt": text, "nudges": 0, "file": fname, "delivering": True,
2804
2961
  "model": st["workers"][t["worker"]].get("model"), "tier": st["workers"][t["worker"]].get("tier")}
2962
+ end_compact(st, t["worker"], st["workers"][t["worker"]]) # compacted before this job: say so, once
2963
+ st["workers"][t["worker"]]["ctx"] = tid # its chat now holds this milestone (compacted before another)
2805
2964
  save(st)
2806
2965
  try:
2807
2966
  deliver(st, t["worker"], text)
@@ -2895,10 +3054,15 @@ def cmd_review(args):
2895
3054
  die("no reviewer configured")
2896
3055
  ri = st.get("reviewer_info") or {}
2897
3056
  busy = st.get("reviewer_busy") and st["reviewer_busy"] != tid
2898
- if busy or cooling(st["reviewer"], ri):
3057
+ squash = None if busy or cooling(st["reviewer"], ri) or still_compacting(st, st["reviewer"], ri) else \
3058
+ compact_due(st, st["reviewer"], ri, tid)
3059
+ if squash and not start_compact(st, st["reviewer"], ri, squash, tid):
3060
+ squash = None
3061
+ if busy or cooling(st["reviewer"], ri) or still_compacting(st, st["reviewer"], ri):
2899
3062
  move(st, tid, "awaiting-review")
2900
3063
  save(st)
2901
- why = f"is on {st['reviewer_busy']}" if busy else "is benched (cooldown)"
3064
+ why = (f"is on {st['reviewer_busy']}" if busy else "is benched (cooldown)" if cooling(st["reviewer"], ri)
3065
+ else compacting_line(st, st["reviewer"], ri))
2902
3066
  print(f"BUSY reviewer {why}; {tid} queued as awaiting-review")
2903
3067
  sys.exit(3)
2904
3068
  d = task_dir(t, tid)
@@ -2969,6 +3133,9 @@ def cmd_review(args):
2969
3133
  rtext = f"Read {rel}/review-task-{k}.md and do exactly what it says."
2970
3134
  t["review_round"] = k
2971
3135
  st["reviewer_busy"] = tid
3136
+ if st.get("reviewer_info") is not None:
3137
+ end_compact(st, st["reviewer"], st["reviewer_info"])
3138
+ st["reviewer_info"]["ctx"] = tid # its chat now holds this milestone (compacted before another)
2972
3139
  move(st, tid, "reviewing")
2973
3140
  t["wait"] = {"agent": st["reviewer"], "sentinel": str(sentinel), "report": str(rd / f"review-{k}.md"),
2974
3141
  "result": str(rd / f"review-{k}.json"), "since": now(), "started": now(), "kind": "reviewer",
@@ -3150,6 +3317,12 @@ def cmd_poll(args):
3150
3317
  if events:
3151
3318
  print("\n".join(events))
3152
3319
  return
3320
+ # an agent that got /compact and is idle again can take its next milestone now: back to the event manager
3321
+ squashed = [n for n, w, holding in compact_agents(st) if w.get("compacting") and not holding
3322
+ and not still_compacting(st, n, w)]
3323
+ if squashed:
3324
+ print(f"WAITING compacted: {' '.join(squashed)} (free for new work)")
3325
+ sys.exit(10)
3153
3326
  if time.time() >= end:
3154
3327
  running = [f"{tid}:{st['tasks'][tid]['status']}" for tid in st["order"]
3155
3328
  if st["tasks"][tid]["status"] in ("coding", "reviewing", "conflict")]
@@ -3642,7 +3815,9 @@ def cmd_status(args):
3642
3815
  if st.get("mode") == "quick":
3643
3816
  print(f"QUICK RUN because: {st.get('quick_because') or '-'}")
3644
3817
  print(f"branch={st['branch']} base={st.get('base')} isolation={st['isolation']} "
3645
- f"max_parallel={st['max_parallel']} reviewer={st['reviewer']} (busy: {st.get('reviewer_busy')})")
3818
+ f"max_parallel={st['max_parallel']} reviewer={st['reviewer']} (busy: {st.get('reviewer_busy')})"
3819
+ + (f" — reviewer {compacting_line(st, st['reviewer'], st['reviewer_info'])}"
3820
+ if st.get("reviewer") and still_compacting(st, st["reviewer"], st.get("reviewer_info") or {}) else ""))
3646
3821
  vu = view_url()
3647
3822
  print(f"live view: {vu}" if vu else "live view: off — `orch view` shows this run as a picture in your browser")
3648
3823
  for n in run_notices(st):
@@ -3656,6 +3831,7 @@ def cmd_status(args):
3656
3831
  state = ("OFF (" + (w["off"].get("why") or "developer") + ")" if w.get("off") else
3657
3832
  f"coding {w['task']}" if w.get("task") else
3658
3833
  stopping_line(st, n, w) if still_stopping(st, n, w) else
3834
+ compacting_line(st, n, w) if still_compacting(st, n, w) else
3659
3835
  f"benched {cd // 60}m ({w.get('cooldown_reason') or 'cooldown'})" if cd else "free")
3660
3836
  if state == "free" and h == "ok" and w.get("detect", True) and busy_word(herdr_state(n)):
3661
3837
  state = "free, but herdr shows it working: look at its pane before it gets new work"
@@ -5702,6 +5878,71 @@ def _autopilot(args):
5702
5878
  + f". It gets no new work until it is idle; look at its pane (`orch free {n}` once it has "
5703
5879
  f"stopped)", h.get("again", 0) >= 1)
5704
5880
 
5881
+ def _agent_of(s_, name):
5882
+ return s_["workers"].get(name) if name in s_.get("workers", {}) else \
5883
+ (s_.get("reviewer_info") if name == s_.get("reviewer") else None)
5884
+
5885
+ def tend_compacts():
5886
+ """Coders and the reviewer whose milestone landed get their tool's compact command while they are idle and
5887
+ hold no job; one that is compacting is free again once herdr shows it idle (or after COMPACT_MAX_S)."""
5888
+ st_ = load()
5889
+ for n, w, holding in compact_agents(st_):
5890
+ if holding:
5891
+ continue
5892
+ h = w.get("compacting")
5893
+ if h:
5894
+ s = herdr_state(n) if w.get("detect", True) else None
5895
+ busy = s is not None and busy_word(s)
5896
+ if busy and h.get("idle_since"):
5897
+ h["idle_since"] = None
5898
+ elif s is not None and not busy and not h.get("idle_since"):
5899
+ h["idle_since"] = now()
5900
+ late = now() - h.get("ts", 0) > COMPACT_MAX_S
5901
+ done = not still_compacting(st_, n, w)
5902
+
5903
+ ended = {}
5904
+
5905
+ def upd(s_, n=n, idle=h.get("idle_since"), done=done, late=late, busy=busy):
5906
+ a = _agent_of(s_, n)
5907
+ if not a or not a.get("compacting"):
5908
+ return # its next job was sent first: that step already said so
5909
+ if not done:
5910
+ a["compacting"]["idle_since"] = idle
5911
+ return
5912
+ ended["yes"] = end_compact(s_, n, a, note=not (late and busy))
5913
+ if late and busy:
5914
+ story_note(s_, f"{n} was still busy {_fmt_secs(COMPACT_MAX_S)} after {h.get('cmd')}: orch "
5915
+ f"stopped waiting for it", who="event manager")
5916
+ patch_state(upd)
5917
+ if ended:
5918
+ say(f"{n} is still working {_fmt_secs(COMPACT_MAX_S)} after {h.get('cmd')}: look at its pane"
5919
+ if late and busy else f"COMPACTED {n}: its chat after {h.get('after')} is now a short summary",
5920
+ late and busy)
5921
+ continue
5922
+ if not compact_due(st_, n, w):
5923
+ why = w.get("ctx") and w.get("detect", True) and compact_unsupported(st_, n, w.get("kind"))
5924
+ if why and w.get("kind") not in st_.get("compact_told", []):
5925
+ def told(s_, n=n, k=w.get("kind"), why=why):
5926
+ if k not in s_.setdefault("compact_told", []):
5927
+ s_["compact_told"].append(k)
5928
+ story_note(s_, f"{n}'s chat is not compacted: {why}", who="event manager")
5929
+ patch_state(told)
5930
+ say(f"{n}'s chat is not compacted: {why}")
5931
+ continue
5932
+ sent_ = {}
5933
+
5934
+ def go(s_, n=n, ctx=w.get("ctx")):
5935
+ a = _agent_of(s_, n)
5936
+ holds_ = (a or {}).get("task") if n in s_.get("workers", {}) else s_.get("reviewer_busy")
5937
+ if not a or holds_ or a.get("ctx") != ctx or a.get("compacting"):
5938
+ return
5939
+ cmd, _ = compact_command(s_, a.get("kind"))
5940
+ if cmd and start_compact(s_, n, a, cmd):
5941
+ sent_["cmd"] = cmd
5942
+ patch_state(go)
5943
+ if sent_:
5944
+ say(f"{n} finished {w.get('ctx')} and is idle: sent {sent_['cmd']} so its chat does not keep growing")
5945
+
5705
5946
  def dispatch(kind, tid, worker):
5706
5947
  code, prep = run("prepare", tid, worker, ok=(0, 3))
5707
5948
  if code == 3: # the coder is busy after all (still stopping its last milestone): next loop
@@ -5906,6 +6147,7 @@ def _autopilot(args):
5906
6147
  patch_state(lambda s_: (s_["run"].get("manager") or {}).update(procs))
5907
6148
  watch_herdr()
5908
6149
  tend_stops()
6150
+ tend_compacts()
5909
6151
  # 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
5910
6152
  el, last_tick = time.time() - last_tick, time.time()
5911
6153
  asleep = slept()
@@ -6495,6 +6737,7 @@ def launch_cmd(kind, v, model=None, strict=True, role=None, cwd=None):
6495
6737
  """The shell command that starts agent `kind` in a pane, on `model` when given. With strict=False a kind
6496
6738
  without a model_flag starts on its default model instead of failing (the caller says so). role="reviewer"
6497
6739
  uses the kind's `review_launch` when it has one: the same tool with its code-editing tools turned off.
6740
+ role="lead" adds the kind's `lead_flags` (Codex: its question picker, so /orch-plan asks in a picker).
6498
6741
  A model `<id>@<level>` on a kind with an `effort_flag` starts <id> with that thinking level. `cwd` is the
6499
6742
  folder the agent will run in ({git_dir} is filled in from it)."""
6500
6743
  cmd = fill_launch((v.get("review_launch") if role == "reviewer" else None) or v.get("launch")
@@ -6516,6 +6759,8 @@ def launch_cmd(kind, v, model=None, strict=True, role=None, cwd=None):
6516
6759
  cmd += f" {v['model_flag']} {shlex.quote(base)}"
6517
6760
  if effort:
6518
6761
  cmd += " " + v["effort_flag"].replace("{effort}", shlex.quote(effort))
6762
+ if role == "lead" and v.get("lead_flags"):
6763
+ cmd += " " + v["lead_flags"]
6519
6764
  return cmd
6520
6765
 
6521
6766
 
@@ -6603,7 +6848,7 @@ def cmd_team(args):
6603
6848
  f"it, and `orch sync` will say so")
6604
6849
  if top and v.get("model_flag") and "lead" in roles:
6605
6850
  print(f"\nYour own lead pane on the strongest level (start it like this, then write `Lead: lead ({kind}: {top})`):"
6606
- f"\n {launch_cmd(kind, v, top, strict=False)}")
6851
+ f"\n {launch_cmd(kind, v, top, strict=False, role='lead')}")
6607
6852
  print(f"\nCheck these are models your {kind} really reaches (`--models a,b` to choose others).")
6608
6853
  print("\nThese panes don't exist yet. After `orch sync` and `orch start`, `orch team up` opens each one in its "
6609
6854
  "own folder, on its model, and names it.")
@@ -6993,7 +7238,8 @@ def view_events(limit=None):
6993
7238
  return out
6994
7239
 
6995
7240
 
6996
- ORCH_OWN_MD = {"plan.md", "summary.md", "summary.prev.md", "story.md", "pr-body.md", "manual-tests.md"}
7241
+ ORCH_OWN_MD = {"plan.md", "summary.md", "summary.prev.md", "story.md", "pr-body.md", "manual-tests.md",
7242
+ "questions.md"} # questions.md: the lead writes it, orch reads it (asked_before_plan)
6997
7243
 
6998
7244
 
6999
7245
  def other_plan_files(newer_than=0):
@@ -7102,6 +7348,7 @@ def view_model(st=None, recent=40):
7102
7348
  for n, w in st.get("workers", {}).items():
7103
7349
  cd = max(0, w.get("cooldown_until", 0) - t_now)
7104
7350
  state = ("off" if w.get("off") else "stopping" if w.get("stopping") else
7351
+ "compacting" if w.get("compacting") and not w.get("task") else
7105
7352
  (VIEW_WORDS.get(tasks.get(w["task"], {}).get("status"), "working") if w.get("task") else
7106
7353
  f"benched {cd // 60}m" if cd else "free"))
7107
7354
  agents.append({"name": n, "role": "coder", "kind": w.get("kind"), "model": w.get("model"),
@@ -7110,7 +7357,8 @@ def view_model(st=None, recent=40):
7110
7357
  ri = st.get("reviewer_info") or {}
7111
7358
  busy = st.get("reviewer_busy")
7112
7359
  agents.append({"name": st["reviewer"], "role": "reviewer", "kind": ri.get("kind"), "model": ri.get("model"),
7113
- "tier": ri.get("tier"), "task": busy, "state": "reviewing" if busy else "free"})
7360
+ "tier": ri.get("tier"), "task": busy, "state": "reviewing" if busy else
7361
+ "compacting" if ri.get("compacting") else "free"})
7114
7362
  groups = [m["group"] for m in ms]
7115
7363
  run = st.get("run") or {}
7116
7364
  return {
@@ -7743,6 +7991,8 @@ USAGE = """usage: orch <command> [args]
7743
7991
  version print the installed herdr-orchestra version
7744
7992
  update [--check] [--version vX.Y.Z] install the latest release (or that one) and show what is new
7745
7993
  config [auto-update on|off] this machine's settings: keep orch up to date by itself, or only be told
7994
+ config compact on|off a coder or the reviewer gets /compact when its milestone is done (on by default for
7995
+ Claude Code, Codex and AGY 1.2.15+; never the lead). ORCH_COMPACT=0|1 overrides it
7746
7996
  lead plan|run print the lead playbook (any agent can lead: "Run `orch lead plan` and follow it")
7747
7997
  lead plan quick|full the rest of the plan playbook: a quick run's rules, or steps 3-10 of the full process
7748
7998
  lead run --section <EVENT|ALL_DONE|rules> one part of the run playbook (orch events prints these for you)
@@ -7860,7 +8110,7 @@ def sandbox_warnings():
7860
8110
  if out and codex:
7861
8111
  v = (registry(required=False) or {}).get("codex") or {}
7862
8112
  out.append(" Fix: quit this Codex and start it again with orch's command (it opens just those two):\n "
7863
- + launch_cmd("codex", v, None, strict=False, cwd=Path.cwd()) + "\n (`orch agents launch codex "
8113
+ + launch_cmd("codex", v, None, strict=False, role="lead", cwd=Path.cwd()) + "\n (`orch agents launch codex "
7864
8114
  "--role lead --model <id>` adds a model; `orch models` lists them)")
7865
8115
  return out
7866
8116
 
@@ -8390,7 +8640,7 @@ def cmd_agents(args):
8390
8640
  if sub == "launch":
8391
8641
  rest = args[1:]
8392
8642
  model, role = None, None
8393
- use = "usage: orch agents launch <kind> [--model <id>] [--role coder|reviewer]"
8643
+ use = "usage: orch agents launch <kind> [--model <id>] [--role coder|reviewer|lead]"
8394
8644
  if "--model" in rest:
8395
8645
  i = rest.index("--model")
8396
8646
  model = rest[i + 1] if len(rest) > i + 1 else die(use)
@@ -8473,9 +8723,9 @@ def doctor_kind(kind, v, full=True):
8473
8723
  hcmd = v.get("help_cmd") or f"{binary} --help"
8474
8724
  code, help_ = _probe(hcmd)
8475
8725
  flags = []
8476
- for key in ("launch", "review_launch"):
8726
+ for key in ("launch", "review_launch", "lead_flags"):
8477
8727
  try:
8478
- launch = shlex.split(v.get(key) or binary)
8728
+ launch = shlex.split(v.get(key) or binary) if key != "lead_flags" else [binary] + shlex.split(v.get(key) or "")
8479
8729
  except ValueError:
8480
8730
  launch = [binary]
8481
8731
  for f in (tok.split("=")[0] for tok in launch[1:] if tok.startswith("-")):
@@ -8550,6 +8800,10 @@ def cmd_doctor(args):
8550
8800
  continue
8551
8801
  bad = [m for ok, m in res if not ok]
8552
8802
  broken += bool(bad)
8803
+ if str(reg[k].get("compact") or "").strip(): # information only: no compacting is never "broken"
8804
+ cmd, why = compact_command({}, k)
8805
+ res.append((True, f"compact: {cmd} between milestones (coders and the reviewer)" if cmd else
8806
+ f"compact: not sent — {why}"))
8553
8807
  print(f"{'BROKEN' if bad else 'ok':<7} {k}" + ("" if reg[k].get("verified") else " (registry entry unverified)"))
8554
8808
  for ok, m in res:
8555
8809
  print(f" {'ok ' if ok else 'BAD'} {m}")
@@ -9296,7 +9550,7 @@ def cmd_sub(args):
9296
9550
 
9297
9551
 
9298
9552
  def cmd_config(args):
9299
- """orch config -> this machine's settings; orch config auto-update on|off."""
9553
+ """orch config -> this machine's settings; orch config auto-update on|off; orch config compact on|off."""
9300
9554
  if args[:1] == ["auto-update"] and args[1:2] and args[1].lower() in ("on", "off"):
9301
9555
  s = settings_load()
9302
9556
  s["auto_update"] = args[1].lower() == "on"
@@ -9305,13 +9559,28 @@ def cmd_config(args):
9305
9559
  "never during a run" if s["auto_update"] else " — orch only tells you when a new version is out; "
9306
9560
  "update with `orch update`"))
9307
9561
  return
9562
+ if args[:1] == ["compact"] and args[1:2] and args[1].lower() in ("on", "off"):
9563
+ s = settings_load()
9564
+ s["compact"] = args[1].lower() == "on"
9565
+ settings_save(s)
9566
+ print(f"compact: {args[1].lower()}" + (" — a coder or the reviewer gets its tool's compact command "
9567
+ "(/compact) when its milestone is done, before it starts another one" if s["compact"] else
9568
+ " — orch never compacts an agent's chat; the tools still compact by themselves when the chat is full"))
9569
+ return
9308
9570
  if args:
9309
- die("usage: orch config | orch config auto-update on|off")
9571
+ die("usage: orch config | orch config auto-update on|off | orch config compact on|off")
9310
9572
  s = settings_load()
9311
9573
  env = os.environ.get("ORCH_AUTO_UPDATE")
9312
9574
  print(f"auto-update: {'on' if auto_update_on() else 'off'}"
9313
9575
  + (f" (ORCH_AUTO_UPDATE={env} overrides the saved setting)" if env else "")
9314
9576
  + ("" if "auto_update" in s or env else " (never asked: `orch config auto-update on` turns it on)"))
9577
+ cenv = os.environ.get("ORCH_COMPACT")
9578
+ reg = registry(required=False) or {}
9579
+ kinds = [k for k, v in reg.items() if str(v.get("compact") or "").strip()]
9580
+ print(f"compact: {'on' if compact_on() else 'off'}"
9581
+ + (f" (ORCH_COMPACT={cenv} overrides the saved setting)" if cenv in ("0", "1") else "")
9582
+ + (f" — coders and the reviewer on {', '.join(kinds)} get /compact between milestones; "
9583
+ "`orch config compact off` turns it off" if compact_on() and kinds else ""))
9315
9584
  print(f"installed: {installed_version()}" + ("" if release_install() else " (not a release install: no update checks)"))
9316
9585
  lc = int(s.get("last_check") or 0)
9317
9586
  print("last check: " + (time.strftime("%Y-%m-%d %H:%M", time.localtime(lc)) if lc else "never")
@@ -12,12 +12,16 @@
12
12
  // Commands: /orch-mode [panes|subagent] show or switch the mode; `subagent` also sets it up (below)
13
13
  // /orch-setup [--mode panes|subagent] install the `orch` command from this package (needed once)
14
14
  //
15
+ // Tool: orch_ask the lead's clickable questions before it writes the plan (/orch-plan
16
+ // step 2a): one picker per question, answers saved in
17
+ // .orchestrate/questions.md. Pi has no question tool of its own.
18
+ //
15
19
  // Subagent mode is set up from inside Pi, with no terminal step: `/orch-mode subagent` runs
16
20
  // `orch setup --mode subagent` (or this package's installer when orch is missing or old), which writes
17
21
  // ~/.pi/agent/agents/coder.md and reviewer.md and runs `pi install npm:@tintinweb/pi-subagents`. When that install
18
22
  // is new, the command reloads Pi (ctx.reload) so the Agent tool is there at once.
19
23
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
20
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
24
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
21
25
  import { homedir } from "node:os";
22
26
  import { dirname, join, resolve } from "node:path";
23
27
  import { fileURLToPath } from "node:url";
@@ -66,6 +70,83 @@ async function stateFile(pi: ExtensionAPI, cwd: string): Promise<string | undefi
66
70
  return undefined;
67
71
  }
68
72
 
73
+ /** The main checkout's .orchestrate folder (the same place as stateFile(), also from a worktree); cwd's when no git. */
74
+ async function orchestrateDir(pi: ExtensionAPI, cwd: string): Promise<string> {
75
+ try {
76
+ const r = await pi.exec("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd, timeout: 5000 });
77
+ if (r.code === 0 && r.stdout.trim()) return join(dirname(r.stdout.trim()), ".orchestrate");
78
+ } catch {
79
+ // no git: use cwd
80
+ }
81
+ return join(cwd, ".orchestrate");
82
+ }
83
+
84
+ type AskOption = { key: string; label: string; description?: string; recommended?: boolean };
85
+ type AskQuestion = { id: string; question: string; options: AskOption[]; allow_custom?: boolean };
86
+ type AskParams = { title?: string; questions: AskQuestion[] };
87
+ type AskAnswer = { id: string; question: string; key: string; label: string; custom: boolean };
88
+
89
+ const CUSTOM = "Custom answer...";
90
+
91
+ /** orch_ask's parameters, as plain JSON Schema (Pi validates JSON Schema; no typebox import needed). */
92
+ const ASK_SCHEMA = {
93
+ type: "object",
94
+ properties: {
95
+ title: { type: "string", description: 'Short header, e.g. "Decisions before planning"' },
96
+ questions: {
97
+ type: "array",
98
+ minItems: 1,
99
+ maxItems: 8,
100
+ description: "The decisions only the developer can make, asked one after another",
101
+ items: {
102
+ type: "object",
103
+ properties: {
104
+ id: { type: "string", description: "q1, q2, ..." },
105
+ question: { type: "string", description: "One clear question" },
106
+ options: {
107
+ type: "array",
108
+ minItems: 1,
109
+ maxItems: 6,
110
+ items: {
111
+ type: "object",
112
+ properties: {
113
+ key: { type: "string", description: "a, b, c" },
114
+ label: { type: "string", description: "The choice, in a few words" },
115
+ description: { type: "string", description: "Optional: what it means, from what you found" },
116
+ recommended: { type: "boolean", description: "true on your suggested choice (one per question)" },
117
+ },
118
+ required: ["key", "label"],
119
+ },
120
+ },
121
+ allow_custom: { type: "boolean", description: 'Adds "Custom answer..." (default true)' },
122
+ },
123
+ required: ["id", "question", "options"],
124
+ },
125
+ },
126
+ },
127
+ required: ["questions"],
128
+ } as const;
129
+
130
+ function optionLine(o: AskOption): string {
131
+ return `(${o.key}) ${o.label}${o.recommended ? " [Recommended]" : ""}${o.description ? ` - ${o.description}` : ""}`;
132
+ }
133
+
134
+ /** The questions and answers as markdown for .orchestrate/questions.md (questions with choices, then ## Answers). */
135
+ function questionsMarkdown(p: AskParams, answers: AskAnswer[]): string {
136
+ const lines = [`# ${p.title?.trim() || "Questions before planning"}`, ""];
137
+ p.questions.forEach((q, i) => {
138
+ lines.push(`${i + 1}. ${q.question}`);
139
+ for (const o of q.options) lines.push(` ${optionLine(o)}`);
140
+ });
141
+ lines.push("", "## Answers", "");
142
+ answers.forEach((a, i) => lines.push(`${i + 1}. ${a.custom ? a.label : `(${a.key}) ${a.label}`}`));
143
+ return lines.join("\n") + "\n";
144
+ }
145
+
146
+ function textResult(text: string, details: Record<string, unknown>) {
147
+ return { content: [{ type: "text" as const, text }], details };
148
+ }
149
+
69
150
  async function readMode(pi: ExtensionAPI, cwd: string): Promise<{ mode: Mode; from: string }> {
70
151
  const state = await stateFile(pi, cwd);
71
152
  if (state) {
@@ -153,7 +234,77 @@ export default function orchMode(pi: ExtensionAPI) {
153
234
  mode === "subagent"
154
235
  ? "herdr-orchestra (orch) mode: subagent. When you lead an orch run, the coder and the reviewer are Pi subagents (the Agent tool), not herdr panes; `orch lead run` prints the steps."
155
236
  : "herdr-orchestra (orch) mode: panes. When you lead an orch run, coders and the reviewer run in herdr panes; `orch lead run` prints the steps.";
156
- return { systemPrompt: `${event.systemPrompt}\n\n${line}` };
237
+ const ask =
238
+ "When you lead /orch-plan and need decisions only the developer can make, ask them with the orch_ask tool " +
239
+ "(clickable choices, saved to .orchestrate/questions.md). A coder or reviewer never uses it.";
240
+ return { systemPrompt: `${event.systemPrompt}\n\n${line}\n${ask}` };
241
+ });
242
+
243
+ pi.registerTool({
244
+ name: "orch_ask",
245
+ label: "orch ask",
246
+ description:
247
+ "herdr-orchestra lead only, during /orch-plan (plan playbook step 2a): ask the developer the decisions only " +
248
+ "they can make, as clickable choices, before you write .orchestrate/plan.md. Shows one picker per question, " +
249
+ "saves questions and answers to .orchestrate/questions.md, and returns the answers. status `cancelled`: the " +
250
+ "developer stopped; don't guess, say planning is paused until they answer. status `no_ui`: ask in chat instead. " +
251
+ "Coders and reviewers never use it (a coder reports status `question` in its result file).",
252
+ promptSnippet: "orch_ask: the orch lead's clickable questions for the developer before writing the plan",
253
+ parameters: ASK_SCHEMA as any,
254
+ async execute(_id: string, params: AskParams, _signal: AbortSignal | undefined, _onUpdate: unknown, ctx: ExtensionContext) {
255
+ const qs = Array.isArray(params?.questions) ? params.questions : [];
256
+ if (!qs.length) return textResult("orch_ask needs at least one question.", { status: "error" });
257
+ if (!ctx.hasUI) {
258
+ return textResult(
259
+ "status: no_ui. This Pi has no screen for pickers (print or JSON mode). Write the questions to " +
260
+ ".orchestrate/questions.md and ask them in chat, as plan playbook step 2a says.",
261
+ { status: "no_ui" },
262
+ );
263
+ }
264
+ const answers: AskAnswer[] = [];
265
+ for (let i = 0; i < qs.length; i++) {
266
+ const q = qs[i];
267
+ const opts = Array.isArray(q.options) ? q.options : [];
268
+ const choices = opts.map(optionLine);
269
+ if (q.allow_custom !== false) choices.push(CUSTOM);
270
+ const head = (params.title?.trim() || "Decisions before planning") + (qs.length > 1 ? ` (${i + 1} of ${qs.length})` : "");
271
+ const picked: string | undefined = await ctx.ui.select(`${head}\n${q.question}`, choices);
272
+ let answer: AskAnswer | undefined;
273
+ if (picked === CUSTOM) {
274
+ const typed: string | undefined = await ctx.ui.input(q.question, "Your answer");
275
+ if (typed !== undefined && typed.trim()) answer = { id: q.id, question: q.question, key: "custom", label: typed.trim(), custom: true };
276
+ } else if (picked !== undefined) {
277
+ const o = opts[choices.indexOf(picked)];
278
+ if (o) answer = { id: q.id, question: q.question, key: o.key, label: o.label, custom: false };
279
+ }
280
+ if (!answer) {
281
+ return textResult(
282
+ `status: cancelled at question ${i + 1} of ${qs.length} (${q.id}). The developer stopped answering. ` +
283
+ "Don't guess and don't write the plan: tell them planning is paused until they answer, and ask again " +
284
+ "when they say so. Nothing was saved.",
285
+ { status: "cancelled", at: q.id, answers },
286
+ );
287
+ }
288
+ answers.push(answer);
289
+ }
290
+ const dir = await orchestrateDir(pi, ctx.cwd);
291
+ mkdirSync(dir, { recursive: true });
292
+ const file = join(dir, "questions.md");
293
+ const md = questionsMarkdown(params, answers);
294
+ // The same planning (questions.md newer than plan.md: a second round, or `grill:` one at a time): add to it.
295
+ // Otherwise it is from an earlier plan: start the file again.
296
+ const plan = join(dir, "plan.md");
297
+ const samePlanning =
298
+ existsSync(file) && readFileSync(file, "utf8").trim() !== "" && (!existsSync(plan) || statSync(file).mtimeMs > statSync(plan).mtimeMs);
299
+ if (samePlanning) appendFileSync(file, "\n" + md);
300
+ else writeFileSync(file, md);
301
+ const lines = answers.map((a, i) => `${i + 1}. ${a.id}: ${a.custom ? `custom: ${a.label}` : `(${a.key}) ${a.label}`}`);
302
+ return textResult(
303
+ `status: answered. Saved in ${file}. The developer's answers:\n${lines.join("\n")}\n` +
304
+ "Write each answer into the plan where it applies (plan playbook step 2a), then carry on from step 2b.",
305
+ { status: "answered", file, answers },
306
+ );
307
+ },
157
308
  });
158
309
 
159
310
  /** Lines worth showing from installer / `orch setup` output (both can be long). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-orchestra",
3
- "version": "6.13.0",
3
+ "version": "6.17.0",
4
4
  "description": "Orchestrate AI coding agents (Claude Code, Codex, OpenCode, Amp, Pi) as one team: a lead plans, coders build, a reviewer checks, you get one PR. Runs in Herdr panes, or in one Pi window with subagents.",
5
5
  "license": "MIT",
6
6
  "bin": {
package/playbooks/plan.md CHANGED
@@ -37,16 +37,19 @@ Feature request = the user's message that asked you to run this playbook.
37
37
  A wrong guess in the plan is the most expensive mistake in a run: every coder builds on it. So before you write any plan, settle what only the developer can decide.
38
38
  - From your research, list what the code, the docs and the request do NOT settle: business rules ("can a discount bring the total to zero?"), data shapes nobody has defined, auth or security trade-offs, which of two existing patterns to follow, a change to a decision record. Not questions the code answers: look those up yourself.
39
39
  - **Nothing to ask?** Go straight on to step 2b. Don't invent questions.
40
- - **Something to ask?** Write the questions to `.orchestrate/questions.md` and show the developer the same text, **all in one message**: one line each, numbered, with 2 or 3 concrete choices and your own suggestion and why (from what you found). End with: "Answer by number (for example `1 a, 2 both, 3 no`). I write the plan after your answers; nothing runs until you say go." Then **STOP** and wait.
41
- Example:
40
+ - **Something to ask?** Use the **native question rule**: put all the questions in front of the developer at once, each with 2 or 3 concrete choices and your own suggestion and why (from what you found).
41
+ 1. **You have a question picker: use it.** That is any tool of yours that shows the developer clickable choices and returns their pick: `AskUserQuestion` in Claude Code, `question` in OpenCode, `request_user_input` in Codex (orch starts a Codex lead with it turned on), `orch_ask` in Pi (from orch's Pi package), Antigravity's own picker. Choices `(a)`, `(b)`, `(c)`, your suggestion marked recommended (or labelled `(recommended)`), a custom answer allowed. A picker that takes fewer questions than you have (Claude Code takes 4 at a time): ask in two rounds. When the answers come back, write the questions with their choices and the answers under `## Answers` in `.orchestrate/questions.md` (`orch_ask` saves the file itself), then go straight on: no extra message, no waiting.
42
+ 2. **The developer closed the picker without answering** (Escape, `cancelled`): don't guess and don't plan. Say "Planning is paused until you answer these. Say when you are ready, or answer in chat." and **STOP**.
43
+ 3. **No picker, or it can't show here** (headless, `no_ui`, the tool is refused): write the questions to `.orchestrate/questions.md` and show the developer the same text, **all in one message**: one line each, numbered. End with: "Answer by number (for example `1 a, 2 both, 3 no`). I write the plan after your answers; nothing runs until you say go." Then **STOP** and wait.
44
+ Example (the chat form; a picker shows the same question and choices, one at a time):
42
45
  ```
43
46
  Before I plan, 3 questions:
44
47
  1. Discount on the whole order or on each item? (a) whole order (b) each item. I suggest (a): the cart has no per-item price changes today.
45
48
  2. Percent, fixed amount, or both? I suggest both: the admin screen already has a type dropdown.
46
49
  3. Can a discount bring the total to zero? I suggest no: the payment step refuses a zero total.
47
50
  ```
48
- - The developer started the request with `grill:`: ask **one question at a time** instead, each with your suggestion, until nothing is left that only they can decide. Then go on.
49
- - **When the answers come**, add them under `## Answers` in `.orchestrate/questions.md`, then carry on from step 2b. Write each answer into the plan where it applies: the `Constraints` of the milestones it affects, or `## Global instructions` when it affects all of them (e.g. `Decided by the developer: a discount applies to the whole order, never to one item`). The open questions inside milestones (step 9) are only for what still comes up later.
51
+ - The developer started the request with `grill:`: ask **one question at a time** instead (one picker call per question when you have a picker), each with your suggestion, until nothing is left that only they can decide. Then go on.
52
+ - **When the answers come** (from the picker or in chat), make sure they are under `## Answers` in `.orchestrate/questions.md`, then carry on from step 2b. Write each answer into the plan where it applies: the `Constraints` of the milestones it affects, or `## Global instructions` when it affects all of them (e.g. `Decided by the developer: a discount applies to the whole order, never to one item`). The open questions inside milestones (step 9) are only for what still comes up later.
50
53
  - **New words and decisions get written down.** When the feature brings a new name for something (Discount, not coupon or promo), list it under `## Glossary additions` in the plan (`- **Discount**: money taken off an order total, in paise`), and give the milestone that introduces it an acceptance criterion `docs/glossary.md defines Discount`, with `docs/glossary.md` in its Likely files. A decision that will be hard to change later (money in paise, one discount per order) gets a decision record the same way: `docs/adr/<next number>-<short-name>.md records the decision and why`. The coder writes these files; you never do. Skip both in a repo that keeps no glossary or decision records, unless the developer asks.
51
54
 
52
55
  ## 2b. Quick or full: decide from what you found, not from how the request sounds
package/playbooks/run.md CHANGED
@@ -60,7 +60,7 @@ If you changed plan.md by hand, run `orch sync` (it works once the event manager
60
60
 
61
61
  **Swap a coder** (for example, AGY instead of OpenCode): `orch stop` (the event manager finishes its current step and exits; nothing is lost), change `Workers:` in plan.md, `orch sync`, `orch team up`, check that `orch status` shows the new worker as `herdr=ok`, then `orch resume`. Never kill the event manager by hand.
62
62
 
63
- **Move a milestone to another coder** (for example M7 from rs-agy-1 to rs-claude-1): `orch set M7 paused`, then `orch dispatch M7 --to rs-claude-1`. orch presses the old coder's interrupt key and tells it to stop. Tell the developer it has stopped only when `orch status` no longer shows it as `stopping M7`; until then it may still be editing files, and it gets no new work.
63
+ **Move a milestone to another coder** (for example M7 from rs-agy-1 to rs-claude-1): `orch set M7 paused`, then `orch dispatch M7 --to rs-claude-1`. orch presses the old coder's interrupt key and tells it to stop. Tell the developer it has stopped only when `orch status` no longer shows it as `stopping M7`; until then it may still be editing files, and it gets no new work. A coder or the reviewer shown as `compacting` got `/compact` after its last milestone (orch does this by itself between milestones, never mid-work): it takes its next milestone in a minute, nothing to do.
64
64
 
65
65
  **Before `orch dispatch --to <worker>`**, `orch status` must show that worker as `herdr=ok`. dispatch refuses a worker with no agent (`NO AGENT`, `SHELL ONLY`); do what it says (`orch team up`) and try again. If `orch team up` reports `QUIT <worker>`, the agent quit as soon as it started: show the developer the pane and the saved screen it names.
66
66