Envoy-and-orchestrator workflow for Claude Code with Herdr: one envoy session you talk to, an orchestrator that runs role agents in panes, briefs as files…

Orchestrator-plus-team-agents workflow for Claude Code with Herdr. One envoy session you talk to, an orchestrator that runs the team, role agents in panes, briefs as files, open questions as cards, a numbered decisions file, reports by hook. This plugin is the kernel: a project-agnostic process, role definitions, templates, commands, a Claude Code mod, and glue scripts around the Herdr CLI. Everything about a specific repository lives in that repository's overlay.
Requires Claude Code 2.1.292 or newer (the team mod runs on its function hooks; the Team and Questions tabs, the status line and the toast were checked on that build, not on older ones).
/team:init. It speaks when you speak to it, and when the team mod sends it a next-action message about a run change: a card or step that waits on you, the run idle on you for 2 minutes, a blocked worker, the run finished. A step done sends no message of its own, and the message tells only what changed. So when you come back, the pane already says where the run stands and what you do next. It shows the question queue, records your decisions with decide, and passes operational requests to the orchestrator with relay./team:init starts an orchestrator in its own worker tab. It plans, briefs, reads reports, and acts on DECISION and RELAY lines. It never talks to you in chat: anything it needs from you becomes a card. It never does operational work itself - no investigating, testing, browsing, or editing. Every such task goes to an agent.team-start. Every agent is addressed by its Claude session id, never by its herdr name: herdr does not restore names after a restart, session ids survive it.ask tool): context, question, options with cost, a recommendation, what waits, and whether the door is one-way or two-way with an estimate of the rework. A worker parks a two-way card with about an hour of rework or less and continues; it waits on the others. The envoy shows cards grouped by tag, and decide closes one or several with one numbered decision. An urgent card shows as a status line and one toast in the envoy session, and its next-action message goes out at the next check, without the quiet wait.scratchpad/current/, composed by team-brief from templates plus your project overlay. The orchestrator sends the one-line kick-off with the brief_send tool.scratchpad/current/decisions-<ticket>.md) is the single binding source. Every brief reads it first. team-init creates it; after that the envoy is its only writer, through decide.scratchpad/current/reports/<name>-<topic>.md.REPORT lines and new decisions, checks the agents, and sends what it found as one prompt. The envoy half draws the Team and Questions tabs beside the transcript and keeps the urgent badge.The full protocol is the team-orchestration skill. Operational lessons are in its references/lessons.md (not auto-loaded).
Develop against a local checkout:
claude --plugin-dir plugins/team
Or install from the marketplace once published:
/plugin marketplace add abrose/claude-plugins
/plugin install team@abrose-plugins
| Command | Does | |
|---|---|---|
/team:init <ticket> | Run it in the session you talk to: that session becomes the envoy. Archives the previous run, writes the decisions file and the plan file (team-init does it; a ticket must be a plain name such as ABC-123), starts the orchestrator in a worker tab, writes the first roster. The team mod then opens the Team and Questions tabs. Agents are started on demand, not chosen up front. | |
/team:brief <name> <topic> | The orchestrator runs it: compose a brief, fill its task section, send the kick-off with brief_send, note the status line in the plan file. | |
/team:status | Run it in the envoy session. Read the roster (the orchestrator and the workers), read idle agents that owe a report, flag anything that needs you. | |
| `/team:release [name ... | all]` | all (the end of a session) runs in the envoy session; <name> runs in the orchestrator or the envoy session. Clear and close finished agents, then forget their records and index entries; refuse a working one. Never closes the envoy's pane or the pane of the session it runs in. all also clears the mod's state files, but keeps delivered.json so the orchestrator gets no old DECISION line again. |
/team:resurrect | Run it in the envoy session. After a restart, relaunch the orchestrator and the workers that came back without their team flags, resuming their sessions. It starts no agent that has no record. | |
/team-overview | Hide or show the Team and Questions tabs (a mod command; the choice is kept per team). In a herdr pane narrower than 144 columns the tabs wait undrawn; the first call draws them. | |
/team-envoy | Run it in a fresh session you talk to, to make it the envoy of the live run (a mod command). The Team and Questions tabs, the status line and the envoy tools move to this session. If the orchestrator's session is gone, it starts a new orchestrator from zero and says so; a live one is left alone. Without a run it refuses and names /team:init. |
In the Team pane, click an agent row to jump to its herdr pane. With the keyboard: ctrl+x tab focuses the pane, then 1-9 jumps to that agent.
bin/, on PATH when enabled)| Script | Does | ||
|---|---|---|---|
| `team-id slug\ | hash\ | for` | Compute a team id: slug a ticket, or a random hash. |
team-init <ticket> [--envoy-pane <id>] | Refuse a ticket that is not a plain name (exit 2), check the Claude Code version, archive the previous run to scratchpad/.archive/ (refuses while its agents are live), write decisions-<ticket>.md and progress-<ticket>.md from the templates (never overwrites), write the team id and config with this session as envoy_session, seed the safe permission allowlist, record the envoy's tab, start the orchestrator in a worker tab and record its session and tab (team-orch-start), prune stale session index entries. | ||
team-orch-start | Start the run's orchestrator in a new worker tab of the current directory and write its orchestrator_session and orchestrator_tab into the config. team-init and /team-envoy both use it. | ||
team-start <name> <role> | Start a role agent (investigator, implementer, tester or orchestrator) in a pane with a session id it assigns (--session-id), verify its status bar, record it under .team/ with its launch flags, and write its session index entry. The new claude loads the plugin this script came from (--plugin-dir), unless that is an installed copy. --new-tab opens a worker tab with the agent in its root pane. | ||
| `team-brief compose\ | prepare` | Compose a brief from templates + overlay, or prepare its kick-off prompt (update the record, mirror into a worktree, print the prompt). | |
team-slice <branch> <parent> | Create a worktree (with the repo's own worktree_cmd from the overlay; refuses without one) and a Herdr tab for one slice. | ||
team-status | Match herdr agent list to .team/ records by session id into a roster. Each session appears once; the envoy and the calling session never do. | ||
team-resurrect | Relaunch the orchestrator and the workers a herdr restore marked as restored, with their saved flags and the same --plugin-dir rule as team-start. A marked agent /cleared before it ran is adopted: the session its recorded pane runs, when no record claims it, becomes its identity. | ||
team-forget <name> ... | Delete the session index entry and the record .team/<name>.json of each named agent, once its pane is closed (team-release runs it). Keeps both for an agent herdr still lists, and accepts only plain names and plain session ids. | ||
team-release <name> | Release one agent: take the lock .team/releasing/<name> (a held lock exits 5), find its pane by session id now, /clear, close the pane, team-forget. /team:release and the mod's auto-release both run it. A failed step exits 1 with <step>: <reason> on stderr. |
| Role | Agent | Model | Default effort | Read-only |
|---|---|---|---|---|
| investigator | team-investigator | Opus 5.5 | medium | yes (tool filter) |
| implementer | team-implementer | Sonnet 5.5 | medium | no |
| tester | team-tester | Sonnet 5.5 | low | yes, except test files (by rule) |
| orchestrator | team-orchestrator | Opus 5.5 | medium | by rule (never edits, never investigates); started by team-init |
| envoy | team-envoy | Opus 5.5 (fresh session only) | - | In a fresh session started with claude --agent team-envoy: yes (Edit, Write blocked). In your own session after /team:init: no. It keeps every tool and its own model; the prose rule of team-role-envoy is its only guard |
The orchestrator overrides the defaults per job with team-start --model opus-5-5|sonnet-5-5|haiku-5-5 and --effort low|medium|high|xhigh|max. Any other model is refused. Without --effort, haiku-5-5 runs at effort high.
Reviewer and post-notes work run on team-investigator with the brief-review and brief-post-notes templates. Mechanical jobs run on team-implementer with --model haiku-5-5.
/team:init <ticket> assigns the run a short team id (a slug of the ticket) and writes it to .team/config.json. Every agent name becomes <team_id>-<label>; the orchestrator is <team_id>-orch. Init checks the live herdr agent list and, if that name namespace is already taken (for example by a prior run for the same ticket), disambiguates the team id (app-1, then app-1-2, then a random hash). team-start likewise refuses a <team_id>-<label> that a live agent already holds. A team's mod only ever acts on the agents and tabs recorded under its own .team/ directory.
hooks/mod/ is a Claude Code mod in the same plugin. It loads in every session with the plugin enabled and activates per role: the orchestrator half in the session that .team/config.json names as orchestrator_session, the envoy half in the one it names as envoy_session. A config without envoy_session (an older run) runs both halves in the orchestrator session. On session.start it sets TEAM_SESSION_ID, which team-init reads.
Every 15 s the envoy half reads the plan, the cards and the agent rows for the Team and Questions tabs, sets the status line to <n> urgent: ... while an urgent card waits, and toasts each new urgent card once. It also sets the line to run waits on you: <k> open (Q-a, ...), with one toast per episode (every toast stays 30 s), when an open card is all the team waits on for 2 minutes (every worker idle with a fresh report, the orchestrator idle; an urgent badge or a prompt not sent line wins the line). The Questions tab draws a waiting urgent card with a red !. It also lists each idle worker tab in the Team tab as tab <id> idle, consider release (<pane> <status>, ...). It sends no prompt.
Every 15 s the orchestrator half:
session to a herdr agent and writes a moved pane id back to the record, so pane ids heal after a restart;.team/delivered.json and sends their REPORT lines (the first activation only sets the marks), and sends a DECISION line for each new decision the envoy recorded;WATCH line for a transition into blocked (with the dialog's first line), and for an agent that has been quiet for 2 minutes without a report, once per quiet spell. Quiet means idle or done in herdr, or no new turn in its transcript since its last stop. A report counts only when the report file holds a REPORT line and is newer than the brief;team-start has not marked it pending; never touches the orchestrator's own tab (the one herdr shows it in, and orchestrator_tab in the config) or the envoy's (envoy_tab), which team-init records;idle or done with a fresh report for 30 minutes (the timer resets on working or blocked), when it has no open or assumed card and its pane is in a team tab (one team-start made, listed in tabs.json) that is not the orchestrator's, the envoy's or the human's. It runs team-release <name> (the script /team:release <name> runs too: /clear, close the pane, team-forget), then sends released <name> (<pane>) after 30 min idle. A step that fails sends WATCH <name>: auto-release failed at <step>: <reason> and is not tried again until the agent worked, blocked or lost its report, or herdr was down (then after a fresh 30 minutes). An agent without a report is never released;WATCH herdr unreachable: <reason> while herdr is down.All lines of one tick go out as one prompt (REPORT lines first, then DECISION, then WATCH and the released lines), which waits until the orchestrator is idle and never touches a draft you are typing.
The brief_send tool (mcp__team__brief_send) sends a kick-off by session id. It works only in the orchestrator session; elsewhere (a worker, the envoy, another repo) it refuses.
The card tools are ask, queue, decide and relay:
| Tool | Where | Does |
|---|---|---|
ask | orchestrator and workers (not the envoy, except in a run with one session) | File a card. Returns Q-<n>; the worker names it in its REPORT. |
queue | envoy | List open and assumed cards grouped by tag, most pressing first. |
decide | envoy | Close cards with one numbered decision (appended to the decisions file), or mark them obsolete. Lists in overrides the assumed cards the answer changes. |
relay | envoy | Send an operational request to the orchestrator as a RELAY line. Refuses a text equal to the last one sent. |
Auto mode reviews that send as a SendMessage with no user request behind it, so its classifier gives no verdict; team-init therefore adds SendMessage to permissions.allow in .claude/settings.local.json, which decides it without the classifier. Remove that entry if you want to approve each send yourself. When the agent got a brief in its current session and was neither cleared nor compacted since, it waits up to 6 s for a /clear or /compact to land, then refuses.
A run started before 0.6.0 has no envoy_session in its config. It keeps working: the orchestrator session holds both roles, shows the Team and Questions tabs, and can call queue and decide itself. relay refuses there, because no separate envoy exists. Start the next run with /team:init to get the envoy and the orchestrator in separate sessions.
A team started before 0.5.0 has no orchestrator_session in its config, so the mod stays inactive for it and nothing delivers its REPORT lines; team-status warns about it. Finish such a run by reading reports/ by hand, or start a new run with /team:init.
A project provides zero or more of these under its own repository. The kernel runs with an empty overlay; a missing file it would have used produces one warning.
| Path | Used by | Content |
|---|---|---|
.claude/team/project.yaml | team-slice, /team:release, brief compose | stacked, spdd, worktree_cmd (required by team-slice), worktree_dir (required by team-slice), release_check, gate_cmd |
.claude/team/env.md | brief compose ("Environment") | how to run and test locally; a "Slice kick-off" checklist |
.claude/team/gate.md | brief compose ("Gate") | test command, lint, the greps a delivery must pass |
.claude/team/tracker.md | analysis and post-notes briefs | ticket system and hygiene rules |
.claude/team/roles/<role>.md | brief compose | extra brief sections for one role in this repo |
.claude/skills/project-<role>/SKILL.md | agent preload | standing rules for one role in this repo |
All under $TEAM_SCRATCH (default scratchpad/current/, git-ignored). /team:init archives the previous run and loose scratchpad entries to scratchpad/.archive/. decisions-<ticket>.md, progress-<ticket>.md, orchestration-decisions.md, brief-<name>-<topic>.md, reports/<name>-<topic>.md, .team/<name>.json, .team/config.json, .team/tabs.json, .team/watch-state.json, .team/layout-flags.json, .team/delivered.json, .team/toasted.json (ids of urgent cards seen or toasted, plus the stall: timer and stall-toast: marks of the stall flag), .team/last-relay.txt (the last relayed text and its orchestrator session), .team/next-action.json (the marks of the next-action message), .team/denials/ (one <name>.json per agent with its last auto-mode denial), .team/questions/ (one Q-<n>.json per card, and claims/), .team/decisions/ (one <n>.json per decision, which the orchestrator's tick reads), .team/stops/, .team/restored/, .team/roster.md.
One file lives outside the run dir: the session index, ${TEAM_INDEX_DIR:-${CLAUDE_CONFIG_DIR:-~/.claude}/team/sessions}/<session>.json ({ "scratch", "name" } per agent). It follows the Claude Code profile, and team-start passes its caller's CLAUDE_CONFIG_DIR to the agent's pane. The envoy's team-init starts the orchestrator, and the orchestrator starts the workers, so a team runs in one profile.
The Stop hook finds its agent in this order:
TEAM_NAME and an absolute TEAM_SCRATCH in its own environment. team-start stamps both onto the agent's pane; they survive /clear but not a restart.session_id through the session index, then the record, whose session must match.Neither: the hook exits silently (any non-team session). A SessionStart hook keeps the identity current: on /clear (a new session id in the same process) it moves the record's session and the index entry to the new id; on a resume without TEAM_NAME (a herdr restore) it marks the worker in .team/restored/ for /team:resurrect. The mod follows the /clear of the orchestrator session and of the envoy session the same way, through session.end.
python3 -m unittest discover -s plugins/team/tests
claude plugin test plugins/team
The bash tests put a shim directory on PATH that exposes tests/fake-herdr as herdr, tests/fake-git as git and tests/fake-claude as claude. They record every invocation and answer with canned output, so the scripts run against a real (fake) CLI, never a mock. The mod tests (tests/mod/) answer each engine call the mod makes from an in-memory world (tests/mod/world.ts): files, herdr output, store, env, clock.
MIT. See LICENSE.
hooks/mod/team.tsx 582 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3import type { TeamAgentRow, TeamCard, TeamPlan } from '../../types'
4import { activeConfig, envoyConfig, noteClear, sessionRole } from './activation'
5import type { TeamConfig } from './activation'
6import { badgeText, freshStall, freshUrgent, pickStatus, stallIds, TOAST_MS, toastText } from './badge'
7import { BRIEF_TOOL, BRIEF_TOOL_SPEC, briefSend } from './brief'
8import { logReceived } from './inbox'
9import { readJson, writeJson } from './io'
10import type { Io } from './io'
11import { bySession, herdrAgents, herdrFocus } from './herdr'
12import type { HerdrListing } from './herdr'
13import { closeHides, drawPane, drawQuestions, hiddenKey, pruneExpanded, QUESTIONS_PANE, TEAM_PANE } from './pane'
14import { mainCheckout, runDir, teamDir } from './paths'
15import { parsePlan } from './plan'
16import { pluginVersion } from './version'
17import { DECIDE_TOOL_SPEC, decideTool, QUEUE_TOOL_SPEC, queueTool } from './decide'
18import { recordDenial } from './denial'
19import { gatherInput, markShown, noteTurnEnd, noteTurnStart, pushNextAction, resetNextAction } from './next-action-push'
20import { closeStalePromptCards } from './prompt-cards'
21import { resetHolds } from './prompt-hold'
22import { ASK_TOOL_SPEC, askTool, readCards } from './questions'
23import { reattach } from './reattach'
24import { RELAY_TOOL_SPEC, relayTool } from './relay'
25import { pickDecisions } from './decisions'
26import { numberMark } from './reports'
27import {
28 clearResetState, compactWhenIdle, noteMainTurn, nudgeLines, onCompacted, RESET_TOOL, RESET_TOOL_SPEC, RESUME_LINE,
29 resetSelf, withHandoverInstructions,
30} from './reset'
31import type { ResetPort } from './reset'
32import {
33 agentRows, idleTabRows, newReportLines, readLedger, readRecords, stallWorkers, syncPanes, watchTick,
34} from './tick'
35import type { TeamRecord } from './tick'
36
37export const TICK_MS = 15000
38const active = atom({ plugin: 'team', key: 'active' } as const, false)
39const agents = atom({ plugin: 'team', key: 'agents' } as const, [] as TeamAgentRow[])
40const idle = atom({ plugin: 'team', key: 'idleTabs' } as const, [] as string[])
41const plan = atom({ plugin: 'team', key: 'plan' } as const, null as TeamPlan | null)
42const cards = atom({ plugin: 'team', key: 'cards' } as const, [] as TeamCard[])
43const expanded = atom({ plugin: 'team', key: 'expandedCards' } as const, [] as string[])
44const urgent = atom({ plugin: 'team', key: 'urgent' } as const, 0)
45const planPath = atom({ plugin: 'team', key: 'planPath' } as const, '')
46const tickAt = atom({ plugin: 'team', key: 'tickAt' } as const, '')
47const version = atom({ plugin: 'team', key: 'version' } as const, '')
48const error = atom({ plugin: 'team', key: 'error' } as const, '')
49// One tick loop per module: a second session.start replaces it, never adds one.
50let tickTimer: Timer | null = null
51// True while a tick runs: a tick that finds it set returns at once.
52let ticking = false
53// Lines of a rejected send, in order. The next tick that sends puts them first. Memory only: a mod restart
54// loses them. A new session.start (a /clear) keeps them.
55let retryLines: string[] = []
56// Sends that were called and have not settled: a submit waits while the session is busy. A requested
57// compact waits for zero, so it never runs over a line that is queued but not yet taken.
58let sendsInFlight = 0
59// The status text this module set last; null until a session sets one, so its first tick always sets the line.
60let lastBadge: string | undefined | null = null
61
62// The main checkout, resolved once per session root: the 15 s tick must not spawn git every time.
63// Keyed by the session root, which moves on a /cd. A git that could not run is not cached.
64let mainRoot: { from: string; path: string } | null = null
65
66async function projectRoot($: EngineInterface): Promise<string> {
67 const from = await $.session.root()
68 if (mainRoot?.from === from) return mainRoot.path
69 const path = await mainCheckout(from, async args => {
70 try {
71 const r = await $.process.run(['git', 'rev-parse', ...args], { cwd: from, timeoutMs: 5000 })
72 return r.exitCode === 0 ? r.stdout.trim() : ''
73 } catch {
74 return null
75 }
76 })
77 if (path === null) return from
78 mainRoot = { from, path }
79 return path
80}
81
82function makeIo($: EngineInterface): Io {
83 // Every team script resolves its run dir from the main checkout (lib/run-dir.sh). The mod hands
84 // it the absolute run dir and the main checkout as cwd, so a script never depends on the env or
85 // the cwd the engine inherits. An absolute TEAM_SCRATCH needs no git (see main-checkout.test.ts):
86 // it passes the env alone and leaves the cwd to the engine.
87 // Shared by io.run and io.rename; it reads `io` only when called, after io exists.
88 const run: Io['run'] = async (argv, timeoutMs = 10000) => {
89 try {
90 const scratch = await $.env.get('TEAM_SCRATCH')
91 if (scratch?.startsWith('/')) return await $.process.run(argv, { env: { TEAM_SCRATCH: scratch }, timeoutMs })
92 const cwd = await projectRoot($)
93 const env = { TEAM_SCRATCH: await runDir(io) }
94 return await $.process.run(argv, { cwd, env, timeoutMs })
95 } catch (err) {
96 return { exitCode: -1, stdout: '', stderr: String(err) }
97 }
98 }
99 const io: Io = {
100 sessionId: () => $.session.id(),
101 root: () => projectRoot($),
102 envGet: async name =>
103 name === 'TEAM_SCRATCH' ? $.env.get('TEAM_SCRATCH') : $.env.get('HERDR_BIN_PATH'),
104 setSessionEnv: id => $.env.set('TEAM_SESSION_ID', id),
105 readText: async path => {
106 try {
107 const text = await $.fs.read(path)
108 return typeof text === 'string' ? text : null
109 } catch {
110 return null
111 }
112 },
113 writeText: (path, text) => $.fs.write(path, text),
114 // mv in one directory is a rename(2). Whether the engine has $.fs.rename is not known from the repo.
115 rename: async (from, to) => {
116 const r = await run(['mv', from, to])
117 if (r.exitCode !== 0) throw new Error(`mv ${to} failed: ${r.stderr.trim()}`)
118 },
119 list: async dir => {
120 try {
121 return (await $.fs.list(dir)).map(e => e.name)
122 } catch {
123 return []
124 }
125 },
126 mtime: async path => {
127 try {
128 return (await $.fs.stat(path)).mtimeMs
129 } catch {
130 return null
131 }
132 },
133 run,
134 sleep: ms => $.clock.sleep(ms),
135 now: () => $.clock.now(),
136 sendTo: async (sessionId, text) => {
137 const sent = await $.session.send({ to: { sessionId }, text })
138 return sent.isDelivered ? { isDelivered: true } : { isDelivered: false, reason: sent.reason }
139 },
140 submit: text => $.prompt.submit({ text }),
141 draft: async () => {
142 try {
143 return (await $.prompt.read()).text
144 } catch {
145 return ''
146 }
147 },
148 pluginRoot: $.plugin.root,
149 }
150 return io
151}
152
153// Both tabs open on the first activation and on show; the last one opened is the one shown.
154async function openPanes($: EngineInterface): Promise<void> {
155 await $.ui.open({ id: TEAM_PANE, title: 'Team' })
156 await $.ui.open({ id: QUESTIONS_PANE, title: 'Questions' })
157}
158
159// A person's close of either tab closes the other one too and stores hidden:
160// the choice is per run, not per tab.
161async function hideForRun($: EngineInterface): Promise<void> {
162 const cfg = await envoyConfig(makeIo($))
163 if (!cfg) return
164 await $.store.set(hiddenKey(cfg.team_id), true)
165 const open = (await $.ui.panes()).map(p => p.id)
166 for (const id of [TEAM_PANE, QUESTIONS_PANE]) if (open.includes(id)) await $.ui.close({ id })
167}
168
169async function showPanes($: EngineInterface, teamId: string): Promise<void> {
170 if ((await $.store.get(hiddenKey(teamId))) === true) return
171 await openPanes($)
172}
173
174const NOT_SENT = 'prompt not sent: '
175
176/** The tabs layout hygiene and the release leave alone, besides the tab of the session itself. */
177const exemptTabs = (cfg: TeamConfig) => [cfg.orchestrator_tab, cfg.envoy_tab].filter((t): t is string => !!t)
178
179/** Sets the status line when its text differs from the one this module set last. */
180async function setStatus($: EngineInterface, text: string | undefined): Promise<void> {
181 if (text === lastBadge) return
182 await $.ui.status(text)
183 lastBadge = text
184}
185
186/**
187 * The orchestrator half: keeps records true, then sends REPORT, DECISION and WATCH lines as one prompt.
188 * `split` is true when another session is the envoy: no pane shows the error, so the status line does.
189 */
190async function orchestratorHalf(
191 $: EngineInterface, io: Io, cfg: TeamConfig, teamdir: string,
192 records: Record<string, TeamRecord>, listed: HerdrListing, split: boolean,
193): Promise<void> {
194 await syncPanes(io, teamdir, records, listed)
195 const run = await runDir(io)
196 const now = await $.clock.now()
197 const filed = await readCards(io, teamdir)
198 // A card still waiting for the human (open, or parked and so assumed) holds its sender's release back.
199 const waiting = new Set(filed.filter(c => c.status === 'open' || c.status === 'assumed').map(c => c.from))
200 // The cards the team mod closed by itself: each gets one WATCH line, so the orchestrator flips its `[?]` step.
201 const modClosed = filed.filter(c => c.status === 'obsolete' && c.closed_by === 'team mod')
202 // A delivered.json that cannot be used holds REPORT and DECISION lines only. The watch rules, the layout
203 // hygiene and the release run anyway: they have no use for the marks, and a person must see the outage.
204 const reports = await newReportLines(io, run, teamdir, records)
205 const watch = await watchTick(io, run, teamdir, records, listed, now, await $.session.id(), exemptTabs(cfg), waiting,
206 { broken: reports.unreadable, path: reports.path }, modClosed)
207 let fresh = watch
208 let failure: unknown = reports.unreadable ? new Error('delivered.json does not parse') : null
209 if (!reports.unreadable) {
210 const decisions = pickDecisions(await readLedger(io, teamdir), numberMark(reports.delivered, '_decision'))
211 // The marks go first: a submit waits while the session is busy, and a later tick must not pick the same lines again.
212 // When the write fails, REPORT and DECISION lines wait (the marks did not move, so the next tick picks them
213 // again); this tick's WATCH lines are not picked again, so they go out now.
214 try {
215 await reports.commit({ _decision: decisions.mark })
216 fresh = [...reports.lines, ...decisions.lines, ...watch]
217 } catch (err) {
218 failure = err
219 }
220 }
221 if (failure !== null) await showNotSent($, failure, split)
222 // The context nudge goes through the same send path as the other lines, so a rejected send keeps it.
223 fresh = [...fresh, ...(await nudgeLines(resetPort($)))]
224 // Lines of a rejected send go first. The list is emptied as the submit is called, so a later tick cannot send them twice.
225 const lines = [...retryLines, ...fresh.filter(l => !retryLines.includes(l))]
226 if (lines.length > 0) {
227 retryLines = []
228 // Not awaited: the tick ends here, and the submit settles whenever the session takes the prompt.
229 void sendLines($, lines, split, failure !== null).catch(err => showNotSentSafely($, err, split))
230 }
231 // After the send, so a tick that sends lines sees the send in flight and compacts on a later one.
232 // Not awaited either: a compact takes a model call, and a tick must not hold the next ticks back for it.
233 void compactWhenIdle(resetPort($), { retryLines: retryLines.length, sendsInFlight }, text => update($, error, () => text),
234 // No turn follows an idle-time compact by itself, so one RESUME line starts it. It goes through `sendLines`:
235 // a rejected send lands in `retryLines` like any other line. Only this call sends it; the compact hook does not.
236 () => { void sendLines($, [RESUME_LINE], split).catch(err => showNotSentSafely($, err, split)) },
237 ).catch(() => {})
238}
239
240/** The two engine calls the reset needs, over `$`. The breakdown carries `autoCompactThreshold`. */
241function resetPort($: EngineInterface): ResetPort {
242 return {
243 figures: async () => {
244 // The plain call has no threshold; the summary breakdown is a local estimate, no request is made.
245 const usage = await $.session.usage({ breakdown: 'summary' }).catch(() => $.session.usage())
246 const { tokens, window, breakdown } = usage.context
247 // `rawMaxTokens` is the window /context measures against; `context.percent` is against the model window.
248 return { tokens, window, compactWindow: breakdown?.rawMaxTokens, autoCompactThreshold: breakdown?.autoCompactThreshold }
249 },
250 compact: async instructions => {
251 const done = await $.session.compact({ instructions })
252 return done.skip === undefined ? {} : { skip: done.skip }
253 },
254 }
255}
256
257async function showNotSent($: EngineInterface, err: unknown, split: boolean): Promise<void> {
258 const text = `${NOT_SENT}${String(err).slice(0, 160)}`
259 await update($, error, () => text)
260 if (split) await setStatus($, text)
261}
262
263/** The display of an error that cannot throw: when it fails, nothing is left to tell. */
264async function showNotSentSafely($: EngineInterface, err: unknown, split: boolean): Promise<void> {
265 try {
266 await showNotSent($, err, split)
267 } catch {
268 // The display itself failed, so there is nothing left to tell; the lines are in the retry list.
269 }
270}
271
272/**
273 * Sends one prompt. A failed send keeps its lines in `retryLines`, so the next tick that sends puts them
274 * first in its bundle. The marks stay where they are. The list is memory only: a restart loses it.
275 * A good send clears the `prompt not sent` status line unless `keepError` is set.
276 */
277async function sendLines($: EngineInterface, lines: string[], split: boolean, keepError = false): Promise<void> {
278 sendsInFlight += 1
279 try {
280 try {
281 await $.prompt.submit({ text: lines.join('\n') })
282 } catch (err) {
283 // Only a rejected submit fills the list.
284 retryLines = [...retryLines, ...lines.filter(l => !retryLines.includes(l))]
285 await showNotSent($, err, split)
286 return
287 }
288 // The lines are sent. A throw from here on goes to the caller's catch and never fills the list.
289 // `keepError`: this tick shows an error of its own (a broken or unwritable delivered.json); a send of WATCH lines must not clear it.
290 if (split && !keepError && lastBadge?.startsWith(NOT_SENT)) await setStatus($, undefined)
291 } finally {
292 sendsInFlight -= 1
293 }
294}
295
296/** Test-only access to the module state; the mod itself never calls it. */
297export const testing = {
298 reset: () => {
299 retryLines = []
300 sendsInFlight = 0
301 ticking = false
302 lastBadge = null
303 clearResetState()
304 },
305 retryLines: () => [...retryLines],
306 setBadge: (text: string | undefined | null) => {
307 lastBadge = text
308 },
309 sendLines,
310}
311
312/**
313 * The envoy half: the plan, the cards and the agent rows the panes draw, then the next-action message.
314 * `canPush` is false in a session that also holds the orchestrator role: rule 16 forbids the orchestrator
315 * to speak to the human, so such a session gets no next-action turn.
316 */
317async function envoyHalf(
318 $: EngineInterface, io: Io, cfg: TeamConfig, teamdir: string,
319 records: Record<string, TeamRecord>, listed: HerdrListing, canPush: boolean,
320): Promise<void> {
321 const run = await runDir(io)
322 const path = `${run}/progress-${cfg.ticket}.md`
323 const text = await io.readText(path)
324 const parsed = text === null ? null : parsePlan(text)
325 await update($, planPath, () => path)
326 await update($, plan, () => parsed)
327 const rows = agentRows(records, listed)
328 // A card about a worker's permission prompt closes itself once the prompt is gone for two ticks in a row.
329 // It runs before the `canPush` return: a single-session run closes such cards too.
330 const stale = await closeStalePromptCards(io, {
331 cards: await readCards(io, teamdir), records, rows, listed, now: await $.clock.now(),
332 })
333 const found = stale.cards
334 await update($, cards, () => found)
335 await update($, agents, () => rows)
336 const myId = await $.session.id()
337 const idleRows = await idleTabRows(io, await runDir(io), teamdir, records, listed, myId, exemptTabs(cfg))
338 await update($, idle, () => idleRows.rows)
339 await update($, error, () => (listed.ok ? '' : `herdr: ${listed.reason}`))
340 // The orchestrator has a record, but its state comes from herdr's listing, by the session the config names.
341 const orchestrator = listed.ok && cfg.orchestrator_session
342 ? bySession(listed.agents).get(cfg.orchestrator_session)?.agent_status
343 : undefined
344 const stall = stallIds({
345 cards: found,
346 herdrUp: listed.ok,
347 workers: stallWorkers(records, rows, idleRows.briefed, myId),
348 orchestrator,
349 })
350 const stalled = await urgentBadge($, io, teamdir, found, stall)
351 if (!canPush) return
352 const input = await gatherInput(io, {
353 run, cfg, teamdir, records, rows, listed, cards: found, plan: parsed, stalled, myId,
354 now: await $.clock.now(), dialogs: stale.dialogs,
355 })
356 await pushNextAction(io, teamdir, input)
357}
358
359/**
360 * The status line and the toasts; neither starts a turn. The line is, in this order: a `prompt not sent`
361 * error (set only in an orchestrator-only session, and kept while it shows), the urgent badge, the stall
362 * text. Each new urgent card gets one toast, and each stall episode one toast, whatever the line shows.
363 * `stall` is `stallIds`: the open cards while the whole team waits on the human, else null.
364 * Returns whether the run counts as stalled: the wait has held for `STALL_AFTER_MS`, the same timer that shows
365 * the stall line and toast. The next-action trigger T4 reads this flag, not `stall` itself.
366 */
367async function urgentBadge(
368 $: EngineInterface, io: Io, teamdir: string, found: TeamCard[], stall: string[] | null,
369): Promise<boolean> {
370 await update($, urgent, () => found.filter(c => c.urgent && (c.status === 'open' || c.status === 'assumed')).length)
371 const marksPath = `${teamdir}/toasted.json`
372 const read = await readJson<string[]>(io, marksPath)
373 const fresh = freshUrgent(found, read)
374 const waiting = freshStall(stall, found.some(c => c.status === 'open'), fresh.seen, await $.clock.now())
375 const notSent = lastBadge?.startsWith(NOT_SENT) ? lastBadge : undefined
376 await setStatus($, pickStatus(notSent, badgeText(found), waiting.text))
377 for (const c of fresh.toast) await $.ui.toast(toastText(c), { timeoutMs: TOAST_MS })
378 if (waiting.toast !== undefined) await $.ui.toast(waiting.toast, { timeoutMs: TOAST_MS })
379 await writeJson(io, marksPath, waiting.seen)
380 return waiting.text !== undefined
381}
382
383/** The timer does not wait for a tick (its callback returns void), so a slow tick would overlap the next one. */
384async function tick($: EngineInterface, io: Io): Promise<void> {
385 if (ticking) return
386 ticking = true
387 try {
388 await tickOnce($, io)
389 } finally {
390 ticking = false
391 }
392}
393
394async function tickOnce($: EngineInterface, io: Io): Promise<void> {
395 const held = await sessionRole(io)
396 const was = await read($, active)
397 await update($, active, () => held !== null)
398 // Every team status line belongs to a role. Clear it once when the session loses its role. A session
399 // that still holds only the orchestrator role keeps its `prompt not sent` line: a good submit clears it.
400 const keepsError = !!held?.role.orchestrator && !!lastBadge?.startsWith(NOT_SENT)
401 if (!held?.role.envoy && lastBadge && !keepsError) await setStatus($, undefined)
402 if (!held) return
403 const { cfg, role } = held
404 if (role.envoy && !was) await showPanes($, cfg.team_id)
405
406 const teamdir = await teamDir(io)
407 const listed = await herdrAgents(io)
408 const records = await readRecords(io, teamdir)
409 // The envoy half first: the orchestrator half may report a failed prompt, which must not be cleared.
410 if (role.envoy) await envoyHalf($, io, cfg, teamdir, records, listed, !role.orchestrator)
411 if (role.orchestrator) await orchestratorHalf($, io, cfg, teamdir, records, listed, !role.envoy)
412
413 const at = new Date(await $.clock.now()).toISOString().slice(11, 19)
414 await update($, tickAt, () => at)
415}
416
417export const register: Register = on => {
418 mainRoot = null
419 on('session.start', async ($, e, next) => {
420 const io = makeIo($)
421 await $.env.set('TEAM_SESSION_ID', await $.session.id())
422 lastBadge = null
423 resetNextAction()
424 resetHolds()
425 clearResetState()
426 // Read once: the footer shows the copy that runs, the one under the plugin root.
427 const found = pluginVersion(await io.readText(`${io.pluginRoot}/.claude-plugin/plugin.json`))
428 await update($, version, () => found ?? '')
429 await $.command.register({ name: 'team-overview', description: 'Show or hide the Team and Questions tabs' })
430 await $.command.register({
431 name: 'team-envoy',
432 description: 'Make this session the envoy of the live team run; starts a new orchestrator if its session is gone',
433 })
434 await $.tool.register(BRIEF_TOOL_SPEC)
435 await $.tool.register(RESET_TOOL_SPEC)
436 await $.tool.register(ASK_TOOL_SPEC)
437 await $.tool.register(QUEUE_TOOL_SPEC)
438 await $.tool.register(DECIDE_TOOL_SPEC)
439 await $.tool.register(RELAY_TOOL_SPEC)
440 tickTimer?.cancel()
441 tickTimer = $.clock.every(TICK_MS, () => tick($, io))
442 return next(e)
443 })
444
445 on('session.end', async ($, e, next) => {
446 if (e.reason === 'clear') noteClear(e.sessionId)
447 return next(e)
448 })
449
450 on('tool.call', { tool: `mcp__team__${BRIEF_TOOL}` }, async ($, e) =>
451 briefSend(makeIo($), String(e.name ?? ''), String(e.topic ?? '')))
452
453 // Only records the request: a tool call runs inside a turn, and a compact cannot. The tick compacts when idle.
454 on('tool.call', { tool: `mcp__team__${RESET_TOOL}` }, async $ => resetSelf(makeIo($)))
455
456 // Every compact of the orchestrator carries the handover instructions, Claude Code's own auto-compact too.
457 // A subagent's compact (`agentId`) and a `precompute` (nothing installed) are left alone.
458 on('session.compact', async ($, e, next) => {
459 if (e.agentId !== undefined || !(await activeConfig(makeIo($)))) return next(e)
460 const done = await next({ ...e, instructions: withHandoverInstructions(e.instructions) })
461 if (done.skip === undefined && e.trigger !== 'precompute') onCompacted()
462 return done
463 })
464
465 // The orchestrator's inbox log: RELAY and peer lines leave no other trace. It never holds a delivery back.
466 on('session.receive', async ($, e, next) => {
467 if (e.agentId === undefined) {
468 try {
469 const io = makeIo($)
470 if (await activeConfig(io)) await logReceived(io, e.text)
471 } catch {
472 // A log that cannot be written must not stop the delivery.
473 }
474 }
475 return next(e)
476 })
477
478 on('tool.call', { tool: 'mcp__team__ask' }, async ($, e) => askTool(makeIo($), e))
479
480 // A queue call shows the cards to the envoy: the next-action message does not repeat what it just read.
481 on('tool.call', { tool: 'mcp__team__queue' }, async ($, e) => {
482 const io = makeIo($)
483 const shown = await queueTool(io, e)
484 if (!shown.isError) await markShown(io, await teamDir(io))
485 return shown
486 })
487
488 // The envoy is mid-turn between these two events: a next-action message waits for the end.
489 on('turn.start', async ($, e, next) => {
490 noteTurnStart(await $.clock.now())
491 noteMainTurn(true)
492 return next(e)
493 })
494
495 // A subagent's turn ends with an `agentId`; only the main loop's end frees the envoy.
496 on('turn.complete', async ($, e, next) => {
497 if (e.agentId === undefined) {
498 noteTurnEnd()
499 noteMainTurn(false)
500 }
501 return next(e)
502 })
503
504 on('tool.call', { tool: 'mcp__team__decide' }, async ($, e) => decideTool(makeIo($), e))
505
506 on('tool.call', { tool: 'mcp__team__relay' }, async ($, e) => relayTool(makeIo($), e))
507
508 // Auto mode denied a tool call: record it, and pass the event on unchanged (no `retry`).
509 on('classic.PermissionDenied', async ($, e, next) => {
510 await recordDenial(makeIo($), e.tool_name, e.reason)
511 return next(e)
512 })
513
514 on('command.run', { command: 'team-overview' }, async $ => {
515 const cfg = await envoyConfig(makeIo($))
516 if (!cfg) return { text: 'No team run in this session.' }
517 // A pane that is open but not placed (a herdr pane under 144 columns) is not drawn, so it counts as closed.
518 const open = (await $.ui.panes()).filter(p => p.isPlaced).map(p => p.id)
519 if (open.includes(TEAM_PANE) || open.includes(QUESTIONS_PANE)) {
520 await $.ui.close({ id: TEAM_PANE })
521 await $.ui.close({ id: QUESTIONS_PANE })
522 await $.store.set(hiddenKey(cfg.team_id), true)
523 return { text: 'Team overview hidden.' }
524 }
525 await $.store.set(hiddenKey(cfg.team_id), false)
526 await openPanes($)
527 return { text: 'Team overview shown.' }
528 })
529
530 // The tabs open on the next tick, which finds the envoy role new to this session.
531 on('command.run', { command: 'team-envoy' }, async $ => {
532 const text = await reattach(makeIo($))
533 return { text }
534 })
535
536 on('ui.close', { id: TEAM_PANE }, async ($, e, next) => {
537 const done = await next(e)
538 if (closeHides(e.origin)) await hideForRun($)
539 return done
540 })
541
542 on('ui.close', { id: QUESTIONS_PANE }, async ($, e, next) => {
543 const done = await next(e)
544 if (closeHides(e.origin)) await hideForRun($)
545 return done
546 })
547
548 on('ui.render', { component: 'Pane', requestId: QUESTIONS_PANE }, async ($, e) => {
549 const { Box, Text, Button } = $.ui.resolve(e)
550 const current = await read($, cards)
551 const open = await read($, expanded)
552 const live = pruneExpanded(open, current)
553 if (live !== open) await update($, expanded, () => live)
554 return drawQuestions({ Box, Text, Button } as never, {
555 cards: current,
556 teamId: (await envoyConfig(makeIo($)))?.team_id ?? '',
557 expanded: live,
558 columns: e.props.bodyColumns,
559 toggle: id => update($, expanded, ids => (ids.includes(id) ? ids.filter(i => i !== id) : [...ids, id])),
560 })
561 })
562
563 on('ui.render', { component: 'Pane', requestId: TEAM_PANE }, async ($, e) => {
564 const { Box, Text, Button } = $.ui.resolve(e)
565 return drawPane({ Box, Text, Button } as never, {
566 agents: await read($, agents),
567 idle: await read($, idle),
568 plan: await read($, plan),
569 cards: await read($, cards),
570 teamId: (await envoyConfig(makeIo($)))?.team_id ?? '',
571 planPath: await read($, planPath),
572 tickAt: await read($, tickAt),
573 version: await read($, version),
574 error: await read($, error),
575 rows: e.viewport?.rows ?? 30,
576 }, async a => {
577 const reason = await herdrFocus(makeIo($), a.pane)
578 if (reason !== '') await update($, error, () => `focus ${a.name}: ${reason}`)
579 })
580 })
581}
582hooks/mod/activation.ts 75 lines1import { readJson, writeJson } from './io'
2import type { Io } from './io'
3import { teamDir } from './paths'
4
5export type TeamConfig = {
6 team_id: string
7 ticket: string
8 orchestrator: string
9 orchestrator_session?: string
10 orchestrator_tab?: string
11 envoy_session?: string
12 envoy_tab?: string
13}
14
15let clearedFrom: string | null = null
16
17export const noteClear = (oldId: string) => {
18 clearedFrom = oldId
19}
20
21export type Role = { orchestrator: boolean; envoy: boolean }
22
23/** Without envoy_session the orchestrator session also holds the envoy role. */
24export function roleOf(cfg: TeamConfig | null, id: string): Role {
25 const orchestrator = !!cfg && cfg.orchestrator_session === id
26 const envoy = !!cfg && (cfg.envoy_session ? cfg.envoy_session === id : orchestrator)
27 return { orchestrator, envoy }
28}
29
30async function followClear(io: Io): Promise<void> {
31 if (clearedFrom === null) return
32 const old = clearedFrom
33 clearedFrom = null
34 const path = `${await teamDir(io)}/config.json`
35 const cfg = await readJson<TeamConfig>(io, path)
36 const id = await io.sessionId()
37 await io.setSessionEnv(id)
38 if (!cfg || old === id) return
39 const moved = {
40 ...cfg,
41 ...(cfg.orchestrator_session === old ? { orchestrator_session: id } : {}),
42 ...(cfg.envoy_session === old ? { envoy_session: id } : {}),
43 }
44 if (moved.orchestrator_session !== cfg.orchestrator_session || moved.envoy_session !== cfg.envoy_session) {
45 await writeJson(io, path, moved)
46 }
47}
48
49// Follows a pending /clear first, so a command or tool call right after one
50// does not wait for the next tick to find the team.
51export async function readConfig(io: Io): Promise<TeamConfig | null> {
52 await followClear(io)
53 return readJson<TeamConfig>(io, `${await teamDir(io)}/config.json`)
54}
55
56/** The run config and the halves this session holds, or null when it holds none. */
57export async function sessionRole(io: Io): Promise<{ cfg: TeamConfig; role: Role } | null> {
58 const cfg = await readConfig(io)
59 if (!cfg) return null
60 const role = roleOf(cfg, await io.sessionId())
61 return role.orchestrator || role.envoy ? { cfg, role } : null
62}
63
64/** The run config when this session holds the orchestrator role, else null. */
65export async function activeConfig(io: Io): Promise<TeamConfig | null> {
66 const found = await sessionRole(io)
67 return found?.role.orchestrator ? found.cfg : null
68}
69
70/** The run config when this session holds the envoy role, else null. The envoy half needs no orchestrator_session. */
71export async function envoyConfig(io: Io): Promise<TeamConfig | null> {
72 const found = await sessionRole(io)
73 return found?.role.envoy ? found.cfg : null
74}
75hooks/mod/badge.ts 103 lines1import type { TeamCard } from '../../types'
2
3const unresolvedUrgent = (cards: TeamCard[]) =>
4 cards.filter(c => c.urgent && (c.status === 'open' || c.status === 'assumed')).sort((a, b) => a.n - b.n)
5
6/** The status line text: how many urgent cards wait, and the oldest of them. Undefined when none wait. */
7export function badgeText(cards: TeamCard[]): string | undefined {
8 const waiting = unresolvedUrgent(cards)
9 const oldest = waiting[0]
10 return oldest ? `${waiting.length} urgent: ${oldest.id} ${oldest.from}: ${oldest.question}` : undefined
11}
12
13export const toastText = (c: TeamCard) => `URGENT ${c.id} ${c.from}: ${c.question}`
14
15/**
16 * The urgent cards to toast, and the marks to keep. `seen` is null when no marks
17 * exist yet: that run is a baseline, so it marks every urgent card and toasts none.
18 */
19export function freshUrgent(cards: TeamCard[], seen: string[] | null): { toast: TeamCard[]; seen: string[] } {
20 const urgent = cards.filter(c => c.urgent).sort((a, b) => a.n - b.n)
21 const marks = new Set(seen ?? [])
22 const toast = seen === null ? [] : unresolvedUrgent(cards).filter(c => !marks.has(c.id))
23 for (const c of urgent) marks.add(c.id)
24 return { toast, seen: [...marks] }
25}
26
27/** How long the whole team must wait on the human before the run counts as stalled: 8 ticks of 15 s. */
28export const STALL_AFTER_MS = 120_000
29
30/** How long an urgent-card toast and a stall toast stay on screen: 30 s (decision 7). */
31export const TOAST_MS = 30_000
32
33export type StallWorker = {
34 /** The herdr state, or `gone` when herdr lists no agent for the record. */
35 state: string
36 /** Whether the worker's report is fresh; read only for an idle or done worker. */
37 fresh: boolean
38}
39
40export type StallInput = {
41 cards: TeamCard[]
42 herdrUp: boolean
43 workers: StallWorker[]
44 /** The orchestrator's herdr state; undefined when herdr does not list it. */
45 orchestrator: string | undefined
46}
47
48const quiet = (state: string | undefined) => state === 'idle' || state === 'done'
49
50/**
51 * The ids of the open cards when the whole team waits on the human, else null: herdr is up, no worker
52 * works, every idle or done worker has a fresh report, the orchestrator is idle or done, and at least
53 * one card is open. A parked (assumed) card does not count: the team goes on without it.
54 */
55export function stallIds(input: StallInput): string[] | null {
56 const open = input.cards.filter(c => c.status === 'open').sort((a, b) => a.n - b.n)
57 if (open.length === 0 || !input.herdrUp || !quiet(input.orchestrator)) return null
58 const stuck = input.workers.every(w => w.state === 'gone' || (quiet(w.state) && w.fresh))
59 return stuck ? open.map(c => c.id) : null
60}
61
62/**
63 * The one status line has three claimants, in this order: a `prompt not sent` error (`notSent`, the line
64 * as it shows now when it is one), the urgent badge, the stall text.
65 */
66export const pickStatus = (notSent: string | undefined, urgent: string | undefined, stall: string | undefined) =>
67 notSent ?? urgent ?? stall
68
69export const stallText = (ids: string[]) => `run waits on you: ${ids.length} open (${ids.join(', ')})`
70
71// Two marks in toasted.json beside the urgent card ids: the episode under way and its toast.
72const SINCE_MARK = 'stall:'
73const TOAST_MARK = 'stall-toast:'
74
75/**
76 * The stall line and toast for this tick, and the marks to keep. `ids` is `stallIds` (null on a break),
77 * `open` tells whether any card is open, `seen` is the marks as read. The timer is the
78 * `stall:<ms>:<ids>` mark: it starts when the wait first holds for a set of open cards, starts over
79 * when the set changes, and goes at once on a break. The toast is keyed by the same set: a new card or
80 * an answer starts a new episode. A break keeps the toast mark, so the same cards that stall again after
81 * an agent worked do not toast twice; it goes when the set changes or no card is open.
82 */
83export function freshStall(ids: string[] | null, open: boolean, seen: string[], now: number):
84 { text: string | undefined; toast: string | undefined; seen: string[] } {
85 const others = seen.filter(m => !m.startsWith(SINCE_MARK) && !m.startsWith(TOAST_MARK))
86 if (ids === null) {
87 const kept = seen.filter(m => !m.startsWith(SINCE_MARK) && (open || !m.startsWith(TOAST_MARK)))
88 return { text: undefined, toast: undefined, seen: kept }
89 }
90 const key = ids.join(',')
91 const held = seen.find(m => m.startsWith(SINCE_MARK))?.slice(SINCE_MARK.length)
92 const colon = held?.indexOf(':') ?? -1
93 const sameSet = held !== undefined && held.slice(colon + 1) === key
94 const since = sameSet ? Number(held!.slice(0, colon)) : now
95 const marks = [...others, `${SINCE_MARK}${since}:${key}`]
96 const toasted = seen.includes(`${TOAST_MARK}${key}`)
97 if (toasted) marks.push(`${TOAST_MARK}${key}`)
98 if (now - since < STALL_AFTER_MS) return { text: undefined, toast: undefined, seen: marks }
99 const text = stallText(ids)
100 if (!toasted) marks.push(`${TOAST_MARK}${key}`)
101 return { text, toast: toasted ? undefined : text, seen: marks }
102}
103hooks/mod/brief.ts 62 lines1import { activeConfig } from './activation'
2import { bySession, herdrAgents } from './herdr'
3import { readJson, writeJson } from './io'
4import type { Io, ToolResult } from './io'
5import { teamDir } from './paths'
6import type { TeamRecord } from './tick'
7
8export const BRIEF_TOOL = 'brief_send'
9export const BRIEF_TOOL_SPEC = {
10 name: BRIEF_TOOL,
11 description:
12 'Send a composed brief to a team agent by its session id. Run `team-brief compose` first. ' +
13 'Returns "<name>: <state>"; an error names the reason.',
14 inputSchema: {
15 type: 'object',
16 properties: { name: { type: 'string' }, topic: { type: 'string' } },
17 required: ['name', 'topic'],
18 },
19}
20// A hook gets 10 s and a clock wait counts against it; leave room for the send.
21const WAIT_MS = 6000
22const POLL_MS = 500
23
24const fail = (result: string): ToolResult => ({ result, isError: true })
25
26const briefedInThisSession = (rec: TeamRecord) =>
27 rec.session !== undefined && rec.brief_sent_session === rec.session
28
29/**
30 * The record once it is no longer briefed in its current session, or after
31 * WAIT_MS. A /clear moves `session` on; a /compact keeps it, and the
32 * SessionStart hook drops `brief_sent_session` instead.
33 */
34async function clearedRecord(io: Io, path: string): Promise<TeamRecord | null> {
35 for (let waited = 0; ; waited += POLL_MS) {
36 const rec = await readJson<TeamRecord>(io, path)
37 if (!rec || !briefedInThisSession(rec) || waited >= WAIT_MS) return rec
38 await io.sleep(POLL_MS)
39 }
40}
41
42export async function briefSend(io: Io, name: string, topic: string): Promise<ToolResult> {
43 if (!(await activeConfig(io))) return fail('brief_send works only in the orchestrator session')
44 if (!/^[a-z][a-z0-9_-]{0,31}$/.test(name)) return fail(`bad name: ${name}`)
45 const path = `${await teamDir(io)}/${name}.json`
46 const rec = await clearedRecord(io, path)
47 if (!rec) return fail(`no agent record: ${name}`)
48 if (!rec.session) return fail(`${name} has no session id; start it again with team-start`)
49 if (briefedInThisSession(rec)) return fail(`${name} was not cleared or compacted since its last brief`)
50
51 const prepared = await io.run([`${io.pluginRoot}/bin/team-brief`, 'prepare', name, '--topic', topic])
52 if (prepared.exitCode !== 0) return fail(prepared.stderr.trim() || `team-brief prepare failed (${prepared.exitCode})`)
53 const sent = await io.sendTo(rec.session, prepared.stdout.trim())
54 if (!sent.isDelivered) return fail(`not delivered: ${sent.reason ?? 'unknown reason'}`)
55
56 const latest = (await readJson<TeamRecord>(io, path)) ?? rec
57 await writeJson(io, path, { ...latest, brief_sent_session: rec.session, watch_session: rec.session })
58 const listed = await herdrAgents(io)
59 const state = listed.ok ? bySession(listed.agents).get(rec.session)?.agent_status ?? 'gone' : 'unknown'
60 return { result: `${name}: ${state}` }
61}
62hooks/mod/inbox.ts 22 lines1import type { Io } from './io'
2import { teamDir } from './paths'
3
4export const INBOX_LOG = 'inbox.log'
5/** The log keeps about this many characters: the newest lines. */
6const MAX_CHARS = 200_000
7
8/** One log entry: the time, then the text. Every line after the first is indented by two spaces. */
9export function inboxEntry(at: number, text: string): string {
10 const [first = '', ...rest] = text.split(/\r\n|[\r\n\u{2028}\u{2029}]/u)
11 return `${[`${new Date(at).toISOString()} ${first}`, ...rest.map(l => ` ${l}`)].join('\n')}\n`
12}
13
14/** Appends one received line to `.team/inbox.log`; the oldest lines go when the log grows past the cap. */
15export async function logReceived(io: Io, text: string): Promise<void> {
16 const path = `${await teamDir(io)}/${INBOX_LOG}`
17 const all = ((await io.readText(path)) ?? '') + inboxEntry(await io.now(), text)
18 if (all.length <= MAX_CHARS) return io.writeText(path, all)
19 const cut = all.slice(-MAX_CHARS)
20 return io.writeText(path, cut.slice(cut.indexOf('\n') + 1))
21}
22hooks/mod/io.ts 56 lines1export type RunResult = { exitCode: number; stdout: string; stderr: string }
2
3export type ToolResult = { result: string; isError?: true }
4
5/** Everything the mod's logic needs from the engine, built over `$` in team.tsx. */
6export type Io = {
7 sessionId: () => Promise<string>
8 /**
9 * The project root, absolute: the main checkout of the session's root (the same from a linked
10 * worktree). A shell `cd` does not move it. Cached per session root, so git runs once.
11 */
12 root: () => Promise<string>
13 envGet: (name: 'TEAM_SCRATCH' | 'HERDR_BIN_PATH') => Promise<string | undefined>
14 setSessionEnv: (id: string) => Promise<void>
15 readText: (path: string) => Promise<string | null>
16 writeText: (path: string, text: string) => Promise<void>
17 /** Moves `from` over `to` in one step (same directory). Throws when it fails; `to` is then untouched. */
18 rename: (from: string, to: string) => Promise<void>
19 list: (dir: string) => Promise<string[]>
20 mtime: (path: string) => Promise<number | null>
21 run: (argv: string[], timeoutMs?: number) => Promise<RunResult>
22 sleep: (ms: number) => Promise<void>
23 now: () => Promise<number>
24 sendTo: (sessionId: string, text: string) => Promise<{ isDelivered: boolean; reason?: string }>
25 /** Submits `text` as a prompt of its own, once the session is idle. Settles as that turn starts; rejects when refused. */
26 submit: (text: string) => Promise<unknown>
27 /** The draft in the prompt box; '' where there is none or the read fails. */
28 draft: () => Promise<string>
29 pluginRoot: string
30}
31
32export async function readJson<T>(io: Io, path: string): Promise<T | null> {
33 const text = await io.readText(path)
34 if (text === null) return null
35 try {
36 return JSON.parse(text) as T
37 } catch {
38 return null
39 }
40}
41
42/**
43 * Writes `<path>.tmp-<random>`, then renames it over `path`: a reader sees the old file or the new one, never
44 * half of one. A failed write or rename leaves `path` as it was (a temp file may stay; its name is no state file).
45 */
46export async function writeJson(io: Io, path: string, value: unknown): Promise<void> {
47 const tmp = `${path}.tmp-${Math.random().toString(36).slice(2, 10)}`
48 await io.writeText(tmp, JSON.stringify(value))
49 await io.rename(tmp, path)
50}
51
52export async function tailText(io: Io, path: string, bytes: number): Promise<string> {
53 const r = await io.run(['tail', '-c', String(bytes), path])
54 return r.exitCode === 0 ? r.stdout : ''
55}
56hooks/mod/herdr.ts 109 lines1import type { Io } from './io'
2
3export type HerdrAgent = {
4 pane_id: string
5 tab_id?: string
6 agent_status: string
7 agent_session?: { value: string }
8 /** The herdr name `herdr agent start <name>` gave it; herdr does not restore it after a restart. */
9 name?: string
10}
11export type HerdrPane = { pane_id: string; tab_id: string; agent_status: string }
12export type HerdrListing = { ok: true; agents: HerdrAgent[] } | { ok: false; reason: string }
13
14async function herdr(io: Io, args: string[], timeoutMs?: number) {
15 const bin = (await io.envGet('HERDR_BIN_PATH')) ?? 'herdr'
16 return io.run([bin, ...args], timeoutMs)
17}
18
19function failure(r: { exitCode: number; stdout: string; stderr: string }): string {
20 return (r.stderr || r.stdout).trim().slice(0, 200) || `exit ${r.exitCode}`
21}
22
23/** `timeoutMs` bounds the call; without it the `io.run` default (10 s) applies. */
24export async function herdrAgents(io: Io, timeoutMs?: number): Promise<HerdrListing> {
25 const r = await herdr(io, ['agent', 'list'], timeoutMs)
26 if (r.exitCode !== 0) return { ok: false, reason: failure(r) }
27 try {
28 return { ok: true, agents: JSON.parse(r.stdout)?.result?.agents ?? [] }
29 } catch {
30 return { ok: false, reason: 'bad output from herdr agent list' }
31 }
32}
33
34export async function herdrPanes(io: Io): Promise<HerdrPane[] | null> {
35 const r = await herdr(io, ['pane', 'list'])
36 if (r.exitCode !== 0) return null
37 try {
38 return JSON.parse(r.stdout)?.result?.panes ?? []
39 } catch {
40 return null
41 }
42}
43
44const DIALOG_CAP = 200
45const nonEmpty = (rows: string[]) => rows.map(l => l.trim()).filter(l => l !== '')
46const isFrameRule = (row: string) => row.length >= 20 && /^─+$/.test(row)
47const isDashedRule = (row: string) => /^╌+$/.test(row)
48
49/**
50 * The text of the dialog in a `herdr agent read` snapshot (the bottom 20 screen rows, old history on top).
51 * A permission dialog sits below the last full-width `─` rule and replaces the input box and footer:
52 * - title row / command row (between the two `╌` rules) / last row ending with `?`, or
53 * - when the frame has no `╌` pair or no `?` row: every row below the frame, minus `╌` rules and a
54 * last `Esc to cancel` row.
55 * With no frame rule the last 3 non-empty rows are returned. The result is capped at 200 characters.
56 */
57export function dialogText(snapshot: string): string {
58 const rows = snapshot.split('\n').map(l => l.trim())
59 const frame = rows.map(isFrameRule).lastIndexOf(true)
60 if (frame === -1) return nonEmpty(rows).slice(-3).join(' / ').slice(0, DIALOG_CAP)
61 const below = nonEmpty(rows.slice(frame + 1))
62 const dashed = below.flatMap((row, i) => (isDashedRule(row) ? [i] : []))
63 const question = below.findLastIndex(row => row.endsWith('?'))
64 if (dashed.length >= 2 && question !== -1) {
65 const command = below.slice(dashed[0] + 1, dashed[1])[0] ?? ''
66 return [below[0], command, below[question]].join(' / ').slice(0, DIALOG_CAP)
67 }
68 const kept = below.filter(row => !isDashedRule(row))
69 if (kept.at(-1)?.startsWith('Esc to cancel')) kept.pop()
70 return kept.join(' / ').slice(0, DIALOG_CAP)
71}
72
73/** A dialog text with its whitespace collapsed and trimmed: what two reads of one prompt agree on. */
74export const normalizeDialog = (text: string) => text.replace(/\s+/g, ' ').trim()
75
76/**
77 * Whether two dialog texts are the same prompt: equal after whitespace is collapsed. A dialog empty on either
78 * side (a failed read, an agent that showed no prompt at filing) never counts as a different prompt.
79 */
80export function samePrompt(a: string, b: string): boolean {
81 const left = normalizeDialog(a)
82 const right = normalizeDialog(b)
83 return left === '' || right === '' || left === right
84}
85
86/** The dialog a blocked agent shows, for the WATCH line. Empty when the snapshot is empty or the call fails. */
87export async function herdrDialog(io: Io, pane: string, timeoutMs?: number): Promise<string> {
88 const r = await herdr(io, ['agent', 'read', pane, '--source', 'detection', '--lines', '20'], timeoutMs)
89 return r.exitCode === 0 ? dialogText(r.stdout) : ''
90}
91
92/** Focuses the agent's pane; the failure reason, or '' when it worked. */
93export async function herdrFocus(io: Io, pane: string): Promise<string> {
94 const r = await herdr(io, ['agent', 'focus', pane])
95 return r.exitCode === 0 ? '' : failure(r)
96}
97
98/** Closes the pane; the failure reason, or '' when it worked. */
99export async function herdrClose(io: Io, pane: string): Promise<string> {
100 const r = await herdr(io, ['pane', 'close', pane])
101 return r.exitCode === 0 ? '' : failure(r)
102}
103
104export function bySession(list: HerdrAgent[]): Map<string, HerdrAgent> {
105 const map = new Map<string, HerdrAgent>()
106 for (const a of list) if (a.agent_session?.value) map.set(a.agent_session.value, a)
107 return map
108}
109hooks/mod/pane.tsx 211 lines1import type { Elements } from 'claude-code'
2import type { TeamAgentRow, TeamCard, TeamPlan, TeamPlanItem } from '../../types'
3import { queueGroups } from './cards'
4import type { QueueGroup } from './cards'
5import { fitPlan } from './plan'
6
7export const TEAM_PANE = 'team'
8export const QUESTIONS_PANE = 'questions'
9export const hiddenKey = (teamId: string) => `overviewHidden:${teamId}`
10/** Only the person's own close hides the overview. A close by a plugin or on unload does not. */
11export const closeHides = (origin: { kind: string }) => origin.kind === 'person'
12
13export type PaneView = {
14 agents: TeamAgentRow[]
15 /** Rows of idle team tabs, with the pane statuses seen: "tab w4:t19 idle, consider release (w4:p3K done)". */
16 idle: string[]
17 plan: TeamPlan | null
18 cards: TeamCard[]
19 teamId: string
20 planPath: string
21 tickAt: string
22 /** The plugin version for the footer; '' draws none. */
23 version: string
24 error: string
25 rows: number
26}
27
28const MARK = {
29 x: { glyph: '✓', color: 'green', dim: true },
30 '>': { glyph: '▶', color: 'yellow', dim: false },
31 ' ': { glyph: '○', color: undefined, dim: false },
32 /** An item that waits on the human. Not `!`: that is the urgent card mark. */
33 '?': { glyph: '◆', color: 'magenta', dim: false },
34} as const
35
36export function drawPane({ Box, Text, Button }: Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>, view: PaneView,
37 focus: (agent: TeamAgentRow) => void,
38) {
39 const groups = queueGroups(view.cards)
40 const unresolved = groups.flatMap(g => g.cards)
41 const urgent = unresolved.filter(c => c.urgent)
42 const tally = (cards: TeamCard[], status: 'open' | 'assumed') => cards.filter(c => c.status === status).length
43 const groupRow = (g: QueueGroup) =>
44 [g.tag, ...(['open', 'assumed'] as const)
45 .filter(s => tally(g.cards, s) > 0)
46 .map(s => `${tally(g.cards, s)} ${s}`)].join(' ')
47 const questionRows = (unresolved.length === 0 ? 1 : 1 + urgent.length + groups.length) + 1
48 // The WAITS ON YOU heading is one more row, drawn only when an item waits.
49 const waitsHeading = view.plan !== null && view.plan.waits.length > 0 ? 1 : 0
50 const room = Math.max(view.rows - view.agents.length - view.idle.length - 12 - questionRows - waitsHeading, 3)
51 const fitted = view.plan ? fitPlan(view.plan, room) : null
52 const item = (i: TeamPlanItem) => (
53 <Text wrap="truncate-end" dimColor={MARK[i.mark].dim}>
54 {' '}
55 <Text color={MARK[i.mark].color}>{MARK[i.mark].glyph}</Text> {i.text}
56 </Text>
57 )
58 const section = (title: string, items: TeamPlanItem[]) => (
59 <Box flexDirection="column">
60 <Text dimColor>{title}</Text>
61 {items.length === 0 ? <Text dimColor> -</Text> : items.map(item)}
62 </Box>
63 )
64 return (
65 <Box flexDirection="column">
66 {fitted ? (
67 <Box flexDirection="column">
68 <Text bold wrap="truncate-end">{fitted.plan.title || 'Plan'}</Text>
69 {fitted.plan.waits.length > 0 && section('WAITS ON YOU', fitted.plan.waits)}
70 {section(fitted.hiddenDone ? `DONE (+${fitted.hiddenDone} earlier)` : 'DONE', fitted.plan.done)}
71 {section('RUNNING', fitted.plan.running)}
72 {section('NEXT', fitted.plan.next)}
73 </Box>
74 ) : (
75 <Text dimColor wrap="truncate-end">no plan yet: {view.planPath}</Text>
76 )}
77 <Text> </Text>
78 {unresolved.length === 0 ? (
79 <Text dimColor>Questions: none open</Text>
80 ) : (
81 <Box flexDirection="column">
82 <Text bold>{`Questions (${tally(unresolved, 'open')} open, ${tally(unresolved, 'assumed')} assumed)`}</Text>
83 {urgent.map(c => (
84 <Text key={c.id} wrap="truncate-end">
85 <Text color="yellow">!</Text> {c.id} {shortFrom(c.from, view.teamId)}: {c.question}
86 </Text>
87 ))}
88 {groups.map(g => <Text key={g.tag} wrap="truncate-end">{` ${groupRow(g)}`}</Text>)}
89 </Box>
90 )}
91 <Text> </Text>
92 <Text bold>Agents</Text>
93 {view.agents.length === 0 && <Text dimColor> (none)</Text>}
94 {view.agents.map((a, i) => (
95 <Button key={a.name} plain hotkey={i < 9 ? String(i + 1) : undefined} onPress={() => focus(a)}>
96 {`${a.state.padEnd(8)} ${a.name} ${a.pane}`}
97 </Button>
98 ))}
99 {view.idle.map(row => <Text key={row} dimColor wrap="truncate-end">{row}</Text>)}
100 {view.error !== '' && <Text color="red" wrap="truncate-end">{view.error}</Text>}
101 <Text dimColor>{`${view.version === '' ? '' : `team ${view.version} `}tick ${view.tickAt || '-'}`}</Text>
102 </Box>
103 )
104}
105
106/** Flip to true if the unicode glyphs draw at the wrong width in a terminal. */
107export const ASCII_GLYPHS = false
108
109/** The one place for card glyphs: status and door, each with an ASCII fallback behind ASCII_GLYPHS. */
110const CARD_GLYPH = {
111 status: {
112 open: { glyph: '●', ascii: '?', color: 'yellow', dim: false },
113 assumed: { glyph: '◐', ascii: '~', color: 'cyan', dim: false },
114 answered: { glyph: '✓', ascii: '+', color: 'green', dim: true },
115 obsolete: { glyph: '✗', ascii: 'x', color: undefined, dim: true },
116 },
117 /** Replaces the status glyph of an urgent card that still waits (open or parked): one column, like the glyphs it stands in for. */
118 urgent: { glyph: '!', ascii: '!', color: 'red', dim: false },
119 door: {
120 'one-way': { glyph: '→', ascii: '1' },
121 'two-way': { glyph: '⇄', ascii: '2' },
122 },
123 expand: {
124 collapsed: { glyph: '▸', ascii: '>' },
125 open: { glyph: '▾', ascii: 'v' },
126 },
127} as const
128
129/** The expanded ids that still name a card. Returns the same array when none goes, so the caller can skip a write. */
130export function pruneExpanded(expanded: string[], cards: Pick<TeamCard, 'id'>[]): string[] {
131 const live = expanded.filter(id => cards.some(c => c.id === id))
132 return live.length === expanded.length ? expanded : live
133}
134
135/** The sender as a person reads it: no `<team_id>-` prefix, no `/general` tag. */
136export function shortFrom(from: string, teamId: string): string {
137 const prefix = `${teamId}-`
138 return teamId !== '' && from.startsWith(prefix) ? from.slice(prefix.length) : from
139}
140
141export function cardSource(c: Pick<TeamCard, 'from' | 'tag'>, teamId: string): string {
142 const from = shortFrom(c.from, teamId)
143 return c.tag === 'general' ? from : `${from}/${c.tag}`
144}
145
146export type QuestionsView = {
147 cards: TeamCard[]
148 teamId: string
149 /** Ids of the cards shown expanded. */
150 expanded: string[]
151 toggle: (id: string) => void
152 /** Draw ASCII glyphs. Defaults to ASCII_GLYPHS. */
153 ascii?: boolean
154 /** Cells across the pane body (`bodyColumns`). The headline is cut to fit; absent means no cut. */
155 columns?: number
156}
157
158/** The marker, a space and the status glyph that open a headline: each glyph is one column (live check, 40 columns). */
159const HEAD_COLUMNS = 3
160
161/** Cut `text` to `room` columns with an ellipsis at the cut. A Text inside a Button does not truncate by itself. */
162export function cutTail(text: string, room: number | undefined): string {
163 if (room === undefined) return text
164 const chars = Array.from(text)
165 return chars.length <= room ? text : `${chars.slice(0, Math.max(room - 1, 0)).join('')}…`
166}
167
168/** The question log: every card newest first, one collapsible row each. Enter or a click expands the full card. */
169export function drawQuestions({ Box, Text, Button }: Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>,
170 { cards, teamId, expanded, toggle, ascii = ASCII_GLYPHS, columns }: QuestionsView,
171) {
172 const waiting = (c: TeamCard) => c.urgent && (c.status === 'open' || c.status === 'assumed')
173 const status = (c: TeamCard) => (waiting(c) ? CARD_GLYPH.urgent : CARD_GLYPH.status[c.status])
174 const glyph = (g: { glyph: string; ascii: string }) => (ascii ? g.ascii : g.glyph)
175 const headline = (c: TeamCard, open: boolean) => (
176 <Text wrap="truncate-end" dimColor={status(c).dim}>
177 {glyph(CARD_GLYPH.expand[open ? 'open' : 'collapsed'])} <Text color={status(c).color}>{glyph(status(c))}</Text>
178 {cutTail(
179 ` ${c.id}${c.decision === undefined ? '' : ` #${c.decision}`} ${glyph(CARD_GLYPH.door[c.door])} `
180 + `${cardSource(c, teamId)}: ${c.question}`,
181 columns === undefined ? undefined : columns - HEAD_COLUMNS,
182 )}
183 </Text>
184 )
185 const lines = (c: TeamCard) => [
186 c.question,
187 `Context: ${c.context}`,
188 ...c.options.map((o, i) => `${i + 1}. ${o.option} (${o.cost})`),
189 `Rec: ${c.recommendation}`,
190 `Blocks: ${c.blocks}`,
191 `Rework: ${c.rework} Door: ${c.door}`,
192 ...(c.reason === undefined ? [] : [`Reason: ${c.reason}`]),
193 ]
194 return (
195 <Box flexDirection="column">
196 {cards.length === 0 && <Text dimColor>no questions yet</Text>}
197 {[...cards].sort((a, b) => b.n - a.n).flatMap(c => {
198 const open = expanded.includes(c.id)
199 return [
200 <Button key={c.id} plain onPress={() => toggle(c.id)}>{headline(c, open)}</Button>,
201 ...(open ? [(
202 <Box key={`${c.id}:body`} flexDirection="column" paddingLeft={4}>
203 {lines(c).map((l, i) => <Text key={i}>{l}</Text>)}
204 </Box>
205 )] : []),
206 ]
207 })}
208 </Box>
209 )
210}
211hooks/mod/paths.ts 35 lines1import type { Io } from './io'
2
3/**
4 * The main checkout of a session root: the parent of the common git dir when that ends in `/.git`
5 * (the same from a linked worktree), else the git top level, else the session root. Same rule as
6 * `team_project_root` in lib/run-dir.sh. `ask` runs `git rev-parse <args>` from the session root
7 * and answers its trimmed stdout, '' when git fails. null means git could not run (timeout, no
8 * spawn): the caller must not cache that.
9 */
10export async function mainCheckout(
11 root: string,
12 ask: (args: string[]) => Promise<string | null>,
13): Promise<string | null> {
14 const common = await ask(['--path-format=absolute', '--git-common-dir'])
15 if (common === null) return null
16 if (common.startsWith('/') && common.endsWith('/.git')) return common.slice(0, -'/.git'.length)
17 const top = await ask(['--show-toplevel'])
18 if (top === null) return null
19 return top || root
20}
21
22/**
23 * The run directory, absolute. A relative `TEAM_SCRATCH` is joined onto the main checkout of the
24 * session's project root (`io.root`), which a shell `cd` does not move. The session's cwd would
25 * follow the `cd` and lose the run.
26 */
27export async function runDir(io: Io): Promise<string> {
28 const scratch = (await io.envGet('TEAM_SCRATCH')) ?? 'scratchpad/current'
29 return scratch.startsWith('/') ? scratch : `${await io.root()}/${scratch}`
30}
31
32export async function teamDir(io: Io): Promise<string> {
33 return `${await runDir(io)}/.team`
34}
35hooks/mod/plan.ts 39 lines1import type { TeamPlan, TeamPlanItem } from '../../types'
2
3const ITEM = /^\s*[-*]\s+\[([xX>? ])\]\s*(.*?)\s*$/
4const SECTIONS = new Set(['WAITS ON YOU', 'DONE', 'RUNNING', 'NEXT'])
5const BUCKET = { x: 'done', '>': 'running', ' ': 'next', '?': 'waits' } as const
6
7/** Buckets items by their mark, not their heading: the orchestrator flips a
8 * mark in place and does not always move the line to the matching section. */
9export function parsePlan(text: string): TeamPlan {
10 const plan: TeamPlan = { title: '', waits: [], done: [], running: [], next: [] }
11 let inPlan = false
12 for (const line of text.split('\n')) {
13 if (line.startsWith('# ') && !plan.title) {
14 plan.title = line.slice(2).trim()
15 } else if (line.startsWith('## ')) {
16 inPlan = SECTIONS.has(line.slice(3).trim().toUpperCase())
17 } else {
18 const m = ITEM.exec(line)
19 if (!m || !inPlan) continue
20 const mark = (m[1] ?? ' ').toLowerCase() as TeamPlanItem['mark']
21 plan[BUCKET[mark]].push({ mark, text: m[2] ?? '' })
22 }
23 }
24 return plan
25}
26
27/** The most DONE items the pane ever shows, however tall it is. */
28export const DONE_CAP = 10
29
30/** Fits the plan into `rows` item lines. DONE keeps at most its newest `DONE_CAP`
31 * items, fewer when the leftover rows are short; it gives up its oldest items first.
32 * WAITS, RUNNING and NEXT are never cut. */
33export function fitPlan(plan: TeamPlan, rows: number): { plan: TeamPlan; hiddenDone: number } {
34 const left = Math.max(rows - plan.waits.length - plan.running.length - plan.next.length, 0)
35 const room = Math.min(DONE_CAP, left)
36 const done = plan.done.slice(Math.max(plan.done.length - room, 0))
37 return { plan: { ...plan, done }, hiddenDone: plan.done.length - done.length }
38}
39hooks/mod/version.ts 11 lines1/** The `version` field of plugin.json text. Missing text, bad JSON or no text field give null. */
2export function pluginVersion(text: string | null): string | null {
3 if (text === null) return null
4 try {
5 const version = (JSON.parse(text) as { version?: unknown } | null)?.version
6 return typeof version === 'string' && version !== '' ? version : null
7 } catch {
8 return null
9 }
10}
11hooks/mod/decide.ts 220 lines1import type { TeamCard } from '../../types'
2import { envoyConfig } from './activation'
3import type { TeamConfig } from './activation'
4import { queueGroups } from './cards'
5import { writeJson } from './io'
6import type { Io, ToolResult } from './io'
7import { runDir, teamDir } from './paths'
8import { goneSince } from './prompt-hold'
9import { readCards, writeCard } from './questions'
10
11export type DecisionEntry = {
12 n: number
13 cards: { id: string; from: string; tag: string }[]
14 answer: string
15 rationale: string
16 overrides: string[]
17 at: number
18}
19
20const fail = (result: string): ToolResult => ({ result, isError: true })
21
22const isText = (v: unknown): v is string => typeof v === 'string' && v.trim() !== ''
23
24/** The run config, or the refusal when this session does not hold the envoy role. */
25export async function envoyOnly(io: Io, tool: string): Promise<TeamConfig | ToolResult> {
26 return (await envoyConfig(io)) ?? fail(`${tool} works only in the envoy session`)
27}
28
29export async function queueTool(io: Io, input: unknown): Promise<ToolResult> {
30 const cfg = await envoyOnly(io, 'queue')
31 if ('result' in cfg) return cfg
32 const tag = (input as { tag?: unknown } | null)?.tag
33 const cards = await readCards(io, await teamDir(io))
34 return { result: JSON.stringify({ groups: queueGroups(cards, typeof tag === 'string' ? tag : undefined) }) }
35}
36
37/** 1 + the highest decision number in the file, amendments (3a) counted under their number. */
38export function nextDecision(text: string): number {
39 const numbers = [...text.matchAll(/^(\d+)[a-z]?\.\s/gm)].map(m => Number(m[1]))
40 return Math.max(0, ...numbers) + 1
41}
42
43export const decisionParagraph = (n: number, date: string, answer: string, rationale: string, ids: string[]) =>
44 `${n}. (${date}) ${answer} Why: ${rationale} Cards: ${ids.join(', ')}.\n`
45
46type DecideInput =
47 | { obsolete: true; cards: string[]; reason: string }
48 | { obsolete: false; cards: string[]; answer: string; rationale: string; overrides: string[] }
49
50function checkDecide(input: unknown): DecideInput | string {
51 const v = (input ?? {}) as Record<string, unknown>
52 const ids = v.cards
53 if (!Array.isArray(ids) || ids.length === 0 || !ids.every(id => typeof id === 'string' && /^Q-\d+$/.test(id))) {
54 return 'cards must list at least one Q-<n> id'
55 }
56 const listed = v.overrides ?? []
57 if (!Array.isArray(listed) || !listed.every((id): id is string => typeof id === 'string')) {
58 return 'overrides must list Q-<n> ids'
59 }
60 const overrides = [...new Set<string>(listed)]
61 const cards = [...new Set<string>(ids)]
62 if (v.obsolete === true) {
63 if (!isText(v.reason)) return 'reason is required to mark cards obsolete'
64 return { obsolete: true, cards, reason: v.reason }
65 }
66 if (!isText(v.answer) || !isText(v.rationale)) return 'answer and rationale are required'
67 // U+2028 and U+2029 count as line breaks: with the m flag, `^` matches after them (nextDecision).
68 if (/[\r\n\u{2028}\u{2029}]/u.test(v.answer)) return 'answer must be one line'
69 if (/[\r\n\u{2028}\u{2029}]/u.test(v.rationale)) return 'rationale must be one line'
70 return { obsolete: false, cards, answer: v.answer, rationale: v.rationale, overrides }
71}
72
73const unusable = (card: TeamCard) =>
74 card.status === 'answered' ? `${card.id} is already answered (decision ${card.decision})`
75 : card.status === 'obsolete' ? `${card.id} is already obsolete`
76 : null
77
78// One chain for the module: two calls in flight run one at a time, so each reads the
79// decisions file after the one before it has written. A failed call must not break the chain.
80let decideChain: Promise<unknown> = Promise.resolve()
81
82export function decideTool(io: Io, input: unknown): Promise<ToolResult> {
83 const run = decideChain.then(() => decideOnce(io, input))
84 decideChain = run.catch(() => undefined)
85 return run
86}
87
88async function decideOnce(io: Io, input: unknown): Promise<ToolResult> {
89 const cfg = await envoyOnly(io, 'decide')
90 if ('result' in cfg) return cfg
91 const checked = checkDecide(input)
92 if (typeof checked === 'string') return fail(checked)
93
94 const teamdir = await teamDir(io)
95 const byId = new Map((await readCards(io, teamdir)).map(c => [c.id, c]))
96 const picked: TeamCard[] = []
97 for (const id of checked.cards) {
98 const card = byId.get(id)
99 if (!card) return fail(`no card ${id}`)
100 const bad = unusable(card)
101 if (bad) return fail(bad)
102 picked.push(card)
103 }
104
105 if (checked.obsolete) {
106 for (const card of picked) await writeCard(io, teamdir, { ...card, status: 'obsolete', reason: checked.reason })
107 return { result: `Obsolete: ${checked.cards.join(', ')}` }
108 }
109
110 for (const id of checked.overrides) {
111 if (byId.get(id)?.status !== 'assumed' || !checked.cards.includes(id)) {
112 return fail(`${id} is not an assumed card of this decision`)
113 }
114 }
115 const { answer, rationale, overrides } = checked
116 const path = `${await runDir(io)}/decisions-${cfg.ticket}.md`
117 const text = await io.readText(path)
118 if (text === null) return fail(`no decisions file: ${path}`)
119
120 const n = nextDecision(text)
121 const now = await io.now()
122 const date = new Date(now).toISOString().slice(0, 10)
123 const paragraph = decisionParagraph(n, date, answer, rationale, checked.cards)
124 // Not atomic, by decision 31: paragraph, then ledger, then cards. If a write throws after the
125 // paragraph, the file holds a paragraph with no ledger entry (no DECISION line), the cards stay
126 // open, and a retry appends a second paragraph under the next number.
127 await io.writeText(path, `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}${paragraph}`)
128
129 const entry: DecisionEntry = {
130 n,
131 cards: picked.map(c => ({ id: c.id, from: c.from, tag: c.tag })),
132 answer,
133 rationale,
134 overrides,
135 at: now,
136 }
137 await writeJson(io, `${teamdir}/decisions/${n}.json`, entry)
138 for (const card of picked) await writeCard(io, teamdir, { ...card, status: 'answered', decision: n })
139 return { result: [`Decision ${n}`, ...goneNotes(picked)].join('\n') }
140}
141
142/**
143 * One note for each answered card whose prompt already looks gone (the hold window of the stale rule): the
144 * decision still stands, the envoy can tell the human the prompt was probably answered in the pane.
145 */
146function goneNotes(cards: TeamCard[]): string[] {
147 const notes: string[] = []
148 for (const card of cards) {
149 const since = card.prompt ? goneSince(card.id) : undefined
150 if (since === undefined) continue
151 const at = new Date(since)
152 const two = (n: number) => String(n).padStart(2, '0')
153 const time = `${two(at.getHours())}:${two(at.getMinutes())}:${two(at.getSeconds())}`
154 notes.push(`Note: the permission prompt behind ${card.id} looks gone since ${time}.`)
155 }
156 return notes
157}
158
159async function closeOnce(
160 io: Io, id: string, link: NonNullable<TeamCard['prompt']>, text: string, next?: string,
161): Promise<TeamCard | null> {
162 const teamdir = await teamDir(io)
163 const card = (await readCards(io, teamdir)).find(c => c.id === id)
164 if (!card || (card.status !== 'open' && card.status !== 'assumed')) return null
165 if (card.prompt?.session !== link.session || card.prompt.dialog !== link.dialog) return null
166 const closed: TeamCard = {
167 ...card, status: 'obsolete', reason: `Closed by the team mod: ${text}.`, closed_by: 'team mod',
168 ...(next ? { next_dialog: next } : {}),
169 }
170 await writeCard(io, teamdir, closed)
171 return closed
172}
173
174/**
175 * The team mod closes a card about a permission prompt that is gone. It runs on the same chain as `decide`, and
176 * re-reads the card inside the chain: a card the human answered first is left alone (`null`), and a `decide`
177 * that comes after finds the card obsolete and refuses. It writes no decision, so no DECISION line goes out.
178 * `next` is the dialog of the different prompt that now shows; it goes on the card as `next_dialog`.
179 */
180export function closeStalePrompt(
181 io: Io, id: string, link: NonNullable<TeamCard['prompt']>, text: string, next?: string,
182): Promise<TeamCard | null> {
183 const run = decideChain.then(() => closeOnce(io, id, link, text, next))
184 decideChain = run.catch(() => undefined)
185 return run
186}
187
188export const QUEUE_TOOL_SPEC = {
189 name: 'queue',
190 description: 'List the open and assumed cards grouped by tag, most pressing first. Envoy session only.',
191 inputSchema: {
192 type: 'object',
193 properties: { tag: { type: 'string', description: 'Only this group.' } },
194 },
195}
196
197export const DECIDE_TOOL_SPEC = {
198 name: 'decide',
199 description:
200 'Close cards with one numbered decision, or mark them obsolete. List in overrides the assumed cards ' +
201 'whose assumption this answer changes. Envoy session only. Returns "Decision <n>".',
202 inputSchema: {
203 type: 'object',
204 properties: {
205 cards: { type: 'array', items: { type: 'string' }, description: 'Card ids, Q-<n>.' },
206 answer: {
207 type: 'string',
208 description:
209 'The decision the human gave, with the chosen option by its meaning, not a bare ' +
210 'letter or a bare "yes".',
211 },
212 rationale: { type: 'string', description: 'Why, in one sentence.' },
213 overrides: { type: 'array', items: { type: 'string' }, description: 'Assumed cards this answer changes.' },
214 obsolete: { type: 'boolean', description: 'true: mark the cards obsolete instead of answering them.' },
215 reason: { type: 'string', description: 'Why the cards are obsolete.' },
216 },
217 required: ['cards'],
218 },
219}
220