The Index-driven development pipeline: Inspector Lestrade (triage), Dr. Watson (dev work), and Sherlock Holmes (code review). A Claude scheduled task called…

A Claude Code plugin that runs a three-agent development pipeline against a GitHub project board. Items flow from triage → development → review without you touching them. Part of the claude-workbench marketplace.
You work out of a GitHub project board. New issues land with no acceptance criteria. Well-refined ones sit in Ready. Work-in-progress has open draft PRs. PRs waiting on review pile up.
This plugin runs a team of agents on a local 20-minute clock that move items through the pipeline for you — and records what the reviews teach as it goes, so the team stops repeating itself:
claude-opus-5-5[1m] at medium effort, Sonnet lenses) — triage. Reads items in the Inbox lane, writes acceptance criteria as a managed follow-up comment on the issue (the description is left untouched). Before scoring, the draft AC is checked by four blind lens sub-agents (malicious-compliance, testability, completeness, edge-case) that each try to find a gap Holmes and Watson would otherwise hit downstream — a much more expensive place to catch it, since Lestrade only ever sees an issue once while Watson and Holmes cycle back on it every bounce. Real gaps get folded in with one bounded tightening pass, never a re-verification loop; a lightweight comment marks when the AC changed this way. Scores WSJF, moves them to Backlog for your review. The WSJF write also lands two GitHub-native issue attributes The Index derives server-side: the issue Type (PBI) and an issue-level Priority (Urgent/High/Medium/Low) mapped from the WSJF — org-repo-only and best-effort. Also runs blocker + consolidation sweeps: after a repo gets fresh triage work, he re-reads all of its open issues and (1) marks blocked-by dependencies (native GitHub issue dependencies, additive only) so blocked items stay out of Dr. Watson's queue, and (2) consolidates follow-ups — folds expand-from comments into the issue they target and merges unmistakable near-duplicate follow-ups into the earliest anchor (native duplicate-close, high bar, ambiguous clusters flagged not closed) so the backlog stops sprawling.claude-opus-5-5[1m] at medium effort, $10/run cap) — development. Has two modes: Direct mode, the default (invocable as a sub-agent from Claude Code or Cowork for ad-hoc dev work — no The Index calls, just runs the /develop skill in a sub-agent context, and hands its work back as an uncommitted working tree for the dispatching session to commit) and The Index mode, entered only on an explicit Item ID: <n> token (Dispatch-driven, picks the top Ready/In Progress item, clones the repo, writes code and tests against AC, opens a PR, moves to In Review). Ambiguous prose resolves to Direct mode, never to the board. Both modes follow the /develop skill for the actual coding.claude-opus-5-5[1m] parent at medium effort, Sonnet lenses, $10/run cap) — code review. Has two modes, the same way Watson does: Local mode, the default (invocable as a sub-agent on a six-slot prose brief — reviews the uncommitted working tree in the given workdir, tracked changes and untracked files, against the brief's Acceptance: list as the rubric it never amends, and returns the verdict as prose) and The Index mode, entered only on an explicit Item ID: <n> token (Dispatch-driven, reviews the board item's PR and posts an App-signed verdict). Ambiguous prose resolves to Local mode, never to the board. Local mode makes no The Index call and no GitHub write at all — no review, no comment, no issue — so it is safe on any repo, and it closes the loop on Watson's Direct mode, whose output is exactly an uncommitted tree with no review path otherwise. It replaces the board-coupled steps rather than skipping them: the brief is the rubric, the workdir is the evidence room (never cloned, never written to — a harness-level guard enforces that, see Review guard below), and the repo's own suite is run locally in place of reading CI, because the toolchain objection that keeps Index mode off local test runs does not hold when the agent is already in the repo's directory on your machine. It records a vault note per local verdict but deliberately never touches the top-lessons.md digest, since local reviews are a separate population whose counts would skew a frequency ranking. Everything in between — the lens fan-out, adversarial verification, the memory pass, the finding-routing matrix — runs unchanged. The rest of this entry describes The Index mode: reviews open PRs, approves or requests changes. Escalates to you after 3 change rounds — but your input resets that count: comment, review, or weigh in on the PR and the window restarts from your last word, so an escalated PR you've decided on gets a fresh review instead of bouncing straight back. Reviews fan out across blind, read-only lens sub-agents (AC conformance, correctness, security, test honesty), with every blocker adversarially verified before it lands — a 3-agent red-team/blue-team/auditor pipeline handles security-lens findings every round and hard defects on the PR's first review, and a single skeptic handles the rest, soft observations included (the fullest check lands where a wrong verdict costs a round, not on a naming nit). After verification, Holmes (and only Holmes — no sub-agent touches the vault) checks each surviving finding against the memory vault for relevant context — a documented decision that reframes it, a past incident that reinforces it — always re-verified against the current tree before it's trusted, never used to waive a real defect or mark an AC item met. Only the parent writes, so there's still exactly one App-signed verdict. Falls back to a single inline pass when the fan-out is unavailable. Findings route by the coherent unit of work — what the issue is really about — then coupling and locality: a finding that belongs to the unit blocks and is fixed in this PR, even in untouched code the diff never caused, because a half-delivered unit is itself the defect. On top of that, anything actionable in the code a PR touched blocks (request changes, however minor), a bug, security problem, integrity problem, or test defect the PR's repo can fix blocks wherever it lives in that repo, with changes requested in the same PR even when it predates the PR or sits outside its scope (one only another repo can fix goes to that repo's owner, and does not hold the PR), and — coupling beating locality — untouched code the diff made stale, inconsistent, or wrong blocks too. The self-test: block and fix here if EITHER the diff caused it OR it belongs to the coherent unit — a follow-up only when both are false. The precise routing rule lives in Holmes's canonical review contract (agents/holmes.md, §4e/§5). The non-blocking follow-up tier is then gated by materiality, default-deny: it holds only findings unrelated to the unit, and most of those — one-off cosmetics (naming, small duplication, style) — are noted in the verdict, not tracked. Only unrelated systemic/substantial debt (a schedulable chunk with its own testable "done") earns one tracked issue, tagged Tracked under:, capped at one new anchor per PR — the materiality bar that stops the follow-up flood. When Holmes does track, he expands the earliest related open issue in place (a comment Lestrade folds into its acceptance criteria) rather than opening a near-duplicate, and opens a new anchor via create_issue (App-signed as Holmes, board-added and PBI-typed) only when nothing related exists. A class of sites violating one invariant (a containment guard, a null-check, a helper every caller owes) is swept whole: if the class belongs to the unit it's folded into the PR; if it's an unrelated anti-pattern agents will replicate it becomes one umbrella issue with a checkbox per site — either way closing the class at once rather than minting a fresh single-site issue every review, the treadmill that otherwise turns one finding into an endless #A → #B → #C chain. A finding gets the same disposition regardless of verdict, so a clean PR never generates more tracked work than a messy one: on a change request, unit-belonging findings are blockers Watson folds into the same PR, unrelated cosmetics are optional (fix if cheap, else skip), and the unrelated hazard/debt tier is tracked exactly as on approval.A fourth component — Dispatch — is the Claude scheduled task workbench-dev-team-dispatch. It polls the board on its schedule and fires the right agent for each pending item. Dispatch is the only thing that's scheduled; the three agents run as dispatched subprocesses.
Lestrade, Watson, and Holmes used to have no memory of their own reviews: nothing recorded what Holmes rejected, why, or how it got fixed, so the same lessons got re-taught every review (test-honesty is ~38% of all rejections, fail-open ~11%, doc-drift ~11%). There's no separate harvesting agent for this — Holmes is the only one who holds both halves of a rejection (what he flagged, and whether the next push actually fixed it), so he records it himself, live, at re-review: one atomic vault note per bounce or AC-dispute event, categorized against a fixed taxonomy, plus an incrementally-refreshed dev-team/top-lessons.md digest (recurring categories, frequency-ranked, each with the concrete prevention rule). Watson reads that digest and searches the vault for anything task-specific before coding; Lestrade reads it before writing acceptance criteria, so the pipeline gets smarter instead of repeating itself on both sides — what gets built and what gets asked for. Your own corrections take a second channel, because no review rejection records them: they live under feedback/ in the vault, and all three agents are required to search it: Watson before building (/develop requires it in every lane, Direct mode included), Holmes before judging, in both Local and Index mode, and Lestrade before writing acceptance criteria. Your corrections bind every stage, and a stage that never reads them never catches a violation of one.
A review note never replaces an existing one. Holmes builds each learnings note's path himself, and the memory MCP's write replaces any note already at that path. A read cannot prove a path is free, because the server answers Document not found both for a missing file and for a note it cannot parse. So each name ends with the time to the second and a token from openssl rand -hex 3, and he writes only after a read of that path answers Document not found. A write that still answers created: false replaced a note, and his report names the path so the old note can be restored from the vault's git history. agents/lint-vault-note-paths.sh fails when a note write by a built path, in any Markdown file, loses its unique name or its read, or stands outside a code fence.
/plugin marketplace add mike-bronner/claude-workbench
/plugin install workbench-dev-team@claude-workbench
That installs the agents, the dispatcher script, and the bundled skills (see below). Nothing is scheduled yet.
The plugin ships three skills for general use, plus one skill the agents write by:
develop and git-commit — universal development standards. They register themselves globally through the plugin's session rules (hooks/mods/session-rules.ts), which the hooks module sends as one shared system-prompt section, and as context at each sub-agent's start. They apply to every Claude Code / Cowork session, claude -p runs included, not just dev-team agents. Both are also packageable as .skill files for Claude Chat (Mac app) where plugins aren't supported but skills are.orchestrate — runs the team as background sub-agents from any interactive session (see below). The same session rules make every session aware the team is available for delegation.One more skill exists for the agents rather than for you. comms-style is how Lestrade, Watson, and Holmes write every piece of prose that isn't code — ticket comments, PR bodies, review verdicts — modeled on ASD-STE100 (Simplified Technical English).
Each agent's long, situational procedure is not a skill. It lives in references/<agent>/, and the agent reads it by path: each agent prompt in agents/ is a thin router that keeps the always-relevant rules inline and points at its reference file for the detail it only needs at one moment — Holmes's review phases and sub-agent prompt skeletons plus his Local-mode path (references/holmes/), Watson's Index-mode pipeline (references/watson/), Lestrade's acceptance-criteria lenses and Sweep mode (references/lestrade/). Keeping them out of skills/ keeps their descriptions out of every session's skill listing, and the router pattern keeps the per-dispatch prompt small without putting any rule out of reach.
Plugin configuration lives in a slash command (/workbench-dev-team:setup), not a skill — see the Setup section below.
developUniversal dev workflow + standards: orient before writing (the repo's CLAUDE.md, AGENTS.md, CONTRIBUTING.md, .ai/ rules, and review wiki), plan before coding (including a required feedback/ vault search), every change gets a test, no committed secrets, lint before pushing. Triggers whenever code is being implemented, fixed, refactored, or tested — manual or agent-driven.
It names three lanes (foreground, sub-agent, scheduled pipeline) and ends each step the way that lane can: a sub-agent finishes with an uncommitted tree and a report, never a commit or a PR. Includes a decision protocol that presents three options in one table (Option, Pros, Cons, and a Grade against every acceptance criterion), then a one- or two-sentence recommendation, for a meaningful fork the human has not already decided — implementation approach, library choice, scope decisions, a public interface. A fork they already decided is not asked again. In the foreground the human decides through AskUserQuestion, with each option's grade and any warning in its description; a sub-agent picks and records the assumption below the blocking-uncertainty bar and stops with the options above it. Trivial choices (mechanical translation, following existing repo conventions, naming, one-line obvious fixes) are exempt.
Also defines the commit lanes (see Commits below): a sub-agent commits, merges, and pushes nothing and hands its tree back uncommitted, Index-mode development never asks about committing or pushing, Claude Code's permission prompt is the backstop on every git commit and git push, and a push that forces or deletes remote refs is refused outright.
Used by Watson internally in both operating modes. Also invocable directly in any plugin-aware Claude session.
git-commitGenerates commit messages using Conventional Commits + Gitmoji format. Triggers whenever a commit message is being composed — manual, scripted, or agent-driven (including Watson's PRs).
Format example:
feat: ✨ Add email validation endpoint.
Fixes: #789
Full type and emoji references at skills/git-commit/references/.
orchestrateTurns the current session into the team's orchestrator: dispatches Lestrade, Watson, and Holmes as background sub-agents (Agent tool, run_in_background), passing each agent's model from the shared config; maintains a roster table of who's working on what; relays verdicts and decision forks back to you; follows up on running agents via SendMessage. The main conversation stays lean — sub-agents do the heavy work in their own contexts and return summaries.
Watson supports brief-driven Direct mode for ad-hoc dev work with no board item, and Holmes a brief-driven Local mode that reviews the resulting uncommitted tree. Only Lestrade is Index-coupled and needs a board item ID.
The skill also fixes who gets dispatched, and what they're told. Routing covers all three specialists: development goes to Watson, triage to Lestrade, review to Holmes, and the shape of the request says which. Anything ending in a changed file is Watson's, never general-purpose — a specialist loads develop and discovers the repo's conventions and test framework for itself, a generic agent doesn't. Read-only dispatches (Explore, Plan, general-purpose) stay legitimate and are called out as such.
Every handoff is written to a fixed six-slot brief — Workdir: / Goal: / Context: / Constraints: / Acceptance: / Done when: — read-only research dispatches included, which is what makes classifying a prompt as code work unnecessary in the first place. Workdir: is the absolute path, plus the branch or worktree when the human settled one (Workdir: /Users/mike/Developer/foo (branch: fix/retry-backoff)); a bare path stays valid and means there was no workspace decision to record. Goal: is bounded at one or two sentences, because it's the only slot tight enough to check a result against; Context: is prose and deliberately unbounded, since that's where the reasoning goes so Goal: doesn't have to carry it; Constraints: is bullets that each state their own reason, because a constraint without its reason gets obeyed literally and defeated in spirit. Acceptance: is the numbered list of criteria the work is graded against: the receiver grades its forks and its report against it, Holmes reviews against it, and it is where the criteria from /workbench-core:intake cross the handoff. For a Watson or Holmes Item ID: <n> run, the item's acceptance criteria from triage are that list. No length limit is stated anywhere — length was only ever a proxy for prescriptiveness, and the must-omit list (shell commands, numbered steps, named test paths, framework choices) attacks that directly. Constraints: may read "none"; Context: may not, and carries at least one sentence on why the task exists. The brief binds the receiver too, and in two ways: every agent in agents/ refuses a brief missing a slot and names what's missing, and an agent handed a complete-but-unusable brief stops and sends its questions back to the orchestrator instead of guessing — the bar there is blocking uncertainty only, so anything short of it proceeds with the assumption stated. The two fixed dispatch tokens (Item ID: <n>, Repo sweep: <owner/repo>) are exempt from both, since they aren't briefs. A third exemption is the orchestrator boundary itself: the template governs a dispatch that leaves an orchestrator for a specialist, and a specialist's own fan-out to internal workers is outside it. The measurement behind the rule already excluded that traffic — of 622 dispatches, the 422 sent from sessions that were themselves agent runs were counted as correct behaviour — the parent holds every fact those workers need, so Context: has nothing to recover, and their prompts are written against measured cost rather than to a template. It's stated as a boundary and not as a list of agents, so a specialist that grows a fan-out later inherits it with no edit. A companion PreToolUse gate in workbench-core checks one thing — that the slots are present — and refuses a handoff that drops one; judging whether the prose inside them is any good is the receiving agent's job, not a shell script's.
The orchestrator asks before a branch or a worktree is created. Not a prohibition — branches and worktrees are the wanted outcome of most dev work, and a PR is a normal finish line. What changed is who decides. Ahead of any dispatch whose work ends in a commit, the skill reads the target tree and asks in three cases: on main/master/trunk it proposes a branch name; on a feature branch already carrying unrelated work it names what's there and proposes a branch off the base; inside a worktree it confirms that worktree is the one meant for this task. All three end in a question to you, never in a refusal, and your answer is recorded in the brief's Workdir: slot so the sub-agent works where you said. Two Watsons on one repo still get separate worktrees, asked for the same way: you create them, and the orchestrator then dispatches one Watson per worktree. It never creates a worktree and never passes the Agent tool's worktree isolation, which workbench-core's provisioning guard denies. The reasoning, including why the answer widened Workdir: instead of adding a slot, sits in skills/orchestrate/references/brief-rationale.md, which loads only when a rule is challenged rather than on every orchestration.
Independent units dispatch together. Work in different repos or in files that do not overlap, read-only research, and reviews of a finished tree all go out at once, in one message. Local work (interactive sessions, Watson's Direct mode, Holmes's Local mode, research) has no count cap on sub-agents. The Index pipeline stays bounded on purpose: scheduled Dispatch starts one Watson per tick, and every Index-mode cap stays.
The skill also routes GitHub actions to the right executor. Two rules: (1) agent work products (formal reviews, AC, status moves) only ever go through The Index, signed as the dispatched agent — never gh; (2) your own actions (comments you dictate, merges you order) go through gh under your identity, on any repo. Whether a repo is Index-governed is answered by check_repo_access — a server-side tool that checks The Index GitHub App's installation list (spec in THE_INDEX_HANDOFF_ROUTING.md; until it ships, the skill degrades to a list_items scan and says so). Merges are never delegated to agents and only happen on your explicit request.
A sub-agent does not commit, merge, or push, and never asks to. It hands its work back uncommitted, with a diff summary, the full git status list, and a proposed message, and the orchestrator takes the uncommitted tree from there. Claude Code's permission prompt on each git commit, git push, and gh pr merge is the mechanical backstop. The scheduled pipeline commits and pushes unattended, inside its own clone and the scratch roots, splits the work into commits as Watson judges best, and never merges.
No agent disguises a command to get past a gate. Watson, Holmes, and Lestrade each carry a ## When a gate or guard refuses you section: never reword, split, encode, or rebuild a command to get past a gate or guard, and report the refusal instead. It exists because Holmes once got past the installed commit gate by building the words "commit" and "push" from pieces at run time. agents/lint-gate-refusal.sh pins the section in every agent file.
Every agent's scratch lands in a folder of its own, and the dev-team mod deletes it. Each agent file carries a ## Scratch folders section: make scratch with a bare mktemp -d. The mod points a dev-team agent's bare mktemp at a folder made for that run under a scratch root, the session scratchpad or ~/Developer/scratchpad when the harness names none, and deletes the folder at the end of a turn of that agent that finds no child it spawned still live (hooks/mods/scratch.ts). A child's end never deletes its parent's folder, since an ended agent may resume and read it again. A folder kept that way for a run that never resumes goes when the session ends: the mod records every folder it makes and has not deleted, and at session.end removes each one still under a scratch root, in one rm held to the end's short time budget. A folder that rm did not delete stays recorded for the next end. The rewrite stands only when the line reads back exactly as written plus the one template word, so a mktemp inside a quoted string or a heredoc is left alone. Three shared clones keep their own scratch-ro
hooks/register.ts 620 lines1// workbench-dev-team's hooks module, beside the command hooks in hooks.json.
2// It builds on workbench-core's $.workbench noun (dependencies in plugin.json).
3//
4// The logic is pure and lives in mods/. Every hook that touches `$` lives in
5// this file, because the engine follows `$` into no imported function, and a
6// plugin registers each event once.
7//
8// The scheduled path never reaches agent.spawn: it starts the mode type
9// directly (`claude -p --agent workbench-dev-team:watson-index`), and
10// bin/dispatch-agent.sh passes the rows' model and effort as flags. The
11// other hooks run in that process too.
12//
13// The /config rows reach this module as its options. Claude Code reloads the
14// module when one changes, so `register` runs again with the new values.
15
16import { atom, read, update } from 'claude-code'
17import type { EngineInterface, Register, Timer, TurnUsage } from 'claude-code'
18
19import type { RunsView } from '../types'
20
21import { BOARD_TIMEOUT_MS, EMPTY_BOARD, afterFetch, boardArgv, boardOutcome, cadenceMsOf, escalatedOf, isDue } from './mods/board'
22
23import { budgetNotice, contextOf, isOverBudget } from './mods/budget'
24import { DISPATCH_CONTEXT, dispatchDeny, dispatcherArgv, dispatchOutcome, dispatchResult, indexDispatchOf, isForcedBackground } from './mods/dispatch'
25import { outputOf, stopBlockOf, withStarted } from './mods/helper-wait'
26import type { Activity, Watch } from './mods/helper-wait'
27import type { Disk, ShellParse } from './mods/review-guard'
28import { isReviewerType, judgeWrites, refusalOf, reviewBash, reviewEdit } from './mods/review-guard'
29import { BOARD_PANE, RUNS_PANE, boardTree, runsTree } from './mods/panes'
30import type { LogEnd } from './mods/runs'
31import { LOG_DIR, RUNS_REFRESH_MS, endsOf, livePairsOf, markersOf, newestRuns, rowsOf, scanArgv } from './mods/runs'
32import { RULES, isRulesLane, isRulesSubagent, withRules } from './mods/session-rules'
33import { hasBareMktemp, hasLiveChild, isDeletable, pointMktemp, prefixOf, readsAsPointed, rootOf, sweepOf } from './mods/scratch'
34import type { CallerLane } from './mods/spawn'
35import {
36 CONFIG_MODES,
37 DEFAULT_BRANCHES,
38 branchDeny,
39 branchUnreadDeny,
40 configLineOf,
41 configTextOf,
42 familyOf,
43 isDevTeamType,
44 isGated,
45 isHolmesMode,
46 knobsOf,
47 lensSpawnOf,
48 modeTypeOf,
49 spawnFailedDeny,
50 withConfigLine,
51 workdirOf,
52} from './mods/spawn'
53
54async function gated($: EngineInterface, agentId: string | undefined): Promise<boolean> {
55 const lane = await $.workbench.callerLane(agentId === undefined ? {} : { agentId }).catch(() => 'main' as const)
56 const isOn = await $.workbench.orchestratorIsOn().catch(() => true)
57 return isGated(lane, isOn)
58}
59
60// ── Whose run a loop is ──────────────────────────────────────────────────────
61
62// A dev-team run, as the per-run state keys it: its agent type, and its agentId,
63// or `run` for the top-level loop of a `claude -p --agent` run. Undefined for
64// the main session and for every agent outside the dev-team.
65type Run = { type: string; key: string }
66
67async function runOf($: EngineInterface, agentId: string | undefined): Promise<Run | undefined> {
68 if (agentId !== undefined) {
69 const { value: type } = await $.state.get({ plugin: 'workbench-dev-team', key: 'agentType', id: agentId })
70 return isDevTeamType(type) && type !== undefined ? { type, key: agentId } : undefined
71 }
72 if ((await $.workbench.callerLane({})) !== 'top-level-agent') return undefined
73 const type = await $.env.get('CLAUDE_CODE_AGENT')
74 return isDevTeamType(type) && type !== undefined ? { type, key: 'run' } : undefined
75}
76
77// The type of the loop a spawn happens in: the top-level `--agent` type, or
78// none, for a main-loop spawn; the type the mod kept, or the one
79// $.agent.list() gives, for a sub-agent's. Undefined when it cannot be told.
80async function spawnerTypeOf($: EngineInterface, parentAgentId: string | undefined): Promise<string | undefined> {
81 if (parentAgentId === undefined) return $.env.get('CLAUDE_CODE_AGENT').catch(() => undefined)
82 const { value: kept } = await $.state.get({ plugin: 'workbench-dev-team', key: 'agentType', id: parentAgentId })
83 if (kept !== undefined) return kept
84 const agents = await $.agent.list().catch(() => undefined)
85 return agents?.find(agent => agent.id === parentAgentId)?.type
86}
87
88// ── Scratch folders ──────────────────────────────────────────────────────────
89
90// The run's scratch folder: the one it has, or a new one under the first
91// scratch root, made with mktemp. Undefined when none can be made.
92async function scratchFolderOf($: EngineInterface, run: Run): Promise<string | undefined> {
93 const { value: kept } = await $.state.get({ plugin: 'workbench-dev-team', key: 'scratch', id: run.key })
94 if (kept && (await $.fs.exists(kept).catch(() => false))) return kept
95 const roots = await $.workbench.scratchRoots()
96 const root = rootOf(roots)
97 if (root === undefined) return undefined
98 const made = await $.process.run(['mktemp', '-d', `${root}/${prefixOf(run.type)}.XXXXXX`])
99 const folder = made.stdout.trim()
100 if (made.exitCode !== 0 || !isDeletable(folder, roots)) return undefined
101 await $.state.set({ plugin: 'workbench-dev-team', key: 'scratch', id: run.key }, folder)
102 await recordFolder($, [folder], 'add')
103 return folder
104}
105
106const FOLDERS = { plugin: 'workbench-dev-team', key: 'scratchFolders' } as const
107
108// Adds folders to the record, or takes them out. Two runs can write at once,
109// so the write lands only on the version it read, and is tried again when
110// another write came first.
111async function recordFolder($: EngineInterface, folders: readonly string[], change: 'add' | 'remove'): Promise<void> {
112 for (let attempt = 0; attempt < 8; attempt++) {
113 const { value = [], version } = await $.state.get(FOLDERS)
114 const rest = value.filter(kept => !folders.includes(kept))
115 if ((await $.state.set(FOLDERS, change === 'add' ? [...rest, ...folders] : rest, { ifVersion: version })).isSet) return
116 }
117}
118
119// The end of the session: every folder still recorded is deleted, in one rm,
120// when it lies under a scratch root. Each was kept because its run had not
121// ended, or a child of its run was live at the run's last turn, and nothing is
122// live once the session ends.
123// The rm is held to what the end's one short budget leaves, and skipped when
124// too little is left. A folder outside every root is never deleted. Only what
125// an rm that exited 0 deleted leaves the record: a folder the rm skipped, or
126// one an rm that failed or ran out of time may have left, stays recorded.
127async function endSession($: EngineInterface, budget: { remainingMs: number }): Promise<void> {
128 const { value: folders = [] } = await $.state.get(FOLDERS)
129 if (folders.length === 0) return
130 const sweep = sweepOf(folders, await $.workbench.scratchRoots(), budget.remainingMs)
131 if (sweep === undefined) return
132 const removed = await $.process.run(['rm', '-rf', '--', ...sweep.doomed], { timeoutMs: sweep.timeoutMs }).catch(() => undefined)
133 if (removed?.exitCode === 0) await recordFolder($, sweep.doomed, 'remove')
134}
135
136// The Bash line with a dev-team agent's bare mktemp pointed at its folder, or
137// the line as written when it has none, or when anything here fails: a mktemp
138// left in $TMPDIR is how the line ran before the mod.
139async function withScratch($: EngineInterface, agentId: string | undefined, line: string): Promise<string> {
140 if (!line.includes('mktemp')) return line
141 try {
142 const before = await $.workbench.parseShell(line)
143 if (!hasBareMktemp(before)) return line
144 const run = await runOf($, agentId)
145 if (run === undefined) return line
146 const folder = await scratchFolderOf($, run)
147 if (folder === undefined) return line
148 const pointed = pointMktemp(line, folder)
149 if (pointed === undefined) return line
150 return readsAsPointed(before, await $.workbench.parseShell(pointed), folder) ? pointed : line
151 } catch {
152 return line
153 }
154}
155
156// The end of a turn: the run's scratch folder deleted, unless a child the run
157// spawned is still live, and its budget notice reset. A child's end never
158// deletes its parent's folder: an ended agent may resume, as Holmes does when
159// his background helpers report, and read it again. A folder kept for a live
160// child goes at the end of the next turn that finds none. When the agent list
161// cannot be read, the folder stays.
162async function endRun($: EngineInterface, agentId: string | undefined): Promise<void> {
163 const key = agentId ?? ((await $.workbench.callerLane({})) === 'top-level-agent' ? 'run' : undefined)
164 if (key === undefined) return
165 const { value: folder } = await $.state.get({ plugin: 'workbench-dev-team', key: 'scratch', id: key })
166 const agents = folder ? await $.agent.list().catch(() => undefined) : undefined
167 if (folder && agents !== undefined && !hasLiveChild(agents, agentId)) {
168 if (isDeletable(folder, await $.workbench.scratchRoots())) await $.process.run(['rm', '-rf', '--', folder])
169 await $.state.set({ plugin: 'workbench-dev-team', key: 'scratch', id: key }, '')
170 await recordFolder($, [folder], 'remove')
171 }
172 const { value: told } = await $.state.get({ plugin: 'workbench-dev-team', key: 'overBudget', id: key })
173 if (told) await $.state.set({ plugin: 'workbench-dev-team', key: 'overBudget', id: key }, false)
174}
175
176async function recordStarted($: EngineInterface, agentId: string | undefined, result: { result?: unknown; text?: unknown }): Promise<void> {
177 const id = (result.result as { backgroundTaskId?: unknown } | undefined)?.backgroundTaskId
178 if (agentId === undefined || typeof id !== 'string' || id === '') return
179 const key = { plugin: 'workbench-dev-team', key: 'backgroundTasks', id: agentId } as const
180 for (let attempt = 0; attempt < 8; attempt++) {
181 const { value = [], version } = await $.state.get(key)
182 const output = outputOf(id, result.text)
183 if ((await $.state.set(key, withStarted(value, output === undefined ? { id } : { id, output }), { ifVersion: version })).isSet) return
184 }
185}
186
187async function stopBlock(
188 $: EngineInterface,
189 agentId: string,
190 inFlight: readonly { id: string; command?: string; description: string }[],
191 activity: ReadonlyMap<string, Activity>,
192 watches: Map<string, Watch>,
193): Promise<string | undefined> {
194 const { value: type } = await $.state.get({ plugin: 'workbench-dev-team', key: 'agentType', id: agentId })
195 if (!isDevTeamType(type)) return undefined
196 const { value: started = [] } = await $.state.get({ plugin: 'workbench-dev-team', key: 'backgroundTasks', id: agentId })
197 const agents = await $.agent.list().catch(() => [])
198 const sizes = new Map<string, number>()
199 for (const entry of started) {
200 if (entry.output === undefined || !inFlight.some(task => task.id === entry.id)) continue
201 const size = await $.fs.stat(entry.output).then(stat => stat.size, () => undefined)
202 if (size !== undefined) sizes.set(entry.output, size)
203 }
204 return stopBlockOf(agentId, agents, started, inFlight, { helper: id => activity.get(id), outputSize: path => sizes.get(path) }, watches)
205}
206
207// ── The context budget ───────────────────────────────────────────────────────
208
209async function measure($: EngineInterface, agentId: string | undefined, usage: TurnUsage | null): Promise<void> {
210 const tokens = contextOf(usage)
211 if (!isOverBudget(tokens) || tokens === undefined) return
212 const run = await runOf($, agentId)
213 if (run === undefined) return
214 const { value: told } = await $.state.get({ plugin: 'workbench-dev-team', key: 'overBudget', id: run.key })
215 if (told) return
216 await $.state.set({ plugin: 'workbench-dev-team', key: 'overBudget', id: run.key }, true)
217 const notice = budgetNotice(run.type, run.key, tokens)
218 $.ui.toast(notice, { timeoutMs: 15000 })
219 $.ui.log(notice, { to: 'transcript' })
220}
221
222// ── The Index dispatcher ─────────────────────────────────────────────────────
223
224// The Agent call's answer for a Watson Index-mode dispatch: the dispatcher's
225// first line, or a refusal. It never falls through to a spawn, which would
226// start a run without its pipeline flag.
227async function runDispatcher($: EngineInterface, itemId: string, prompt: string) {
228 const home = await $.env.get('HOME').catch(() => undefined)
229 if (!home) return { deny: dispatchDeny('HOME is not set, so the dispatcher cannot be found') }
230 const run = await $.process.run(dispatcherArgv(home, itemId), { timeoutMs: 120_000 }).catch(() => undefined)
231 if (run === undefined) return { deny: dispatchDeny('the dispatcher could not run') }
232 const outcome = dispatchOutcome(run)
233 if ('deny' in outcome) return outcome
234 return { result: dispatchResult(outcome.line, prompt), context: [DISPATCH_CONTEXT] }
235}
236
237// ── The guards ───────────────────────────────────────────────────────────────
238
239const GUARDED: ReadonlySet<string> = new Set(['Bash', 'Edit', 'Write', 'NotebookEdit'])
240
241const GUARD_FAILED =
242 '🛑 Blocked: a call the review guard could not judge.\n\nworkbench-dev-team. The review guard failed while reading this call, so it is refused rather than let an unread write through. Report this to the human as a guard defect. Do not try another spelling.'
243
244// The input fields the guards read. The engine types them per tool; these are
245// read as unknown, so a field of the wrong type is judged as absent.
246type GuardInput = { tool: string; agentId?: string; command?: unknown; file_path?: unknown; notebook_path?: unknown }
247
248// Whether a call comes from a Holmes reviewer, or from anything a reviewer
249// spawned: true, false, or undefined when it cannot be told. A top-level
250// `--agent` run names its type in CLAUDE_CODE_AGENT, and every loop in it is
251// held. A sub-agent's type, and its parents', come from $.agent.list().
252async function isReviewer($: EngineInterface, agentId: string | undefined, lane: CallerLane | undefined): Promise<boolean | undefined> {
253 if (isReviewerType(await $.env.get('CLAUDE_CODE_AGENT').catch(() => undefined))) return true
254 if (lane === 'main' || lane === 'top-level-agent') return false
255 if (lane === undefined || agentId === undefined) return undefined
256 const agents = await $.agent.list().catch(() => undefined)
257 if (agents === undefined) return undefined
258 const seen = new Set<string>()
259 for (let id: string | undefined = agentId; id !== undefined && !seen.has(id); ) {
260 seen.add(id)
261 const agent = agents.find(a => a.id === id)
262 if (agent === undefined) return undefined
263 if (isReviewerType(agent.type)) return true
264 id = agent.parentId
265 }
266 return false
267}
268
269// The scratch roots: core's, and $TMPDIR, each a physical directory.
270async function scratchRootsOf($: EngineInterface): Promise<string[]> {
271 const roots = [...(await $.workbench.scratchRoots().catch(() => []))]
272 const tmp = await $.env.get('TMPDIR').catch(() => undefined)
273 const real = tmp ? (await $.fs.stat(tmp, { resolve: true }).catch(() => undefined))?.realPath : undefined
274 if (real !== undefined && (await $.fs.stat(real).catch(() => undefined))?.kind === 'dir') roots.push(real)
275 return roots
276}
277
278// The review guard's refusal for a reviewer's call, or undefined.
279async function reviewDeny($: EngineInterface, e: GuardInput, parse: ShellParse | undefined): Promise<string | undefined> {
280 const cwd = await $.session.cwd().catch(() => undefined)
281 const context = { cwd, home: await $.env.get('HOME').catch(() => undefined) }
282 let verdict
283 if (e.tool === 'Bash') {
284 if (parse === undefined) return undefined
285 verdict = reviewBash(parse, context)
286 } else {
287 const raw = e.tool === 'NotebookEdit' ? e.notebook_path : e.file_path
288 verdict = reviewEdit(e.tool, typeof raw === 'string' ? raw : '', context)
289 }
290 const roots = await scratchRootsOf($)
291 if ('finding' in verdict) return refusalOf(verdict.finding, roots)
292 const disk: Disk = {
293 stat: path => $.fs.stat(path, { resolve: true }).then(stat => ({ realPath: stat.realPath }), () => undefined),
294 names: dir => $.fs.list(dir).then(entries => entries.map(entry => entry.name), () => undefined),
295 }
296 const finding = await judgeWrites(verdict.writes, roots, disk)
297 return finding === undefined ? undefined : refusalOf(finding, roots)
298}
299
300async function guard($: EngineInterface, e: GuardInput): Promise<string | undefined> {
301 const lane = await $.workbench.callerLane(e.agentId === undefined ? {} : { agentId: e.agentId }).catch(() => undefined)
302 const reviewer = await isReviewer($, e.agentId, lane)
303 if (reviewer === false) return undefined
304 const parse = e.tool === 'Bash' ? await $.workbench.parseShell(typeof e.command === 'string' ? e.command : '') : undefined
305 const deny = await reviewDeny($, e, parse)
306 if (deny === undefined || reviewer) return deny
307 return `${deny}\n\nThe guard could not tell which agent made this call, so it held the call to the reviewer's rule. Report this to the human as a guard defect.`
308}
309
310// ── The panes ────────────────────────────────────────────────────────────────
311
312const RUNS_COMMAND = 'dev-team-runs'
313const BOARD_COMMAND = 'dev-team-board'
314const PANE_TITLE = { [RUNS_PANE]: 'Dev-team runs', [BOARD_PANE]: 'The Index board' } as const
315
316const runsAtom = atom({ plugin: 'workbench-dev-team', key: 'runs' } as const, { rows: [] } as RunsView)
317const boardAtom = atom({ plugin: 'workbench-dev-team', key: 'board' } as const, EMPTY_BOARD)
318
319// What the panes keep between refreshes in one load of the module: each read
320// log's end by name, with the size and mtime it was read at, whether a refresh
321// of each pane is under way, and the refresh timer.
322type PaneMemory = { ends: Map<string, { stamp: string; end: LogEnd }>; isRunsBusy: boolean; isBoardBusy: boolean; timer?: Timer }
323
324async function logDirOf($: EngineInterface): Promise<string | undefined> {
325 const home = await $.env.get('HOME').catch(() => undefined)
326 return home ? `${home}/${LOG_DIR}` : undefined
327}
328
329const stampOf = (run: { mtimeMs: number; size: number }): string => `${run.mtimeMs}:${run.size}`
330const NO_END: LogEnd = { tail: [], refusals: 0 }
331
332// The runs view from the newest logs. Only a log whose size or mtime changed
333// since its last read is read again.
334async function readRuns($: EngineInterface, memory: PaneMemory): Promise<RunsView> {
335 const dir = await logDirOf($)
336 if (dir === undefined) return { rows: [], error: 'HOME is not set, so the dispatch logs cannot be found.' }
337 const entries = await $.fs.list(dir).catch(() => undefined)
338 if (entries === undefined) return { rows: [], error: `There is no dispatch log folder at ${dir}.` }
339 const runs = newestRuns(entries)
340 if (runs.length === 0) return { rows: [] }
341 const changed = runs.filter(run => memory.ends.get(run.name)?.stamp !== stampOf(run))
342 if (changed.length > 0) {
343 const scan = await $.process.run(scanArgv($.plugin.root, changed.map(run => `${dir}/${run.name}`)), { timeoutMs: 20_000 }).catch(() => undefined)
344 // The scan skips a log it cannot open, so a non-zero exit with output is
345 // still the ends of the logs it read. No output and a failure is no read.
346 if (scan === undefined || (scan.exitCode !== 0 && scan.stdout === '')) return { rows: [], error: 'The dispatch logs could not be read.' }
347 const scanned = endsOf(scan.stdout)
348 for (const run of changed) {
349 const end = scanned.get(`${dir}/${run.name}`)
350 if (end === undefined) memory.ends.delete(run.name)
351 else memory.ends.set(run.name, { stamp: stampOf(run), end })
352 }
353 }
354 // A changed log the scan could not open was deleted since the listing: its
355 // run leaves the pane, and the others stay.
356 const read = runs.filter(run => memory.ends.get(run.name)?.stamp === stampOf(run))
357 for (const name of memory.ends.keys()) if (!read.some(run => run.name === name)) memory.ends.delete(name)
358 const ps = await $.process.run(['ps', '-axo', 'command='], { timeoutMs: 10_000 }).catch(() => undefined)
359 if (ps === undefined || ps.exitCode !== 0) return { rows: [], error: 'The process list could not be read, so which runs are live is unknown.' }
360 const ends = new Map(read.map(run => [`${dir}/${run.name}`, memory.ends.get(run.name)?.end ?? NO_END]))
361 return { rows: rowsOf(dir, read, ends, livePairsOf(ps.stdout), markersOf(entries)) }
362}
363
364async function refreshRuns($: EngineInterface, memory: PaneMemory): Promise<void> {
365 if (memory.isRunsBusy) return
366 memory.isRunsBusy = true
367 try {
368 const view = await readRuns($, memory)
369 await update($, runsAtom, () => view)
370 } finally {
371 memory.isRunsBusy = false
372 }
373}
374
375// The escalated items, read from the log folder on every refresh, and the
376// board from The Index when the cadence allows. The attempt is recorded before
377// the client runs, so no later refresh, and no reload, starts a second one
378// inside the cadence.
379async function refreshBoard($: EngineInterface, memory: PaneMemory, cadenceMs: number): Promise<void> {
380 const dir = await logDirOf($)
381 const entries = dir === undefined ? [] : await $.fs.list(dir).catch(() => [])
382 const escalated = escalatedOf(markersOf(entries))
383 await update($, boardAtom, view => ({ ...view, escalated }))
384 if (memory.isBoardBusy) return
385 const now = await $.clock.now()
386 if (!isDue(await read($, boardAtom), now, cadenceMs)) return
387 memory.isBoardBusy = true
388 try {
389 await update($, boardAtom, view => ({ ...view, attemptedAt: now }))
390 const run = await $.process.run(boardArgv($.plugin.root), { timeoutMs: BOARD_TIMEOUT_MS }).catch(() => undefined)
391 const outcome = boardOutcome(run)
392 await update($, boardAtom, view => afterFetch(view, now, outcome))
393 } finally {
394 memory.isBoardBusy = false
395 }
396}
397
398// One refresh of every open pane. With none open, the timer stops.
399async function refreshPanes($: EngineInterface, memory: PaneMemory, cadenceMs: number): Promise<void> {
400 const open = new Set((await $.ui.panes()).map(pane => pane.id))
401 if (!open.has(RUNS_PANE) && !open.has(BOARD_PANE)) {
402 memory.timer?.cancel()
403 memory.timer = undefined
404 return
405 }
406 await Promise.all([open.has(RUNS_PANE) ? refreshRuns($, memory) : undefined, open.has(BOARD_PANE) ? refreshBoard($, memory, cadenceMs) : undefined])
407}
408
409function startRefresh($: EngineInterface, memory: PaneMemory, cadenceMs: number): void {
410 memory.timer ??= $.clock.every(RUNS_REFRESH_MS, () => void refreshPanes($, memory, cadenceMs).catch(() => undefined))
411}
412
413// Whether this session gets the dev-team rules (mods/session-rules.ts). An
414// environment that cannot be read sends them: losing the rules is the worse
415// failure, as workbench-core rules for its own.
416async function isRulesSession($: EngineInterface): Promise<boolean> {
417 return $.env.get('WORKBENCH_SKIP_WARMUP').then(isRulesLane, () => true)
418}
419
420export const register: Register = (on, options) => {
421 // The rows, read once: the options are fixed for this activation.
422 const config = configTextOf(options)
423
424 // The panes. Neither one writes: see refreshRuns and refreshBoard.
425 const cadenceMs = cadenceMsOf(options.dispatchCadenceMinutes)
426 const memory: PaneMemory = { ends: new Map(), isRunsBusy: false, isBoardBusy: false }
427
428 const activity = new Map<string, Activity>()
429 const watches = new Map<string, Watch>()
430 const begin = (agentId: string | undefined): (() => void) => {
431 if (agentId === undefined) return () => undefined
432 const seen = activity.get(agentId) ?? { ticks: 0, inFlight: 0 }
433 activity.set(agentId, seen)
434 seen.ticks++
435 seen.inFlight++
436 return () => {
437 seen.inFlight--
438 }
439 }
440
441 on('session.start', async ($, e, next) => {
442 await $.command.register({ name: RUNS_COMMAND, description: 'Show live and recent dev-team runs from the dispatch logs', immediate: true }).catch(() => undefined)
443 await $.command.register({ name: BOARD_COMMAND, description: "Show The Index board's lanes, fetched once per dispatch cadence at most", immediate: true }).catch(() => undefined)
444 const open = await $.ui.panes().catch(() => [])
445 if (open.some(pane => pane.id === RUNS_PANE || pane.id === BOARD_PANE)) startRefresh($, memory, cadenceMs)
446 return next(e)
447 })
448
449 on('command.run', async ($, e, next) => {
450 const pane = e.command === RUNS_COMMAND ? RUNS_PANE : e.command === BOARD_COMMAND ? BOARD_PANE : undefined
451 if (pane === undefined) return next(e)
452 await $.ui.open({ id: pane, title: PANE_TITLE[pane] })
453 startRefresh($, memory, cadenceMs)
454 void refreshPanes($, memory, cadenceMs).catch(() => undefined)
455 return { text: `${PANE_TITLE[pane]} pane opened.` }
456 }).catch(($, e, next) => (e.command === RUNS_COMMAND || e.command === BOARD_COMMAND ? { text: 'The dev-team pane could not open. Try the command again.' } : next(e)))
457
458 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
459 if (e.requestId === RUNS_PANE) return runsTree($.ui.resolve(e), await read($, runsAtom), e.props.scroll.bodyRows)
460 if (e.requestId === BOARD_PANE) return boardTree($.ui.resolve(e), await read($, boardAtom), cadenceMs)
461 return next(e)
462 })
463
464 on('agent.spawn', async ($, e, next) => {
465 // Only the model's own Agent calls are judged, the ones core's gate sees.
466 // A plugin's $.agent.spawn is the plugin's implementation, not a handoff.
467 const isModel = next.origin.plugin === 'engine'
468 const isGatedCall = isModel && (await gated($, e.parentAgentId))
469
470 // The helper rule. A spawner the mod cannot name is let through: the
471 // review guard still holds every write by anything Holmes spawned.
472 let input = e
473 if (isModel && isHolmesMode(await spawnerTypeOf($, e.parentAgentId))) {
474 const lens = lensSpawnOf(e)
475 if ('deny' in lens) return lens
476 input = { ...e, subagentType: lens.subagentType }
477 }
478
479 // The workspace check. git answering with no branch (not a repository, or
480 // a detached HEAD) passes; git that cannot run at all refuses, since the
481 // answer is then unknown, and recording a branch in Workdir: passes.
482 if (isGatedCall && familyOf(input.subagentType) === 'watson' && modeTypeOf('watson', input.prompt).endsWith(':watson-direct')) {
483 const workdir = workdirOf(input.prompt)
484 if (workdir !== undefined && !workdir.isRecorded && workdir.path.startsWith('/')) {
485 const head = await $.process
486 .run(['git', '-C', workdir.path, 'symbolic-ref', '--quiet', '--short', 'HEAD'], { timeoutMs: 10_000 })
487 .catch(() => undefined)
488 if (head === undefined) return { deny: branchUnreadDeny(workdir.path) }
489 const branch = head.stdout.trim()
490 if (head.exitCode === 0 && DEFAULT_BRANCHES.includes(branch)) return { deny: branchDeny(workdir.path, branch) }
491 }
492 }
493
494 // Nothing in this block calls next, so a failure here passes the dispatch
495 // on unchanged, and next is called once either way.
496 let routed: typeof e | undefined
497 let knobs: ReturnType<typeof knobsOf> = {}
498 try {
499 const family = familyOf(input.subagentType)
500 if (family !== undefined) {
501 knobs = knobsOf(config, family)
502 const subagentType = modeTypeOf(family, input.prompt)
503 const configFamily = CONFIG_MODES[subagentType]
504 const prompt = configFamily === undefined ? input.prompt : withConfigLine(input.prompt, configLineOf(config, configFamily))
505 // A model the caller named is the caller's choice, and stands.
506 const model = input.model ?? knobs.model
507 routed = { ...input, subagentType, prompt, ...(model === undefined ? {} : { model }) }
508 }
509 } catch {
510 routed = undefined
511 }
512 const spawned = routed ?? input
513 const result = await next(spawned)
514 if (result.agentId !== undefined) {
515 if (routed !== undefined && knobs.effort !== undefined) {
516 await $.state.set({ plugin: 'workbench-dev-team', key: 'effort', id: result.agentId }, knobs.effort)
517 }
518 if (isDevTeamType(spawned.subagentType)) {
519 await $.state.set({ plugin: 'workbench-dev-team', key: 'agentType', id: result.agentId }, spawned.subagentType)
520 }
521 }
522 return result
523 }).catch(($, e, next) => (next.called ? next(e) : { deny: spawnFailedDeny() }))
524
525 // The dev-team session rules: a shared section in the main loop's system
526 // prompt, and context at a sub-agent's start.
527 on('prompt.compose', async ($, e, next) => {
528 const result = await next(e)
529 return (await isRulesSession($)) ? { sections: withRules(result.sections) } : result
530 })
531
532 on('classic.SubagentStart', async ($, e, next) => {
533 const result = await next(e)
534 if (!isRulesSubagent(e.agent_type) || !(await isRulesSession($))) return result
535 return { ...result, additionalContext: [...(result.additionalContext ?? []), RULES] }
536 })
537
538 // The config line for a top-level run of a mode that reads it. Nothing here
539 // calls next, so a failure leaves the prompt as it came.
540 on('prompt.submit', async ($, e, next) => {
541 let line: string | undefined
542 try {
543 if ((await $.workbench.callerLane({})) === 'top-level-agent') {
544 const family = CONFIG_MODES[(await $.env.get('CLAUDE_CODE_AGENT')) ?? '']
545 if (family !== undefined) line = configLineOf(config, family)
546 }
547 } catch {
548 line = undefined
549 }
550 return next(line === undefined ? e : { ...e, context: [...(e.context ?? []), line] })
551 })
552
553 on('turn.step', async function* ($, e, next) {
554 const done = begin(e.agentId)
555 try {
556 let input = e
557 if (e.agentId !== undefined) {
558 const { value: effort } = await $.state.get({ plugin: 'workbench-dev-team', key: 'effort', id: e.agentId })
559 if (effort !== undefined) input = { ...e, effort }
560 }
561 const result = yield* next(input)
562 await measure($, e.agentId, result.usage).catch(() => undefined)
563 return result
564 } finally {
565 done()
566 }
567 })
568
569 on('classic.SubagentStop', async ($, e, next) => {
570 const result = await next(e)
571 if (result.block !== undefined) return result
572 const block = await stopBlock($, e.agent_id, e.background_tasks ?? [], activity, watches)
573 return block === undefined ? result : { ...result, block }
574 })
575
576 on('turn.complete', async ($, e, next) => {
577 const result = await next(e)
578 await endRun($, e.agentId).catch(() => undefined)
579 return result
580 })
581
582 // The sweep runs before the engine's own end step, and its failure leaves
583 // the folders where they are rather than holding the exit up.
584 on('session.end', async ($, e, next) => {
585 await endSession($, next.budget).catch(() => undefined)
586 return next(e)
587 })
588
589 on('tool.call', async ($, e, next) => {
590 const done = begin(e.agentId)
591 try {
592 if (e.tool === 'Bash' || e.tool === 'Edit' || e.tool === 'Write' || e.tool === 'NotebookEdit') {
593 const call = e.tool === 'Bash' && typeof e.command === 'string' ? { ...e, command: await withScratch($, e.agentId, e.command) } : e
594 const deny = await guard($, call)
595 if (deny !== undefined) return { deny }
596 const result = await next(call)
597 if (e.tool === 'Bash') await recordStarted($, e.agentId, result).catch(() => undefined)
598 return result
599 }
600 if (e.tool !== 'Agent') return next(e)
601 const isModel = next.origin.plugin === 'engine'
602 let call = e
603 if (isModel) {
604 // A set agentId is a sub-agent's call, whatever callerLane says, so a
605 // sub-agent never reaches the dispatcher. Only a call with no agentId
606 // asks the lane, and a lookup that fails there reads as the main session.
607 const isMain = e.agentId === undefined && (await $.workbench.callerLane({}).catch(() => 'main' as const)) === 'main'
608 if (isMain) {
609 const itemId = indexDispatchOf(e.subagent_type, e.prompt)
610 if (itemId !== undefined) return runDispatcher($, itemId, e.prompt)
611 if (isForcedBackground(e.subagent_type, e.run_in_background)) call = { ...e, run_in_background: true }
612 }
613 }
614 return await next(call)
615 } finally {
616 done()
617 }
618 }).catch(($, e, next) => (next.called || !GUARDED.has(e.tool) ? next(e) : { deny: GUARD_FAILED }))
619}
620hooks/mods/board.ts 93 lines1// The board pane's logic, as pure functions. hooks/register.ts holds the hooks;
2// hooks/mods/panes.tsx draws the lanes.
3
4// The view types live in the type contract, types/index.d.ts.
5import type { Board, BoardItem, BoardLane, BoardView } from '../../types'
6
7export const LANES = ['unrefined', 'review', 'development'] as const
8
9export const EMPTY_BOARD: BoardView = { attemptedAt: 0, escalated: [] }
10
11// The dispatch cadence's default, as in .claude-plugin/plugin.json.
12export const DEFAULT_CADENCE_MINUTES = 20
13
14export const BOARD_TIMEOUT_MS = 400_000
15
16// The cadence in milliseconds, from the /config row. A value that is not a
17// number of at least one minute reads as the default, so a bad row never
18// makes the pane call The Index more often.
19export function cadenceMsOf(minutes: unknown): number {
20 const value = typeof minutes === 'number' && Number.isFinite(minutes) && minutes >= 1 ? minutes : DEFAULT_CADENCE_MINUTES
21 return value * 60_000
22}
23
24// Whether the pane may fetch the board now: never fetched, or the last attempt
25// started a whole cadence ago.
26export const isDue = (view: BoardView, now: number, cadenceMs: number): boolean => view.attemptedAt === 0 || now - view.attemptedAt >= cadenceMs
27
28export const boardArgv = (root: string): string[] => ['bash', `${root}/bin/dispatch-tick.sh`, '--board']
29
30const isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
31const text = (value: unknown): string | null => (typeof value === 'string' ? value : null)
32
33function itemOf(value: unknown): BoardItem | undefined {
34 if (!isObject(value) || typeof value.id !== 'number') return undefined
35 return {
36 id: value.id,
37 number: typeof value.number === 'number' ? value.number : null,
38 isPr: value.isPr === true,
39 repo: text(value.repo),
40 title: text(value.title),
41 claimedAt: text(value.claimedAt),
42 }
43}
44
45function laneOf(value: unknown): BoardLane | undefined {
46 if (!isObject(value)) return undefined
47 if (typeof value.error === 'string') return { error: value.error.slice(0, 300) }
48 if (typeof value.limit !== 'number' || !Array.isArray(value.items)) return undefined
49 const items = value.items.map(itemOf)
50 return items.every(item => item !== undefined) ? { limit: value.limit, items: items as BoardItem[] } : undefined
51}
52
53// The board the client printed, or undefined when its output is anything else.
54// Only the named fields are kept, each of its own type.
55export function boardOf(stdout: string): Board | undefined {
56 let parsed: unknown
57 try {
58 parsed = JSON.parse(stdout)
59 } catch {
60 return undefined
61 }
62 if (!isObject(parsed) || !isObject(parsed.lanes)) return undefined
63 const lanes = parsed.lanes
64 const [unrefined, review, development] = LANES.map(lane => laneOf(lanes[lane]))
65 return unrefined && review && development ? { unrefined, review, development } : undefined
66}
67
68// What one run of the client means: the board, or why there is none. The
69// client prints its reason as the last line on stderr, and never a token.
70export function boardOutcome(run: { exitCode: number; stdout: string; stderr: string } | undefined): { board: Board } | { error: string } {
71 if (run === undefined) return { error: 'the board client could not run' }
72 const board = run.exitCode === 0 ? boardOf(run.stdout) : undefined
73 if (board !== undefined) return { board }
74 const why = run.stderr.split('\n').findLast(line => line.trim() !== '')?.trim()
75 if (run.exitCode === 0) return { error: 'the board client printed something that is not a board' }
76 return { error: (why ?? `the board client exited ${run.exitCode}`).slice(0, 300) }
77}
78
79// The view after a fetch that started at `startedAt`. A failed fetch keeps the
80// last board, so the pane still shows it, with its age.
81export function afterFetch(view: BoardView, startedAt: number, outcome: { board: Board } | { error: string }): BoardView {
82 if ('board' in outcome) return { attemptedAt: startedAt, board: outcome.board, boardAt: startedAt, escalated: view.escalated }
83 const { board, boardAt } = view
84 return { attemptedAt: startedAt, ...(board ? { board, boardAt } : {}), error: outcome.error, escalated: view.escalated }
85}
86
87// "watson item 42" for each escalated pair "watson-42".
88export const escalatedOf = (markers: readonly string[]): string[] =>
89 markers.map(pair => {
90 const dash = pair.lastIndexOf('-')
91 return `${pair.slice(0, dash)} item ${pair.slice(dash + 1)}`
92 })
93hooks/mods/budget.ts 25 lines1// Each dev-team agent's working-context budget, as pure functions.
2// hooks/register.ts measures every model request of a dev-team agent's loop in
3// turn.step, and notifies the human once when a request passes the budget. It
4// stops nothing: the agents' rule is to finish the work and say what made it
5// expensive, never to buy the budget with the work.
6
7import type { TurnUsage } from 'claude-code'
8
9// The budget every dev-team agent's prose states: about 250k tokens of working
10// context.
11export const BUDGET_TOKENS = 250_000
12
13// A request's working context: every input token it was answered over, cached
14// or not. Undefined when the request carried no usage.
15export const contextOf = (usage: TurnUsage | null | undefined): number | undefined =>
16 usage == null ? undefined : usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
17
18export const isOverBudget = (tokens: number | undefined): boolean => tokens !== undefined && tokens > BUDGET_TOKENS
19
20// The notice, one line: which agent, how far past, and that nothing stopped.
21export function budgetNotice(type: string, id: string, tokens: number): string {
22 const k = (n: number) => `${Math.round(n / 1000)}k`
23 return `📏 workbench-dev-team: ${type.split(':').pop()} (${id}) passed its ${k(BUDGET_TOKENS)}-token working-context budget, at ${k(tokens)} in its latest request. Nothing was stopped.`
24}
25hooks/mods/dispatch.ts 91 lines1// What a main-session Agent call to a dev-team agent turns into, before it
2// reaches agent.spawn, as pure functions. hooks/register.ts holds the hook.
3//
4// 1. A Watson Index-mode run goes through the dispatcher. Its prompt is the
5// whole token `Item ID: <n>`, and only bin/dispatch-agent.sh can give the
6// run its pipeline flag, so the hook runs the installed dispatcher in place
7// of the Agent call and answers the call with the dispatcher's first line:
8// dispatched, SKIP, ESCALATE or REPRIEVE. agent.spawn cannot answer a call
9// with text (its result is a started agent or a refusal), so this lives on
10// the Agent tool call itself, which a hook may answer with its own record.
11// 2. A dev-team dispatch runs in the background unless the call asked for the
12// foreground: `run_in_background: false` is the caller's explicit ask, and
13// anything else is set to true.
14
15import type { ToolResultOf } from 'claude-code'
16
17import { familyOf, itemIdOf } from './spawn'
18
19// Where /workbench-dev-team:setup installs the dispatcher, under $HOME.
20export const DISPATCHER = '.claude-workbench/bin/dispatch-agent.sh'
21
22// The item id a Watson Index-mode dispatch names, or undefined when the call
23// is anything else: another agent, a brief, or a bare id (the dispatch gate
24// refuses a bare id from the main session, so it never reaches the dispatcher).
25export function indexDispatchOf(subagentType: unknown, prompt: unknown): string | undefined {
26 if (typeof subagentType !== 'string' || typeof prompt !== 'string') return undefined
27 if (familyOf(subagentType) !== 'watson') return undefined
28 return itemIdOf(prompt)
29}
30
31// The command the hook runs: bash and the installed script, no shell between.
32export const dispatcherArgv = (home: string, itemId: string): string[] => ['bash', `${home}/${DISPATCHER}`, 'watson', itemId]
33
34const firstLine = (text: string): string | undefined => text.split('\n').find(line => line.trim() !== '')?.trim()
35
36// What the dispatcher's run means for the Agent call: its first line, or a
37// refusal when it exited non-zero or printed nothing. The dispatcher exits 0
38// for every verdict, SKIP and ESCALATE included, so a non-zero exit is a bad
39// argument or a run folder it could not make.
40export function dispatchOutcome(run: { exitCode: number; stdout: string; stderr: string }): { line: string } | { deny: string } {
41 const line = firstLine(run.stdout)
42 if (run.exitCode === 0 && line !== undefined) return { line }
43 const why = firstLine(run.stderr) ?? line ?? `exit ${run.exitCode}, no output`
44 return { deny: dispatchDeny(`the dispatcher refused the run: ${why}`) }
45}
46
47export function dispatchDeny(why: string): string {
48 return [
49 `🛑 Blocked: a Watson Index-mode dispatch, because ${why}.`,
50 '',
51 'Dispatch gate (workbench-dev-team). A Watson `Item ID: <n>` dispatch runs through ~/.claude-workbench/bin/dispatch-agent.sh, which the dev-team mod runs in place of the Agent call. ' +
52 'Nothing was spawned and no board item moved. Relay this to the human, and do not retry through the Agent tool.',
53 ].join('\n')
54}
55
56// What the model reads beside the line: what each first line means.
57export const DISPATCH_CONTEXT =
58 'The dev-team mod ran ~/.claude-workbench/bin/dispatch-agent.sh in place of this Agent call, because only the dispatcher gives a Watson Index-mode run its pipeline flag. ' +
59 'No sub-agent started here, so no completion notification will come. The result is the dispatcher\'s first line. ' +
60 '"dispatched watson pid=... log=..." means the run started: track it from that log, and look there for "Permission denied:" lines, one per refused call. ' +
61 '"REPRIEVE" means a human re-activated an escalated item, and the run started with a raised budget. ' +
62 '"SKIP" (a run on that item is still alive) and "ESCALATE" (the breaker judges the item wedged) mean nothing was spawned: relay the line to the human rather than retrying.'
63
64// The Agent tool's own record for a call the hook answered: completed, with the
65// line as its text. Core checks it against the tool's output schema.
66export function dispatchResult(line: string, prompt: string): ToolResultOf<'Agent'> {
67 return {
68 status: 'completed',
69 agentId: 'dispatch-agent.sh',
70 content: [{ type: 'text', text: line }],
71 totalToolUseCount: 0,
72 totalDurationMs: 0,
73 totalTokens: 0,
74 prompt,
75 usage: {
76 input_tokens: 0,
77 output_tokens: 0,
78 cache_creation_input_tokens: null,
79 cache_read_input_tokens: null,
80 server_tool_use: null,
81 service_tier: null,
82 cache_creation: null,
83 },
84 }
85}
86
87// Whether a dev-team dispatch must be put in the background: every one whose
88// call did not set run_in_background to false.
89export const isForcedBackground = (subagentType: unknown, runInBackground: unknown): boolean =>
90 typeof subagentType === 'string' && familyOf(subagentType) !== undefined && runInBackground !== false && runInBackground !== true
91hooks/mods/helper-wait.ts 82 lines1export type Child = { id: string; type: string; status: string; parentId?: string; name?: string; description: string }
2
3export type InFlight = { id: string; command?: string; description: string }
4
5export type Started = { id: string; output?: string }
6
7export type Activity = { ticks: number; inFlight: number }
8
9export type Watch = { mark: string; unchanged: number; isReleased: boolean }
10
11export type Progress = { helper: (id: string) => Activity | undefined; outputSize: (path: string) => number | undefined }
12
13export const STUCK_AFTER = 2
14
15const OUTSTANDING: ReadonlySet<string> = new Set(['pending', 'running', 'waiting'])
16
17const clip = (text: string): string => (text.length > 120 ? `${text.slice(0, 117)}...` : text)
18
19export const withStarted = (started: readonly Started[], entry: Started): Started[] => [...started.filter(kept => kept.id !== entry.id), entry]
20
21export function outputOf(id: string, text: unknown): string | undefined {
22 if (typeof text !== 'string') return undefined
23 const match = /Output is being written to: (\/\S+?)\.?(?:\s|$)/.exec(text)
24 const path = match?.[1]
25 return path !== undefined && path.endsWith(`/${id}.output`) ? path : undefined
26}
27
28export const watchKey = (agentId: string, itemKey: string): string => `${agentId}\u0000${itemKey}`
29
30type Item = { key: string; line: string; mark: string; isBusy: boolean }
31
32export function stopBlockOf(
33 agentId: string,
34 agents: readonly Child[],
35 started: readonly Started[],
36 inFlight: readonly InFlight[],
37 progress: Progress,
38 watches: Map<string, Watch>,
39): string | undefined {
40 const helpers: Item[] = agents
41 .filter(agent => agent.parentId === agentId && OUTSTANDING.has(agent.status))
42 .map(agent => {
43 const activity = progress.helper(agent.id) ?? { ticks: 0, inFlight: 0 }
44 const line = `- helper ${agent.id} (${agent.type.split(':').pop()}, ${agent.status}): ${clip(agent.name ?? agent.description)}`
45 return { key: `helper:${agent.id}`, line, mark: String(activity.ticks), isBusy: activity.inFlight > 0 }
46 })
47 const commands: Item[] = inFlight.flatMap(task => {
48 const own = started.find(entry => entry.id === task.id)
49 if (own === undefined) return []
50 const size = own.output === undefined ? undefined : progress.outputSize(own.output)
51 return [{ key: `command:${task.id}`, line: `- background command ${task.id}: ${clip(task.command ?? task.description)}`, mark: String(size), isBusy: false }]
52 })
53 const items = [...helpers, ...commands].filter(item => !watches.get(watchKey(agentId, item.key))?.isReleased)
54 if (items.length === 0) return undefined
55 const stuck = items.filter(item => {
56 const key = watchKey(agentId, item.key)
57 const seen = watches.get(key)
58 const unchanged = seen !== undefined && !item.isBusy && item.mark === seen.mark ? seen.unchanged + 1 : 0
59 watches.set(key, { mark: item.mark, unchanged, isReleased: false })
60 return unchanged >= STUCK_AFTER
61 })
62 if (stuck.length === items.length) {
63 for (const item of stuck) watches.set(watchKey(agentId, item.key), { mark: item.mark, unchanged: STUCK_AFTER, isReleased: true })
64 return [
65 '⚠️ These made no progress across your last two attempts to end your turn, so they no longer hold it:',
66 ...stuck.map(item => item.line),
67 '',
68 'workbench-dev-team. A helper made no model request or tool call, and a background command wrote no new output. Name each one in your report as work that looked stuck, with what it was meant to do, and then end your turn. Your next turn end is allowed.',
69 ].join('\n')
70 }
71 return [
72 '🛑 Blocked: you cannot end your turn while work you started has not reported.',
73 '',
74 'workbench-dev-team. Still outstanding:',
75 ...items.map(item => item.line),
76 '',
77 'A sub-agent that ends its turn is never woken by a notice, so these reports would never reach you.',
78 'Keep making short tool calls, such as `sleep 20`, until each one reports. Each tool call delivers the notices that wait for you.',
79 'A helper or background command that makes no progress across two of your attempts to end your turn stops holding it, and you are told which one.',
80 ].join('\n')
81}
82hooks/mods/review-guard.ts 893 lines1// The review guard, as pure functions over workbench-core's reading of a Bash
2// line ($.workbench.parseShell). hooks/register.ts calls them for Bash, Edit,
3// Write and NotebookEdit, resolves the paths they return on the disk, and
4// refuses the call of a Holmes reviewer that would write outside the scratch
5// roots.
6//
7// Holmes reviews code he must not change. In Local mode the tree he reads is the
8// human's live working directory, and the uncommitted change in it is the ONLY
9// copy of the work, so a reviewer that writes to it destroys the thing it was
10// sent to read. Prose in an agent prompt is advisory: on the mode's first real
11// exercise a lens sub-agent ran `chmod` against that directory with the rule in
12// its own prompt. This guard is not advisory.
13//
14// WHO IS HELD. A call from Holmes (`holmes`, or his mode agents `holmes-local`
15// and `holmes-index`) or his helper (`holmes-lens`), with or without the
16// `workbench-dev-team:` prefix, and from any sub-agent one of them spawned, at
17// any depth. A top-level `--agent` run of one of them (the scheduled pipeline)
18// is held on its main loop and in every sub-agent. The main loop of any other
19// session, and every other agent, keeps its tools.
20//
21// THE SCRATCH ROOTS are the places a reviewer may write: workbench-core's
22// $.workbench.scratchRoots (the session scratchpad, ~/Developer/scratchpad and
23// ~/.claude/plans) and $TMPDIR, where a bare `mktemp -d` lands. A write lands
24// in a root only when it is strictly beneath one, resolved both through every
25// symlink and with its final name left unresolved, so no root can be removed
26// and no link can lead out of one. With no root found, every write is refused.
27//
28// WHAT COUNTS AS A WRITE. Reads and test runs pass, and so does a write inside
29// a scratch root. The line is drawn at commands whose purpose is to change a
30// file's content, location, existence, or metadata:
31// 1. git, inverted: GIT_READ_ONLY lists the verbs that only read, and every
32// other verb is refused. branch, tag, remote, config, stash and worktree
33// pass in their listing forms only, symbolic-ref with one argument, and
34// reflog in every form but expire, delete and drop. A git -c,
35// --config-env or --exec-path=<dir> is refused, since configuration can
36// name a program (core.pager, diff.external, an alias). The environment is
37// configuration too (GIT_EXTERNAL_DIFF, GIT_SSH_COMMAND, GIT_CONFIG_COUNT
38// each name a program), so a reviewer's git is refused when a GIT_*
39// variable is set in front of it, and when ANY other statement on the
40// line can change the environment git inherits: an assignment of any
41// name, the export family, anything that sets a variable by name
42// (printf -v, read, mapfile, getopts, a for loop, ${x:=y}), set, source,
43// the dot command, eval, let and arithmetic. The rule is the category,
44// not a list of GIT_ spellings, because each review round found a new
45// spelling. It over-refuses a line that sets an unrelated variable before
46// git, a cost Mike's fail-closed rule accepts for reviewers. A plain
47// `FOO=1 git status`, a non-GIT_ name on git itself, still runs.
48// An option of a reading verb that names or runs a program is refused
49// (PROGRAM_OPTIONS: grep -O, ls-remote --upload-pack, archive --exec and
50// --remote, --ext-diff, and --textconv, git grep's included). `git
51// archive` and git's --output write the file they name, judged by path.
52// 2. The file writers in MUTATING, judged by the paths they write:
53// cp's destination (never its sources), mv's every operand, rsync's
54// destination, the directory tar and unzip extract into, sort -o, uniq's
55// second operand, and so on. A writer fed by xargs or parallel is refused,
56// since its paths arrive at run time.
57// 3. In-place editing: sed -i, perl -i and ruby -i, judged by the files they
58// edit, so an edit on a scratch copy passes. A sed script with a w or e
59// command, an awk program that prints to a file, pipes, or calls
60// system(), and find with -delete, -exec, -ok or -fprint are refused.
61// 4. Formatters asked to write: --write, --fix, --in-place on any other
62// command (git, the writers, find and an in-place edit meet the rules
63// above), a formatter's short write flag, and a formatter that writes by
64// default and was not put in check mode. Refused wherever they point.
65// 5. Redirects bash really performs (>, >>, >|, &>, <>, a >& to a file),
66// judged by target. A > inside quotes, an awk or sed program, a heredoc
67// body, arithmetic or [[ ]] is not a redirect, and the reader says so.
68// A quoted heredoc body is data, so a body written to a scratch file
69// passes whatever text it holds (an `-I{}`, an `=> {`).
70//
71// FAIL CLOSED. A line parseShell cannot read whole (any unknown), a wrapper
72// it cannot place (isPlaced false), a command name built at run time, and a
73// program the guard does not know with a writer's name among its words
74// (`parallel chmod …`, a runner off every list) are refused: a false refusal
75// costs a reviewer one step, while a bypass costs a write to the tree under
76// review (vault: decisions/2026-10-05-holmes-guard-fail-closed-on-unknown-
77// wrappers.md). A cd, pushd, popd or chdir, or a wrapper option that changes
78// directory, makes every later relative path unresolvable.
79//
80// WHAT IT DOES NOT COVER. This guard catches honest mistakes, and is not a
81// security boundary (Mike, 2026-10-07: these gaps are accepted rather than
82// chased). It reads the words of a line, so a change it cannot see in them is
83// out of scope: a value-only change such as PATH=, HOME= or XDG_CONFIG_HOME=
84// before git; git -C into a repository whose own config is hostile; an
85// arithmetic assignment such as $((X=1)); a bash alias defined on the same
86// line; code inside an interpreter (`python -c`, `node -e`); a script file;
87// a package script (`npm run format`); and a zsh builtin outside its tables
88// that sets a variable by name (zformat -f or -a, zregexparse, and module
89// builtins such as sysread, zstat -A and zselect -a). Nor does it catch a
90// program off every list that writes on its own (`gh pr checkout`). The
91// reviewer prompts' no-write rule and the human's review of the diff are the
92// backstop there.
93
94import type { EngineInterface } from 'claude-code'
95
96type Workbench = EngineInterface['workbench']
97export type ShellParse = Awaited<ReturnType<Workbench['parseShell']>>
98export type Statement = ShellParse['statements'][number]
99
100// A refused call: the short action the person reads, and the reason the model
101// reads after it.
102export type Finding = { action: string; reason: string }
103
104// A path a call writes: as written, and absolute when it can be known.
105export type Write = { raw: string; path: string | undefined; writer: string }
106
107export type Verdict = { finding: Finding } | { writes: Write[] }
108
109// The agent types the guard holds. `u` folds `ſ` into `s`, as Python's
110// re.IGNORECASE did for the bash guard.
111const REVIEWER = /(^|[:/])holmes(-lens|-local|-index)?$/iu
112
113export const isReviewerType = (type: string | undefined): boolean => type !== undefined && REVIEWER.test(type.trim())
114
115// git verbs that only read. Every other verb is refused.
116const GIT_READ_ONLY: ReadonlySet<string> = new Set([
117 'annotate', 'blame', 'cat-file', 'check-attr', 'check-ignore', 'count-objects', 'describe', 'diff', 'diff-index',
118 'diff-tree', 'for-each-ref', 'grep', 'log', 'ls-files', 'ls-tree', 'merge-base', 'name-rev', 'rev-list',
119 'rev-parse', 'shortlog', 'show', 'show-ref', 'status', 'var', 'verify-commit', 'verify-tag',
120 'whatchanged', 'ls-remote', 'archive',
121])
122// Read-only only in some forms, judged in gitReads: symbolic-ref with one
123// argument, and reflog other than expire, delete and drop.
124
125const BRANCH_READ_FLAGS = new Set([
126 '--show-current', '-a', '--all', '-r', '--remotes', '-v', '-vv', '--verbose', '-l', '--list', '--no-color',
127 '--contains', '--no-contains', '--merged', '--no-merged', '--points-at',
128])
129const TAG_READ_FLAGS = new Set(['-l', '--list', '-n', '--no-color', '--contains', '--no-contains', '--merged', '--no-merged', '--points-at'])
130const LIST_VALUE_PREFIXES = ['--format=', '--sort=', '--contains=', '--no-contains=', '--merged=', '--no-merged=', '--points-at=']
131const LIST_VALUE_FLAGS = new Set(LIST_VALUE_PREFIXES.map(prefix => prefix.slice(0, -1)))
132const CONFIG_READ_FLAGS = new Set(['--get', '--get-all', '--get-regexp', '--get-urlmatch', '--list', '-l', '--get-color', '--get-colorbool'])
133const CONFIG_WRITE_FLAGS = new Set(['--add', '--unset', '--unset-all', '--replace-all', '--rename-section', '--remove-section', '--edit', '-e'])
134
135// Commands whose purpose is to change a file's content, location, existence,
136// or metadata, each judged by the paths writeTargets says it writes.
137const MUTATING: ReadonlySet<string> = new Set([
138 'chmod', 'chown', 'chgrp', 'rm', 'rmdir', 'unlink', 'mv', 'shred', 'truncate', 'touch', 'tee', 'cp', 'ln',
139 'install', 'dd', 'patch', 'mkdir', 'rsync', 'tar', 'unzip', 'sort', 'uniq',
140])
141
142// Options that take the next word as their value, on both GNU and BSD.
143const VALUE_OPTIONS: Readonly<Record<string, ReadonlySet<string>>> = {
144 install: new Set(['-m', '-o', '-g']),
145 truncate: new Set(['-s', '-r']),
146 touch: new Set(['-r', '-t', '-d']),
147 mkdir: new Set(['-m']),
148 rsync: new Set(['-e', '-f', '-T']),
149 uniq: new Set(['-f', '-s', '-w', '--skip-fields', '--skip-chars', '--check-chars']),
150 chmod: new Set(['--reference']),
151}
152
153const UNZIP_READ_FLAGS = new Set('lptvcZh')
154
155// The three in-place editors: the letters that mean in place, and the letters
156// that take the rest of their word (or the next word) as a value.
157const IN_PLACE_EDITORS: Readonly<Record<string, { inPlace: string; value: string }>> = {
158 sed: { inPlace: 'iI', value: 'ef' },
159 perl: { inPlace: 'i', value: 'eEFImMx' },
160 ruby: { inPlace: 'i', value: 'eCEFIrx' },
161}
162// The value letters whose value is the program, so no file operand is a script.
163const CODE_LETTERS: Readonly<Record<string, string>> = { sed: 'ef', perl: 'eE', ruby: 'e' }
164
165const IN_PLACE_FLAGS = new Set(['--write', '--fix', '--in-place'])
166
167const FORMATTER_WRITE_FLAGS: Readonly<Record<string, ReadonlySet<string>>> = {
168 gofmt: new Set(['-w']), goimports: new Set(['-w']), gofumpt: new Set(['-w']), shfmt: new Set(['-w']),
169 prettier: new Set(['-w']), 'clang-format': new Set(['-i']), autopep8: new Set(['-i']), yapf: new Set(['-i']),
170 'swift-format': new Set(['-i']),
171 rubocop: new Set(['-a', '-A', '-x', '--autocorrect', '--autocorrect-all', '--auto-correct', '--auto-correct-all', '--safe-auto-correct', '--fix-layout']),
172}
173const FORMATTER_CLUSTER_FLAGS: Readonly<Record<string, { write: string; value: string }>> = {
174 yapf: { write: 'i', value: 'le' },
175 autopep8: { write: 'i', value: 'jp' },
176 prettier: { write: 'w', value: '' },
177 rubocop: { write: 'aAx', value: 'corfCs' },
178}
179const STDIN_NAME_OPTIONS = new Set(['--stdin-filename', '--filename'])
180const FORMATTERS_WRITING_BY_DEFAULT: Readonly<Record<string, ReadonlySet<string>>> = {
181 black: new Set(['--check', '--diff', '-c', '--code']),
182 rustfmt: new Set(['--check', '--emit=stdout', '--print-config']),
183 'cargo fmt': new Set(['--check']),
184 'go fmt': new Set(['-n']),
185 'ruff format': new Set(['--check', '--diff']),
186 isort: new Set(['--check-only', '--check', '-c', '--diff', '--show-config', '--show-files', '--stdout', '-d']),
187 'terraform fmt': new Set(['-check', '-write=false']),
188 'mix format': new Set(['--check-formatted', '--dry-run']),
189 'dotnet format': new Set(['--verify-no-changes']),
190 'deno fmt': new Set(['--check']),
191 'zig fmt': new Set(['--check']),
192 stylua: new Set(['--check']),
193 pint: new Set(['--test']),
194 'php-cs-fixer fix': new Set(['--dry-run']),
195}
196const RUSTFMT_CONFIG_FILE_KINDS = new Set(['default', 'minimal'])
197const OFF_VALUES = new Set(['false', 'f', '0', 'no', 'off'])
198const FORMATTER_INFO_FLAGS = new Set(['-h', '--help', '-V', '--version'])
199
200// Wrappers and runners the shell reader does not place, stepped through here
201// so the program behind them is judged. Each runner lists the subcommands that
202// run another program. The value options take the next word.
203const PASS_THROUGH: ReadonlySet<string> = new Set(['npx', 'bunx', 'pnpx', 'noglob'])
204const RUNNERS: Readonly<Record<string, ReadonlySet<string>>> = {
205 bundle: new Set(['exec']), uv: new Set(['run']), poetry: new Set(['run']), pipx: new Set(['run']),
206 pnpm: new Set(['exec', 'dlx']), npm: new Set(['exec', 'x']), yarn: new Set(['exec', 'dlx', 'run']), composer: new Set(['exec']),
207}
208const YARN_OWN_WRITER_NAMES = new Set(['install', 'unlink', 'patch'])
209const RUNNER_VALUE_OPTIONS: Readonly<Record<string, readonly string[]>> = {
210 npx: ['-p', '--package'],
211 uv: ['-w', '--with', '--with-editable', '--with-requirements', '-p', '--python', '--package', '--extra', '--group', '--env-file', '--index', '-i', '--index-url', '--directory', '--project'],
212 poetry: ['-C', '--directory', '-P', '--project'],
213 pipx: ['--spec', '--python', '--pip-args', '--index-url'],
214 pnpm: ['-C', '--dir', '-F', '--filter', '--package'],
215 npm: ['-p', '--package', '--prefix', '-w', '--workspace'],
216 yarn: ['--cwd', '-p', '--package'],
217 composer: ['-d', '--working-dir'],
218}
219const RUNNER_CHDIR_OPTIONS: Readonly<Record<string, readonly string[]>> = {
220 uv: ['--directory'], poetry: ['-C', '--directory'], pnpm: ['-C', '--dir'], npm: ['-w', '--workspace', '--prefix'],
221 yarn: ['--cwd'], composer: ['-d', '--working-dir'],
222}
223// A runner option whose value is a command line, which the guard cannot read.
224const RUNNER_SCRIPT_OPTIONS: Readonly<Record<string, readonly string[]>> = { npm: ['-c', '--call'], npx: ['-c', '--call'] }
225
226// Builtins that change the directory later statements run in.
227const DIRECTORY_CHANGES = new Set(['cd', 'pushd', 'popd', 'chdir'])
228
229// Programs that never run a command named among their words, so a writer's
230// name there is data: `grep -rn chmod .`, `man rm`, `command -v tee`.
231const KNOWN: ReadonlySet<string> = new Set([
232 'echo', 'printf', 'cat', 'head', 'tail', 'wc', 'ls', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'ack', 'jq', 'yq', 'man',
233 'which', 'type', 'whereis', 'whatis', 'apropos', 'command', 'file', 'stat', 'diff', 'cmp', 'comm', 'cut', 'tr',
234 'column', 'nl', 'less', 'more', 'test', '[', '[[', '((', 'printenv', 'basename', 'dirname', 'realpath', 'readlink',
235 'true', 'false', ':', 'cd', 'pushd', 'popd', 'pwd', 'git', 'gh', 'date', 'sleep', 'help', 'hash', 'alias',
236 'export', 'local', 'declare', 'readonly', 'unset', 'set', 'trap', 'tldr', 'mktemp',
237 // A case pattern and a loop's word list are words, never commands.
238 'case', 'for', 'select',
239])
240
241// Names that run or write when they stand among another program's words.
242const WRITER_NAMES: ReadonlySet<string> = new Set([
243 ...MUTATING, ...Object.keys(IN_PLACE_EDITORS), ...Object.keys(FORMATTER_WRITE_FLAGS), 'black', 'rustfmt', 'cargo',
244 'go', 'ruff', 'isort', 'terraform', 'mix', 'dotnet', 'deno', 'zig', 'stylua', 'pint', 'php-cs-fixer', 'git', 'find',
245 'awk', 'gawk', 'mawk', 'nawk', 'bash', 'sh', 'zsh', 'dash', 'ksh', 'fish', 'csh', 'tcsh', 'eval', 'exec', 'source',
246 'env', 'sudo', 'doas', 'nohup', 'nice', 'ionice', 'stdbuf', 'timeout', 'gtimeout', 'xargs', 'parallel',
247 'caffeinate', 'chronic', 'unbuffer', 'flock', 'setsid', 'watch', 'time', 'builtin', ...PASS_THROUGH,
248 ...Object.keys(RUNNERS),
249])
250
251const AWK = new Set(['awk', 'gawk', 'mawk', 'nawk'])
252
253// A command name the shell builds at run time: a brace, a glob, or zsh's
254// `=name` path expansion.
255const BUILT_NAME = /[{}*?[\]]|^=/
256
257// A GIT_* assignment in front of git.
258const isGitEnv = (word: string): boolean => /^GIT_[A-Za-z0-9_]*\+?=/.test(word)
259
260// Commands that can change the environment later commands on the line
261// inherit: they set, export, or import variables by name, or run text that
262// could. printf counts only with -v.
263const ENV_CHANGERS: ReadonlySet<string> = new Set([
264 'export', 'declare', 'typeset', 'local', 'readonly', 'read', 'mapfile', 'readarray', 'getopts', 'for', 'select',
265 'set', 'source', '.', 'eval', 'let', '((', 'unset',
266 // zsh, Mike's shell: its options (allexport among them), its declarations,
267 // and the builtins that set a variable by name.
268 'setopt', 'unsetopt', 'emulate', 'integer', 'float', 'vared', 'zparseopts', 'getln',
269])
270
271// Builtins that set a variable by name only with one of these options:
272// printf -v and print -v, zsh's strftime -s, and zstyle's lookup forms.
273const SETS_BY_OPTION: Readonly<Record<string, RegExp>> = {
274 printf: /^-[A-Za-z]*v/,
275 print: /^-[A-Za-z]*v/,
276 strftime: /^-[A-Za-z]*s/,
277 zstyle: /^-/,
278}
279
280// A parameter expansion that assigns: ${x:=y} or ${x=y}.
281const ASSIGNING_EXPANSION = /\$\{[^}]*?:?=/
282
283// Whether a statement can change the environment of the others on its line.
284const changesEnv = (st: Statement): boolean =>
285 st.assignments.length > 0 ||
286 (ENV_CHANGERS.has(st.name) && st.nameAt >= 0) ||
287 (SETS_BY_OPTION[st.name] !== undefined && st.args.some(a => SETS_BY_OPTION[st.name]?.test(a) === true)) ||
288 st.words.some(w => ASSIGNING_EXPANSION.test(w))
289
290// A path holding any of these is shell the guard does not expand.
291const UNRESOLVABLE = /[$`*?[\]{}()'"\\<>\uE000]/
292
293// Redirect targets that write no file.
294const DEVICE = /^\/dev\/(?:null|stdout|stderr|tty|fd\/[0-9]+)$/
295
296const basename = (word: string): string => (word.split('/').pop() ?? word).toLowerCase()
297
298// The absolute path a command names, or undefined when it cannot be known.
299export function resolvePath(raw: string, cwd: string | undefined, home: string | undefined): string | undefined {
300 let target = raw
301 if (target === '~' || target.startsWith('~/')) {
302 if (!home) return undefined
303 target = home + target.slice(1)
304 }
305 if (target === '' || target.startsWith('~') || UNRESOLVABLE.test(target)) return undefined
306 if (!target.startsWith('/')) {
307 if (!cwd) return undefined
308 target = `${cwd.replace(/\/$/, '')}/${target}`
309 }
310 return target
311}
312
313// Options of a reading verb that run a program, name one, or run one the
314// configuration names, by verb: each refused as `git -c` is. A long option is
315// matched by any cut git accepts down to the length given, so `--open-files=`
316// is `--open-files-in-pager`. git log's `-O<file>` is an order file and reads.
317const PROGRAM_OPTIONS: Readonly<Record<string, readonly [string, number][]>> = {
318 // grep alone runs textconv only when asked.
319 grep: [['-O', 2], ['--open-files-in-pager', 6], ['--ext-grep', 7], ['--textconv', 7]],
320 'ls-remote': [['--upload-pack', 4], ['--exec', 5]],
321 archive: [['--exec', 5], ['--remote', 8]],
322 diff: [['--ext-diff', 6], ['--textconv', 7]],
323 log: [['--ext-diff', 6], ['--textconv', 7]],
324 show: [['--ext-diff', 6], ['--textconv', 7]],
325 whatchanged: [['--ext-diff', 6], ['--textconv', 7]],
326 'diff-tree': [['--ext-diff', 6], ['--textconv', 7]],
327 'diff-index': [['--ext-diff', 6], ['--textconv', 7]],
328 blame: [['--textconv', 7]],
329 annotate: [['--textconv', 7]],
330 'cat-file': [['--textconv', 7], ['--filters', 5]],
331}
332
333// The option of `rest` that runs a program, or undefined. `--` ends options.
334function programOption(verb: string, rest: readonly string[]): string | undefined {
335 for (const arg of rest) {
336 if (arg === '--') return undefined
337 const key = arg.split('=')[0] ?? arg
338 for (const [option, shortest] of PROGRAM_OPTIONS[verb] ?? []) {
339 // A short option counts anywhere in a single-dash cluster (`-nOcat`).
340 const isShort = !option.startsWith('--') && arg.startsWith('-') && !arg.startsWith('--') && arg.includes(option.slice(1))
341 if (option.startsWith('--') ? key.length >= shortest && option.startsWith(key) : isShort) return option
342 }
343 }
344 return undefined
345}
346
347// git's own verdict on `git <verb> <rest>`: true when it only reads.
348function gitReads(verb: string, rest: readonly string[]): boolean {
349 if (programOption(verb, rest) !== undefined) return false
350 if (GIT_READ_ONLY.has(verb)) return true
351 const flags = rest.filter(a => a.startsWith('-'))
352 let positionals = rest.filter(a => !a.startsWith('-'))
353 // symbolic-ref reads a ref with one argument, and sets or deletes it with
354 // two or with -d.
355 if (verb === 'symbolic-ref') {
356 return positionals.length === 1 && flags.every(f => ['-q', '--quiet', '--short', '--recurse', '--no-recurse'].includes(f))
357 }
358 // reflog shows by default; expire, delete and drop destroy the recovery trail.
359 if (verb === 'reflog') return !['expire', 'delete', 'drop'].includes(positionals[0] ?? '')
360 const isListing = flags.includes('-l') || flags.includes('--list')
361 if (verb === 'branch' || verb === 'tag') {
362 positionals = rest.filter((a, i) => !a.startsWith('-') && !(i > 0 && LIST_VALUE_FLAGS.has(rest[i - 1] ?? '')))
363 const allowed = verb === 'branch' ? BRANCH_READ_FLAGS : TAG_READ_FLAGS
364 const flagsOk = flags.every(f => allowed.has(f) || LIST_VALUE_PREFIXES.some(p => f.startsWith(p)) || (verb === 'tag' && /^-n\d+$/.test(f)))
365 return flagsOk && (positionals.length === 0 || isListing)
366 }
367 const first = positionals[0]
368 if (verb === 'remote') {
369 return flags.every(f => ['-v', '--verbose', '--all', '--push', '-n'].includes(f)) && (first === undefined || first === 'get-url' || first === 'show')
370 }
371 if (verb === 'config') {
372 if (flags.some(f => CONFIG_WRITE_FLAGS.has(f.split('=')[0] ?? f))) return false
373 return flags.some(f => CONFIG_READ_FLAGS.has(f)) || first === 'get' || first === 'list'
374 }
375 if (verb === 'stash') return first === 'list' || first === 'show'
376 if (verb === 'worktree') return first === 'list'
377 return false
378}
379
380// The files git writes beside its output: `--output <f>`, `-o <f>` for archive.
381function gitOutputs(verb: string, rest: readonly string[]): string[] {
382 const out: string[] = []
383 rest.forEach((arg, i) => {
384 if (arg.startsWith('--output=')) out.push(arg.slice('--output='.length))
385 else if (arg === '--output' || (verb === 'archive' && arg === '-o')) out.push(rest[i + 1] ?? '')
386 else if (verb === 'archive' && /^-o./.test(arg)) out.push(arg.slice(2))
387 })
388 return out
389}
390
391// The operands of a writer: the words that are not options or option values.
392function operandsOf(name: string, args: readonly string[]): string[] {
393 const operands: string[] = []
394 let isDone = false
395 for (let i = 0; i < args.length; i++) {
396 const arg = args[i] ?? ''
397 if (!isDone && arg === '--') isDone = true
398 else if (isDone || !arg.startsWith('-') || arg === '-') operands.push(arg)
399 else if (VALUE_OPTIONS[name]?.has(arg)) i++
400 }
401 return operands
402}
403
404function tarTargets(args: readonly string[], cwd: string): string[] {
405 const longModes: Record<string, string> = { '--extract': 'x', '--get': 'x', '--create': 'c', '--append': 'r', '--update': 'u', '--catenate': 'A', '--concatenate': 'A', '--delete': 'r' }
406 const modes = new Set<string>()
407 const archives: string[] = []
408 const dirs: string[] = []
409 let toStdout = false
410 for (let i = 0; i < args.length; i++) {
411 const arg = args[i] ?? ''
412 if (arg.startsWith('--')) {
413 const at = arg.indexOf('=')
414 const key = at < 0 ? arg : arg.slice(0, at)
415 for (const m of longModes[key] ?? '') modes.add(m)
416 toStdout ||= key === '--to-stdout'
417 if (key === '--file' || key === '--directory') {
418 const value = at < 0 ? (args[++i] ?? '') : arg.slice(at + 1)
419 ;(key === '--file' ? archives : dirs).push(value)
420 }
421 } else if ((arg.startsWith('-') && arg !== '-') || i === 0) {
422 const letters = arg.replace(/^-+/, '')
423 for (let j = 0; j < letters.length; j++) {
424 const char = letters[j] ?? ''
425 if (char === 'f' || char === 'C') {
426 let value = arg.startsWith('-') ? letters.slice(j + 1) : ''
427 if (!value) value = args[++i] ?? ''
428 ;(char === 'f' ? archives : dirs).push(value)
429 if (arg.startsWith('-')) break
430 } else {
431 if ('xcruA'.includes(char)) modes.add(char)
432 toStdout ||= char === 'O'
433 }
434 }
435 }
436 }
437 const targets: string[] = []
438 if ([...modes].some(m => 'cruA'.includes(m))) targets.push(...archives.filter(a => a !== '-'))
439 if (modes.has('x') && !toStdout) targets.push(...(dirs.length > 0 ? dirs : [cwd]))
440 return targets
441}
442
443function unzipTargets(args: readonly string[], cwd: string): string[] {
444 let letters = ''
445 let dest: string | undefined
446 const operands: string[] = []
447 for (let i = 0; i < args.length; i++) {
448 const arg = args[i] ?? ''
449 if (arg.startsWith('-') && !arg.startsWith('--') && arg.length > 1) {
450 for (let j = 1; j < arg.length; j++) {
451 if (arg[j] === 'd') {
452 dest = arg.slice(j + 1) || (args[++i] ?? '')
453 break
454 }
455 letters += arg[j]
456 }
457 } else if (!arg.startsWith('-')) operands.push(arg)
458 }
459 if (operands.length === 0 || [...letters].some(l => UNZIP_READ_FLAGS.has(l))) return []
460 return [dest ?? cwd]
461}
462
463function sortTargets(args: readonly string[]): string[] {
464 const targets: string[] = []
465 args.forEach((arg, i) => {
466 const next = args[i + 1] ?? ''
467 if (arg.startsWith('--output')) targets.push(arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : next)
468 else if (/^-[A-Za-z]*o$/.test(arg)) targets.push(next)
469 else if (/^-[A-Za-z]*o.+/.test(arg) && !arg.startsWith('--')) targets.push(arg.slice(arg.indexOf('o') + 1))
470 })
471 return targets
472}
473
474// The paths a MUTATING command writes, as written. An extra path can only
475// refuse more. `cwd` is '' when it is unknown, which no path resolves under.
476function writeTargets(name: string, args: readonly string[], cwd: string): string[] {
477 const operands = operandsOf(name, args)
478 if (name === 'dd') return args.filter(a => a.startsWith('of=')).map(a => a.slice(3))
479 if (name === 'cp' || name === 'ln' || name === 'install') {
480 for (let i = 0; i < args.length; i++) {
481 const arg = args[i] ?? ''
482 if (arg.startsWith('--target-directory=')) return [arg.slice(arg.indexOf('=') + 1)]
483 if (arg === '--target-directory' || /^-[A-Za-z]*t$/.test(arg)) return [args[i + 1] ?? '']
484 if (/^-[A-Za-z]*t.+/.test(arg) && !arg.startsWith('--')) return [arg.slice(arg.indexOf('t') + 1)]
485 }
486 if (name === 'install' && args.includes('-d')) return operands
487 if (name === 'ln' && operands.length === 1) return [cwd ? `${cwd}/${basename(operands[0] ?? '')}` : '']
488 // The destination is the last operand; a source is only read.
489 return operands.slice(-1)
490 }
491 if (name === 'chmod' || name === 'chown' || name === 'chgrp') {
492 return args.some(a => a.startsWith('--reference')) ? operands : operands.slice(1)
493 }
494 if (name === 'rsync') {
495 if (args.includes('--remove-source-files')) return operands
496 return operands.length > 1 ? operands.slice(-1) : []
497 }
498 if (name === 'tar') return tarTargets(args, cwd)
499 if (name === 'unzip') return unzipTargets(args, cwd)
500 if (name === 'sort') return sortTargets(args)
501 if (name === 'uniq') return operands.slice(1)
502 if (name === 'patch') {
503 let directory = cwd
504 args.forEach((arg, i) => {
505 if (arg === '-d' || arg === '--directory') directory = args[i + 1] ?? ''
506 else if (arg.startsWith('--directory=')) directory = arg.slice('--directory='.length)
507 else if (arg.startsWith('-d') && arg.length > 2) directory = arg.slice(2)
508 })
509 return [...operands, directory]
510 }
511 return operands
512}
513
514// The files an in-place sed, perl or ruby edits, or undefined when it edits
515// none in place.
516function inPlaceTargets(name: string, args: readonly string[]): string[] | undefined {
517 const editor = IN_PLACE_EDITORS[name]
518 if (editor === undefined) return undefined
519 let isInPlace = false
520 let hasCode = false
521 const operands: string[] = []
522 for (let i = 0; i < args.length; i++) {
523 const arg = args[i] ?? ''
524 if (arg === '--') {
525 operands.push(...args.slice(i + 1))
526 break
527 }
528 if (arg.startsWith('--')) {
529 if (arg.startsWith('--in-place')) isInPlace = true
530 if (name === 'sed' && (arg === '--expression' || arg === '--file')) {
531 hasCode = true
532 i++
533 } else if (name === 'sed' && (arg.startsWith('--expression=') || arg.startsWith('--file='))) hasCode = true
534 continue
535 }
536 if (!arg.startsWith('-') || arg === '-') {
537 operands.push(arg)
538 continue
539 }
540 for (let j = 1; j < arg.length; j++) {
541 const char = arg[j] ?? ''
542 if (editor.inPlace.includes(char)) {
543 isInPlace = true
544 // BSD sed takes the backup suffix as the next word: `sed -i '' …`.
545 if (name === 'sed' && j === arg.length - 1 && (args[i + 1] === '' || /^\.[A-Za-z0-9_~-]*$/.test(args[i + 1] ?? ''))) i++
546 // GNU's attached suffix (`-i.bak`) is the rest of the word.
547 if (name === 'sed' || name === 'perl' || name === 'ruby') {
548 if (j < arg.length - 1 && !/^[A-Za-z]/.test(arg.slice(j + 1))) break
549 }
550 continue
551 }
552 if (editor.value.includes(char)) {
553 if (CODE_LETTERS[name]?.includes(char)) hasCode = true
554 if (j === arg.length - 1) i++
555 break
556 }
557 }
558 }
559 if (!isInPlace) return undefined
560 // With no -e or -f, the first operand is the program, not a file.
561 return hasCode ? operands : operands.slice(1)
562}
563
564// A sed program that writes a file (w, W, s///w) or runs a command (e).
565const SED_WRITES = /(?:^|[;\n{}\d$/])\s*[wW]\s*\S|(?:^|[;\n{}])\s*e(?:\s|$|;)|\/[gpiImM0-9]*e[gpiImM0-9]*\s*(?:$|[;}\n])/
566// An awk program that prints to a file or a pipe, reads a command, or runs one.
567const AWK_WRITES = /\bsystem\s*\(|\|\s*(?:&\s*)?getline|\bprintf?\b[^;}\n]*(?:>|\|)|"\s*\|\s*getline/
568
569function sedPrograms(args: readonly string[]): string[] {
570 const programs: string[] = []
571 let hasFlag = false
572 for (let i = 0; i < args.length; i++) {
573 const arg = args[i] ?? ''
574 if (arg === '-e' || arg === '--expression') {
575 hasFlag = true
576 programs.push(args[++i] ?? '')
577 } else if (arg.startsWith('--expression=')) {
578 hasFlag = true
579 programs.push(arg.slice('--expression='.length))
580 } else if (/^-[A-Za-z]*e./.test(arg) && !arg.startsWith('--')) {
581 hasFlag = true
582 programs.push(arg.slice(arg.indexOf('e') + 1))
583 } else if (arg === '-f' || arg === '--file' || arg.startsWith('--file=')) {
584 hasFlag = true
585 }
586 }
587 if (!hasFlag) {
588 const first = args.find(a => !a.startsWith('-'))
589 if (first !== undefined) programs.push(first)
590 }
591 return programs
592}
593
594function formatterWrites(name: string, args: readonly string[]): string | undefined {
595 if (/^python[0-9.]*$/.test(name) && args[0] === '-m' && args.length > 1) {
596 name = args[1] ?? ''
597 args = args.slice(2)
598 }
599 for (const arg of args) {
600 let key = arg.split('=')[0] ?? arg
601 if (key.length === 3 && key.startsWith('--')) key = key.slice(1)
602 if (FORMATTER_WRITE_FLAGS[name]?.has(key)) return name
603 }
604 const cluster = FORMATTER_CLUSTER_FLAGS[name]
605 if (cluster !== undefined) {
606 for (const arg of args) {
607 if (arg.startsWith('--') || !arg.startsWith('-')) continue
608 for (const char of arg.slice(1)) {
609 if (cluster.write.includes(char)) return name
610 if (cluster.value.includes(char)) break
611 }
612 }
613 }
614 const sub = args.find(a => !a.startsWith('-') && !a.startsWith('+')) ?? ''
615 const key = name in FORMATTERS_WRITING_BY_DEFAULT ? name : `${name} ${sub}`
616 const checks = FORMATTERS_WRITING_BY_DEFAULT[key]
617 if (checks === undefined) return undefined
618 const words = new Set<string>(args)
619 args.forEach((a, i) => {
620 if (i + 1 < args.length) words.add(`${a}=${args[i + 1]}`)
621 const at = a.indexOf('=')
622 if (at >= 0 && !OFF_VALUES.has(a.slice(at + 1).toLowerCase())) words.add(a.slice(0, at))
623 })
624 if (key === 'rustfmt' && words.has('--print-config')) {
625 const operands = args.filter(a => !a.startsWith('-'))
626 const joined = args.filter(a => a.startsWith('--print-config=')).map(a => a.slice('--print-config='.length))
627 const kind = joined[0] ?? operands.shift() ?? ''
628 return operands.length > 0 && RUSTFMT_CONFIG_FILE_KINDS.has(kind) ? key : undefined
629 }
630 if ([...words].some(w => checks.has(w) || FORMATTER_INFO_FLAGS.has(w))) return undefined
631 const operands = args.filter((a, i) => !a.startsWith('-') && !a.startsWith('+') && (i === 0 || !STDIN_NAME_OPTIONS.has(args[i - 1] ?? '')))
632 if (key.includes(' ')) operands.splice(operands.indexOf(sub), 1)
633 if (operands.length === 0 && (args.includes('-') || key === 'rustfmt')) return undefined
634 return key
635}
636
637// The program behind the runners and wrappers the shell reader does not place:
638// its name, its words, whether it changes directory, and a finding when its
639// command cannot be read at all.
640function stepThrough(name: string, args: readonly string[]): { name: string; args: readonly string[]; chdir: boolean; finding?: Finding } {
641 let chdir = false
642 for (let guard = 0; guard < 16; guard++) {
643 const runner = RUNNERS[name]
644 if (!PASS_THROUGH.has(name) && runner === undefined) break
645 const values = RUNNER_VALUE_OPTIONS[name] ?? []
646 const matches = (options: readonly string[], key: string) => options.some(o => key === o || (o.startsWith('--') && key.length > 3 && o.startsWith(key)))
647 // Steps over the options from `i`, before and after a run subcommand.
648 let i = 0
649 let script: string | undefined
650 const skipOptions = () => {
651 while (i < args.length && (args[i] ?? '').startsWith('-')) {
652 const arg = args[i] ?? ''
653 const key = arg.split('=')[0] ?? arg
654 if (matches(RUNNER_SCRIPT_OPTIONS[name] ?? [], key)) script = key
655 if (matches(RUNNER_CHDIR_OPTIONS[name] ?? [], key)) chdir = true
656 i += matches(values, key) && !arg.includes('=') ? 2 : 1
657 }
658 }
659 skipOptions()
660 if (runner !== undefined) {
661 const sub = args[i]
662 if (sub !== undefined && runner.has(sub)) {
663 i++
664 skipOptions()
665 } else if (sub === undefined || !(name === 'yarn' && !YARN_OWN_WRITER_NAMES.has(sub))) {
666 return { name, args, chdir }
667 }
668 }
669 if (script !== undefined) {
670 return { name, args, chdir, finding: { action: `\`${name} ${script}\``, reason: `\`${name} ${script}\` hands over a command line the guard cannot read.` } }
671 }
672 if (i >= args.length) return { name, args, chdir }
673 name = basename(args[i] ?? '')
674 args = args.slice(i + 1)
675 }
676 return { name, args, chdir }
677}
678
679const unreadable = (what: string): Finding => ({
680 action: 'a command the guard cannot read',
681 reason: `${what}, so the guard cannot tell whether it writes. Run each command plainly, with literal paths.`,
682})
683
684// Options of env and sudo that run the command in another directory.
685const CHDIR_WORD = /^(?:-[A-Za-z]*[CD]|--ch)/
686
687export type Context = {
688 // The directory the line starts in; undefined when it is not known.
689 cwd: string | undefined
690 home: string | undefined
691 // Prose in a fenced block, read one line at a time by a lint: what the
692 // reader could not read is passed over, a word that is not a command name
693 // (an unknown program, a name built at run time) is not judged, and neither
694 // are redirects. The rules a known command meets still apply.
695 isDocs?: boolean
696}
697
698// The verdict on one Bash line: a finding, or the paths it writes.
699export function reviewBash(parse: ShellParse, context: Context): Verdict {
700 const isDocs = context.isDocs === true
701 if (!isDocs && parse.unknowns.length > 0) {
702 return { finding: unreadable(`The line holds shell the reader cannot read (${parse.unknowns.join(', ')})`) }
703 }
704 const writes: Write[] = []
705 let cwd = context.cwd
706 const write = (writer: string, raw: string) => writes.push({ writer, raw, path: resolvePath(raw, cwd, context.home) })
707 // Another statement on the line that can change what a git inherits.
708 const envChangers = parse.statements.filter(changesEnv)
709 for (const s of parse.statements) {
710 if (!s.isPlaced && !isDocs) return { finding: unreadable(`A wrapper option in front of \`${s.words[s.nameAt] ?? ''}\` cannot be placed`) }
711 if (!isDocs) {
712 for (const r of s.redirects) {
713 if (!r.isReal) continue
714 const isFile = ['>', '>>', '>|', '&>', '&>>', '<>'].includes(r.op) || (r.op === '>&' && !/^(?:[0-9]+-?|-)$/.test(r.target))
715 if (!isFile || DEVICE.test(r.target)) continue
716 // zsh reads `>!` and `>>!` as one operator that clobbers the next
717 // word, where bash reads a file named `!`: both are judged.
718 if (r.target === '!') writes.push({ writer: 'a redirect', raw: r.target, path: undefined })
719 else write('a redirect', r.target)
720 if (r.target.startsWith('!') && r.target.length > 1) write('a redirect', r.target.slice(1))
721 }
722 }
723 if (s.nameAt < 0) continue
724 const pre = s.words.slice(0, s.nameAt)
725 if ((s.wrappers.includes('env') || s.wrappers.includes('sudo')) && pre.some(w => CHDIR_WORD.test(w))) cwd = undefined
726 if (!isDocs && BUILT_NAME.test(s.name) && !['[', '[['].includes(s.name)) {
727 return { finding: unreadable(`The command name \`${s.words[s.nameAt] ?? ''}\` is built when the line runs`) }
728 }
729 const stepped = stepThrough(s.name, s.args)
730 if (stepped.finding !== undefined) return { finding: stepped.finding }
731 if (stepped.chdir) cwd = undefined
732 const { name, args } = stepped
733 const isFed = s.wrappers.includes('xargs') || s.wrappers.includes('parallel')
734 if (DIRECTORY_CHANGES.has(name)) {
735 cwd = undefined
736 continue
737 }
738 if (name === 'git') {
739 const at = s.subcommandAt
740 const globals = at < 0 ? s.args : s.args.slice(0, at)
741 if (globals.some(a => a === '-c' || /^-c./.test(a) || a.startsWith('--config-env') || a.startsWith('--exec-path='))) {
742 return { finding: { action: '`git -c`', reason: 'git is run with configuration on its command line, which can name a program git runs (core.pager, diff.external, an alias). Run git without -c.' } }
743 }
744 // The environment is configuration too: GIT_EXTERNAL_DIFF, GIT_SSH_COMMAND
745 // and GIT_CONFIG_COUNT/KEY/VALUE each name a program git runs.
746 if (s.assignments.some(isGitEnv) || s.words.some(w => ASSIGNING_EXPANSION.test(w)) || envChangers.some(st => st !== s)) {
747 return {
748 finding: {
749 action: '`git` beside a change to its environment',
750 reason:
751 'git is run with a GIT_ variable in front of it, or beside a command that can change the environment it inherits (an assignment, export, read, a for loop, set, source, eval). A GIT_ variable can name a program git runs (GIT_EXTERNAL_DIFF, GIT_SSH_COMMAND, GIT_CONFIG_COUNT). Run git on its own line, with no variable set before it.',
752 },
753 }
754 }
755 if (at >= 0) {
756 const verb = (s.args[at] ?? '').toLowerCase()
757 const rest = s.args.slice(at + 1)
758 if (!gitReads(verb, rest)) {
759 return {
760 finding: {
761 action: `\`git ${verb}\``,
762 reason: `\`git ${verb}\` is not one of git's read-only forms, so it is refused wherever it points. \`git restore\`, \`checkout\`, \`switch\`, \`reset\`, \`clean\`, and \`stash\` all discard exactly the uncommitted change a Local-mode review is sent to read.`,
763 },
764 }
765 }
766 for (const out of gitOutputs(verb, rest)) write(`git ${verb}`, out)
767 }
768 continue
769 }
770 if (MUTATING.has(name)) {
771 if (isFed) return { finding: { action: `\`${name}\``, reason: `\`${name}\` changes files, and its paths arrive from xargs or parallel at run time, where the guard cannot read them.` } }
772 for (const raw of writeTargets(name, args, cwd ?? '')) write(name, raw)
773 continue
774 }
775 if (name === 'find') {
776 const writer = args.find(a => ['-delete', '-exec', '-execdir', '-ok', '-okdir', '-fprint', '-fprint0', '-fprintf', '-fls'].includes(a))
777 if (writer !== undefined) return { finding: { action: `\`find ${writer}\``, reason: `\`find ${writer}\` deletes, writes, or runs a command against the files it matches.` } }
778 continue
779 }
780 const inPlace = inPlaceTargets(name, args)
781 if (inPlace !== undefined) {
782 if (isFed || inPlace.length === 0) return { finding: { action: `\`${name} -i\``, reason: `\`${name} -i\` rewrites files in place, and the guard cannot tell which.` } }
783 for (const raw of inPlace) write(`${name} -i`, raw)
784 }
785 if (name === 'sed' && sedPrograms(args).some(p => SED_WRITES.test(p))) {
786 return { finding: { action: '`sed` writing or running', reason: 'the sed program writes a file (w) or runs a command (e).' } }
787 }
788 if (AWK.has(name) && args.some(a => AWK_WRITES.test(a))) {
789 return { finding: { action: `\`${name}\` writing or running`, reason: `the ${name} program prints to a file or a pipe, or runs a command.` } }
790 }
791 if (inPlace === undefined && args.some(a => IN_PLACE_FLAGS.has(a.split('=')[0] ?? a))) {
792 return { finding: { action: `\`${name}\` with a rewrite flag`, reason: `\`${name}\` is being run with a rewrite flag. Run formatters and linters in check mode only.` } }
793 }
794 const formatter = formatterWrites(name, args)
795 if (formatter !== undefined) {
796 return { finding: { action: `\`${formatter}\` rewriting files`, reason: `\`${formatter}\` rewrites files unless it runs in check mode. Run formatters and linters in check mode only, such as \`--check\`.` } }
797 }
798 if (!isDocs && !KNOWN.has(name)) {
799 // Each word of an argument counts, after an `=` too: `--split-string=rm x`.
800 const behind = args.flatMap(a => a.split(/[\s=]+/)).find(word => WRITER_NAMES.has(basename(word)))
801 if (behind !== undefined) {
802 return { finding: unreadable(`\`${name}\` is a program the guard does not know, and \`${behind}\` stands among its words, where it may run`) }
803 }
804 }
805 }
806 return { writes }
807}
808
809// The verdict on an Edit, Write or NotebookEdit of `raw`.
810export function reviewEdit(tool: string, raw: string, context: Context): Verdict {
811 return { writes: [{ writer: tool, raw, path: resolvePath(raw, context.cwd, context.home) }] }
812}
813
814// The refusal the model reads: the action, the reason, and the way to work.
815export function refusalOf(finding: Finding, roots: readonly string[]): string {
816 const where = roots.map(root => `\`${root}\``).join(', ') || 'none could be found on this host'
817 return (
818 `🛑 Blocked: ${finding.action}. A Holmes reviewer writes only in scratch.\n\n` +
819 `Review guard (workbench-dev-team). This command is refused, because ${finding.reason}\n\n` +
820 'You are running as a Holmes reviewer, and a reviewer writes nothing outside ' +
821 `the scratch roots. The scratch roots here are: ${where}. The code under review ` +
822 "is read, never changed: in Local mode it is the human's live working " +
823 'directory, and the uncommitted change in it is the only copy of the work.\n\n' +
824 'Read it instead. `git status`, `git diff HEAD`, `git ls-files --others ' +
825 '--exclude-standard`, and `git show` are all allowed, and so is the test suite. ' +
826 'Validate by running the existing tests in place and reading them. Write no ' +
827 'probe script, copy no repository, and change no code, not even in scratch. ' +
828 'Report a hole no test covers as a finding that names the missing test. ' +
829 'If a failure looks pre-existing, say so in your findings — never ' +
830 'isolate it by changing the tree.\n\n' +
831 'There is no flag to clear and no path around this. If you believe you are not ' +
832 'a reviewer, report that to the session that dispatched you and stop.'
833 )
834}
835
836// The disk, as the guard reads it. stat answers where a path lands with every
837// symlink resolved (realPath undefined when it leads nowhere), or undefined
838// when nothing is there. names lists a directory's entries, links included.
839export type Disk = {
840 stat: (path: string) => Promise<{ realPath: string | undefined } | undefined>
841 names: (dir: string) => Promise<string[] | undefined>
842}
843
844// Where an absolute path lands with every symlink resolved: the deepest part
845// that exists, resolved, then the rest as written. Undefined when a part that
846// does not exist is `.` or `..`, or exists only as a link that leads nowhere,
847// since either could land anywhere.
848export async function landing(path: string, disk: Disk): Promise<string | undefined> {
849 const parts = path.split('/').filter(part => part !== '')
850 for (let i = parts.length; i >= 0; i--) {
851 const head = `/${parts.slice(0, i).join('/')}`
852 const stat = await disk.stat(head)
853 if (stat === undefined) continue
854 if (stat.realPath === undefined) return undefined
855 const rest = parts.slice(i)
856 if (rest.some(part => part === '.' || part === '..')) return undefined
857 if (rest.length > 0) {
858 const names = await disk.names(head)
859 if (names === undefined || names.includes(rest[0] ?? '')) return undefined
860 }
861 return [stat.realPath.replace(/\/$/, ''), ...rest].join('/')
862 }
863 return undefined
864}
865
866// Whether a path lands strictly beneath a scratch root, both through every
867// symlink and with its final name left where it lives: `rm <dir>/link`
868// removes the link where it lives, wherever it points.
869export async function isInScratch(path: string, roots: readonly string[], disk: Disk): Promise<boolean> {
870 const trimmed = path.replace(/\/+$/, '')
871 const cut = trimmed.lastIndexOf('/')
872 const name = trimmed.slice(cut + 1)
873 const followed = await landing(path, disk)
874 let own = followed
875 if (!(name === '' || name === '.' || name === '..' || path.endsWith('/'))) {
876 const parent = await landing(trimmed.slice(0, cut) || '/', disk)
877 own = parent === undefined ? undefined : `${parent.replace(/\/$/, '')}/${name}`
878 }
879 const beneath = (p: string | undefined) => p !== undefined && roots.some(root => p.startsWith(`${root.replace(/\/$/, '')}/`))
880 return beneath(followed) && beneath(own)
881}
882
883// The first write that lands outside the scratch roots, as a finding.
884export async function judgeWrites(writes: readonly Write[], roots: readonly string[], disk: Disk): Promise<Finding | undefined> {
885 for (const w of writes) {
886 const base = `\`${w.writer}\` changes a file's content, location, existence, or metadata`
887 if (roots.length === 0) return { action: `\`${w.writer}\``, reason: `${base}, and no scratch root was found to judge its paths against.` }
888 if (w.path === undefined) return { action: `\`${w.writer}\``, reason: `${base}, and the path \`${w.raw || '(none)'}\` cannot be resolved.` }
889 if (!(await isInScratch(w.path, roots, disk))) return { action: `\`${w.writer}\``, reason: `${base}, and \`${w.raw}\` is outside the scratch roots.` }
890 }
891 return undefined
892}
893hooks/mods/panes.tsx 147 lines1// The two dev-team panes' trees, from the views hooks/register.ts keeps. Pure:
2// the elements come in from the hook's $.ui.resolve(e), and nothing here
3// touches `$`. Each row is a keyed Box, so a test finds it by key.
4
5import type { Color, Elements, RenderElement, RenderSurface } from 'claude-code'
6
7import type { BoardItem, BoardLane, BoardView, RunState, RunsView } from '../../types'
8
9export type Draw = Pick<Elements[RenderSurface], 'Box' | 'Text'>
10
11export const RUNS_PANE = 'dev-team-runs'
12export const BOARD_PANE = 'dev-team-board'
13
14const STATE_COLOR: Record<RunState, Color> = {
15 running: 'suggestion',
16 done: 'success',
17 failed: 'error',
18 refused: 'error',
19 'budget-killed': 'warning',
20 escalated: 'warning',
21}
22
23const pad = (n: number): string => String(n).padStart(2, '0')
24
25// A time of day, HH:MM, in the host's zone.
26export const clockOf = (ms: number): string => {
27 const at = new Date(ms)
28 return `${pad(at.getHours())}:${pad(at.getMinutes())}`
29}
30
31export function runsTree({ Box, Text }: Draw, view: RunsView, room: number): RenderElement {
32 if (view.error !== undefined) {
33 return (
34 <Box flexDirection="column">
35 <Text color="error">{view.error}</Text>
36 </Box>
37 )
38 }
39 if (view.rows.length === 0) {
40 return (
41 <Box flexDirection="column">
42 <Text dimColor>No dispatched runs in the logs yet.</Text>
43 </Box>
44 )
45 }
46 // Two lines a run: the run, then its log.
47 const rows = view.rows.slice(0, Math.max(1, Math.floor(room / 2)))
48 return (
49 <Box flexDirection="column">
50 {rows.map((row, i) => (
51 <Box key={`run-${i}`} flexDirection="column">
52 <Text wrap="truncate-end">
53 <Text color={STATE_COLOR[row.state]} bold>
54 {row.state.padEnd(13)}
55 </Text>
56 {` ${row.agent.padEnd(8)} ${row.target} · started ${row.startedAt}`}
57 {row.refusals > 0 ? ` · ${row.refusals} refused call${row.refusals === 1 ? '' : 's'}` : ''}
58 </Text>
59 <Text dimColor wrap="truncate-start">
60 {` ${row.log}`}
61 </Text>
62 </Box>
63 ))}
64 </Box>
65 )
66}
67
68const LANE_TITLE = { unrefined: 'Unrefined (Lestrade)', review: 'Review (Holmes)', development: 'Development (Watson)' } as const
69
70// How many items a lane holds: the count, or "25+" when the list came back full.
71const countOf = (lane: { limit: number; items: BoardItem[] }): string => (lane.items.length >= lane.limit ? `${lane.limit}+` : String(lane.items.length))
72
73const refOf = (item: BoardItem): string => `${item.number === null ? `item ${item.id}` : `${item.isPr ? 'PR ' : ''}#${item.number}`} ${item.repo ?? ''}`.trimEnd()
74
75// How many items each lane lists under its count.
76export const TOP_ITEMS = 3
77
78function laneRows({ Box, Text }: Draw, name: keyof typeof LANE_TITLE, lane: BoardLane): RenderElement {
79 if ('error' in lane) {
80 return (
81 <Box key={`lane-${name}`} flexDirection="column">
82 <Text>
83 <Text bold>{LANE_TITLE[name]}</Text>
84 <Text color="error">{` could not list: ${lane.error}`}</Text>
85 </Text>
86 </Box>
87 )
88 }
89 const claimed = name === 'development' ? lane.items.filter(item => item.claimedAt !== null).length : 0
90 return (
91 <Box key={`lane-${name}`} flexDirection="column">
92 <Text>
93 <Text bold>{LANE_TITLE[name]}</Text>
94 {` ${countOf(lane)}${claimed > 0 ? ` · ${claimed} claimed` : ''}`}
95 </Text>
96 {lane.items.slice(0, TOP_ITEMS).map(item => (
97 <Text dimColor wrap="truncate-end">
98 {` ${refOf(item)} ${item.title ?? ''}`}
99 </Text>
100 ))}
101 </Box>
102 )
103}
104
105export function boardTree(draw: Draw, view: BoardView, cadenceMs: number): RenderElement {
106 const { Box, Text } = draw
107 const board = view.board
108 const claimed = board && !('error' in board.development) ? board.development.items.filter(item => item.claimedAt !== null) : []
109 const status =
110 view.attemptedAt === 0
111 ? 'Fetching the board from The Index.'
112 : `${board && view.boardAt !== undefined ? `Fetched ${clockOf(view.boardAt)}` : 'Not fetched'} · next fetch after ${clockOf(view.attemptedAt + cadenceMs)}`
113 return (
114 <Box flexDirection="column">
115 <Box key="board-status">
116 <Text dimColor>{status}</Text>
117 </Box>
118 {view.error !== undefined && (
119 <Box key="board-error">
120 <Text color="error">{`The last fetch failed: ${view.error}`}</Text>
121 </Box>
122 )}
123 {board && laneRows(draw, 'unrefined', board.unrefined)}
124 {board && laneRows(draw, 'review', board.review)}
125 {board && laneRows(draw, 'development', board.development)}
126 {claimed.length > 0 && (
127 <Box key="claimed" flexDirection="column">
128 <Text bold>Claimed</Text>
129 {claimed.map(item => (
130 <Text wrap="truncate-end">{` ${refOf(item)} since ${item.claimedAt}`}</Text>
131 ))}
132 </Box>
133 )}
134 {view.escalated.length > 0 && (
135 <Box key="escalated" flexDirection="column">
136 <Text bold color="warning">
137 Escalated by the breaker
138 </Text>
139 {view.escalated.map(line => (
140 <Text>{` ${line}`}</Text>
141 ))}
142 </Box>
143 )}
144 </Box>
145 )
146}
147hooks/mods/runs.ts 140 lines1// The runs pane's logic, as pure functions. hooks/register.ts holds the hooks
2// and reads the disk; hooks/mods/panes.tsx draws the rows.
3//
4// bin/dispatch-agent.sh writes one log per run in ~/.claude-workbench/dev-team-logs:
5// <agent>-<item id>-<YYYYMMDD-HHMMSS>.log an item run
6// lestrade-sweep-<owner>-<repo>-<stamp>.log a blocker sweep ("/" written as "-")
7// beside <agent>-<id>.lock (the run's pid) and <agent>-<id>.escalated (the
8// breaker escalated the item after its last run). The pane reads the newest
9// RUN_LIMIT logs only, and each one again only when its size or mtime changed.
10// It reads them with one awk (bin/scan-run-logs.awk) over the changed files,
11// and finds the live runs with one ps. It writes nothing.
12
13export const LOG_DIR = '.claude-workbench/dev-team-logs'
14
15// The most runs the pane shows.
16export const RUN_LIMIT = 8
17
18// How often the runs pane reads the logs while it is open.
19export const RUNS_REFRESH_MS = 15_000
20
21// The view types live in the type contract, types/index.d.ts, which
22// `claude plugin validate` holds every $.state value to.
23import type { DevTeamAgent as Agent, RunRow, RunState } from '../../types'
24
25// What a run's log name says: its agent, what it ran on, when it started, and
26// the pair the lock, the marker and the dispatcher's command line name.
27export type RunLog = { name: string; agent: Agent; target: string; pair: string; startedAt: string }
28
29// The end of a log, as the breaker reads it: its last three lines that are not
30// permission refusals, and how many refusals it holds.
31export type LogEnd = { tail: string[]; refusals: number }
32
33const ITEM_LOG = /^(lestrade|holmes|watson)-([0-9]+)-([0-9]{8})-([0-9]{6})\.log$/
34const SWEEP_LOG = /^lestrade-sweep-(.+)-([0-9]{8})-([0-9]{6})\.log$/
35const MARKER = /^(lestrade|holmes|watson)-([0-9]+)\.escalated$/
36
37const stampOf = (day: string, time: string): string =>
38 `${day.slice(0, 4)}-${day.slice(4, 6)}-${day.slice(6)} ${time.slice(0, 2)}:${time.slice(2, 4)}:${time.slice(4)}`
39
40// The run a log file name records, or undefined for any other file:
41// dispatch-tick.log, a lock, a marker.
42export function runLogOf(name: string): RunLog | undefined {
43 const item = ITEM_LOG.exec(name)
44 if (item) {
45 const [, agent, id, day, time] = item as unknown as [string, Agent, string, string, string]
46 return { name, agent, target: `item ${id}`, pair: `${agent}-${id}`, startedAt: stampOf(day, time) }
47 }
48 const sweep = SWEEP_LOG.exec(name)
49 if (sweep) {
50 const [, slug, day, time] = sweep as unknown as [string, string, string, string]
51 return { name, agent: 'lestrade', target: `sweep ${slug}`, pair: `lestrade-sweep-${slug}`, startedAt: stampOf(day, time) }
52 }
53 return undefined
54}
55
56export type Entry = { name: string; kind: string; mtimeMs: number; size: number }
57export type NewestRun = RunLog & { mtimeMs: number; size: number }
58
59// The newest `limit` run logs in a listing, newest first.
60export function newestRuns(entries: readonly Entry[], limit = RUN_LIMIT): NewestRun[] {
61 const runs: NewestRun[] = []
62 for (const entry of entries) {
63 const log = entry.kind === 'file' ? runLogOf(entry.name) : undefined
64 if (log) runs.push({ ...log, mtimeMs: entry.mtimeMs, size: entry.size })
65 }
66 return runs.sort((a, b) => b.mtimeMs - a.mtimeMs || (a.name < b.name ? 1 : -1)).slice(0, limit)
67}
68
69// The pairs whose item the breaker escalated: one <agent>-<id>.escalated each.
70export function markersOf(entries: readonly Entry[]): string[] {
71 return entries.flatMap(entry => {
72 const marker = MARKER.exec(entry.name)
73 return marker ? [`${marker[1]}-${marker[2]}`] : []
74 })
75}
76
77// The pairs a live dispatcher runs, read from `ps -axo command=`. The
78// dispatcher's run is its wrapper subshell, whose command line is the
79// dispatcher's own: `bash …/dispatch-agent.sh <agent> <target>`. A `--check` or
80// `--mark-escalated` call puts its flag before the agent, so it never matches.
81export function livePairsOf(ps: string): Set<string> {
82 const live = new Set<string>()
83 for (const line of ps.split('\n')) {
84 const run = /dispatch-agent\.sh\s+(lestrade|holmes|watson)\s+(\S+)\s*$/.exec(line)
85 if (!run) continue
86 const [, agent, target] = run as unknown as [string, Agent, string]
87 if (/^[0-9]+$/.test(target)) live.add(`${agent}-${target}`)
88 else if (agent === 'lestrade' && target.includes('/')) live.add(`lestrade-sweep-${target.replaceAll('/', '-')}`)
89 }
90 return live
91}
92
93// The awk program that reads the end of the logs, shipped beside the scripts
94// so bin/test-scan-run-logs.sh runs the real thing.
95export const scanArgv = (root: string, logs: readonly string[]): string[] => ['awk', '-f', `${root}/bin/scan-run-logs.awk`, ...logs]
96
97// The awk run's output, by path. A path that printed nothing is absent.
98export function endsOf(stdout: string): Map<string, LogEnd> {
99 const ends = new Map<string, LogEnd>()
100 let current: LogEnd | undefined
101 for (const line of stdout.split('\n')) {
102 if (line.startsWith('\u001e')) {
103 const tab = line.indexOf('\t')
104 current = { tail: [], refusals: Number(line.slice(1, tab)) || 0 }
105 ends.set(line.slice(tab + 1), current)
106 } else if (current !== undefined && current.tail.length < 3) {
107 current.tail.push(line)
108 }
109 }
110 // The output's own last newline is no line of the log.
111 for (const end of ends.values()) while (end.tail.length > 0 && end.tail[end.tail.length - 1] === '') end.tail.pop()
112 return ends
113}
114
115// A run's state. Only the newest run of a pair can be the one running, or the
116// one the breaker escalated after; an older run of the pair has ended. The end
117// is read as the breaker reads it, from the last lines that are not refusals.
118export function stateOf(facts: { isNewest: boolean; isLive: boolean; isEscalated: boolean; end: LogEnd }): RunState {
119 if (facts.isNewest && facts.isLive) return 'running'
120 if (facts.isNewest && facts.isEscalated) return 'escalated'
121 const tail = facts.end.tail
122 if (tail.some(line => /content filtering policy/i.test(line))) return 'refused'
123 if (tail.some(line => line.includes('Exceeded USD budget'))) return 'budget-killed'
124 if (tail.some(line => /^(API Error|Execution error|Error:)/i.test(line))) return 'failed'
125 return 'done'
126}
127
128// The pane's rows, newest first.
129export function rowsOf(dir: string, runs: readonly NewestRun[], ends: ReadonlyMap<string, LogEnd>, live: ReadonlySet<string>, markers: readonly string[]): RunRow[] {
130 const seen = new Set<string>()
131 return runs.map(run => {
132 const isNewest = !seen.has(run.pair)
133 seen.add(run.pair)
134 const log = `${dir}/${run.name}`
135 const end = ends.get(log) ?? { tail: [], refusals: 0 }
136 const state = stateOf({ isNewest, isLive: live.has(run.pair), isEscalated: markers.includes(run.pair), end })
137 return { agent: run.agent, target: run.target, startedAt: run.startedAt, state, refusals: end.refusals, log }
138 })
139}
140hooks/mods/session-rules.ts 82 lines1// workbench-dev-team's session rules in the system prompt, as one
2// prompt.compose section.
3//
4// They used to reach a session as this plugin's session-warmup.md, which
5// workbench-core's warmup spliced into ~/.claude/CLAUDE.md, and which core's
6// prompt rules (its hooks/mods/prompt-rules.ts) then read from the installed
7// copy into its `workbench-core:plugins` section. That file is retired: the
8// rules are stated once, here, and this plugin sends them itself, so they reach
9// a session that loads the plugin with --plugin-dir as well as an installed
10// one. With no session-warmup.md at this plugin's root, core's reader finds
11// nothing to send, and the rules are not sent twice.
12//
13// The section is `shared`: the same bytes in every session, so the cache that
14// holds it is read, not created, from the second session on. It holds no date,
15// count, version, session id or path read from the machine.
16//
17// Who gets it, as core's lanes give its plugin section:
18// main the main loop of a session, interactive or `claude -p`
19// agent a top-level `claude -p --agent` run (CLAUDE_CODE_AGENT)
20// none a run with WORKBENCH_SKIP_WARMUP=1 (core's summary-writer), which
21// runs with no rules on purpose
22// A sub-agent's system prompt is its own, so it gets the rules as context at
23// SubagentStart, unless it is a fork, which inherits the parent's prompt and
24// the section with it, or its type leaves CLAUDE.md out (isRulesSubagent).
25//
26// Pure functions only: the engine follows `$` into no imported function, so the
27// hooks that read the environment live in hooks/register.ts.
28
29import type { PromptComposeSection } from 'claude-code'
30
31export const RULES_ID = 'workbench-dev-team:rules'
32
33export const RULES = `## Development workflow
34
35For code implementation, bug fixes, refactors, and tests, use the \`/workbench-dev-team:develop\` skill.
36
37## Git commits
38
39For any git commit message — manual, scripted, or agent-driven — use the \`/workbench-dev-team:git-commit\` skill. It enforces Conventional Commits + Gitmoji format with full type/emoji references. This applies universally, not just to dev-team automation.
40
41**Dev-team commits.** A sub-agent does not commit, merge, or push, and never asks to. It leaves the tree uncommitted and hands back the diff, the full \`git status\` list, and the proposed commit message. The orchestrator takes the uncommitted tree from there. Index-mode development commits and pushes unattended from the dispatcher's top-level run, and never asks about committing or pushing.
42
43## Dev-team delegation
44
45Development goes to Dr. Watson, triage to Inspector Lestrade, and review to Sherlock Holmes. Anything that ends in a changed file goes to one of them, never to a generic agent. Invoke \`/workbench-dev-team:orchestrate\` before you dispatch one, and before you act on a request to review, comment, merge, or triage on GitHub.`
46
47// Agent types that leave CLAUDE.md out, as workbench-core names them in its
48// hooks/mods/prompt-rules.ts (OMITS_CLAUDE_MD): they never saw the CLAUDE.md
49// block, and core gives them no workbench rules either.
50export const OMITS_CLAUDE_MD: ReadonlySet<string> = new Set([
51 'Explore',
52 'Plan',
53 'web-fetch',
54 'comment-thread-analyst',
55 'summary-writer',
56 'workbench-core:summary-writer',
57 'meeting-writer',
58 'workbench-core:meeting-writer',
59])
60
61// Whether a sub-agent of this type gets the rules at SubagentStart. A fork
62// (agent_type "fork") inherits its parent's whole system prompt, which already
63// holds the section, so it gets none. Nor does a type that leaves CLAUDE.md
64// out.
65export const isRulesSubagent = (agentType: string): boolean => agentType !== 'fork' && !OMITS_CLAUDE_MD.has(agentType)
66
67export const SECTION: PromptComposeSection = { id: RULES_ID, text: RULES, scope: 'shared' }
68
69// Whether a lane gets the rules, from the environment core reads for its
70// lanes. Only WORKBENCH_SKIP_WARMUP=1 says no.
71export const isRulesLane = (skipWarmup: string | undefined): boolean => skipWarmup !== '1'
72
73const PAD = /\n[ \t]*\n\s*$/
74
75export function withRules(sections: readonly PromptComposeSection[]): PromptComposeSection[] {
76 const theirs = sections.filter(section => section.id !== RULES_ID)
77 const cut = theirs.findIndex(section => section.scope === 'session')
78 const at = cut === -1 ? theirs.length : cut
79 const before = theirs.slice(0, at).map((section, i) => (i === at - 1 && PAD.test(section.text) ? { ...section, text: section.text.replace(/\s+$/, '') } : section))
80 return [...before, cut === -1 ? SECTION : { ...SECTION, text: `${RULES}\n\n` }, ...theirs.slice(at)]
81}
82hooks/mods/scratch.ts 103 lines1// Each dev-team agent's own scratch folder, as pure functions. hooks/register.ts
2// holds the hooks: tool.call points a bare mktemp at the folder, turn.complete
3// deletes the folder when the agent's run ends with no live child, and
4// session.end deletes every folder still recorded.
5//
6// A bare mktemp is one with no template and no directory option (`mktemp`,
7// `mktemp -d`, `mktemp -dq`), which lands in $TMPDIR, outside every scratch
8// root, and outlives the run. The rewrite adds a template inside the agent's
9// folder, so the folder holds every temporary file and folder the run made.
10//
11// Only a dev-team agent's line is pointed: a sub-agent of a dev-team type
12// (holmes-lens included), and the top-level loop of a `claude -p --agent` run
13// of one. The main session and every other agent keep mktemp as they wrote it.
14//
15// The rewrite is checked, never trusted. The line is read again after it, and
16// the rewrite stands only when every statement reads exactly as before, apart
17// from each bare mktemp gaining the one template word. Anything else (a mktemp
18// the text match missed, or one it found inside a quoted string or a heredoc)
19// leaves the line as it was written, which is how it ran before the mod.
20
21import type { ShellParse, Statement } from './review-guard'
22
23// mktemp's no-value options. -t, -p and --tmpdir name a directory, so a line
24// with any of them is not bare.
25const FLAGS = /^-[dqu]+$/
26
27export const isBareMktemp = (statement: Statement): boolean =>
28 statement.name === 'mktemp' &&
29 statement.nameAt === 0 &&
30 statement.wrappers.length === 0 &&
31 statement.assignments.length === 0 &&
32 statement.args.every(arg => FLAGS.test(arg))
33
34export const hasBareMktemp = (parse: ShellParse): boolean => parse.statements.some(isBareMktemp)
35
36// The template a bare mktemp gains: the folder, quoted, and mktemp's X run.
37export const templateOf = (folder: string): string => `${folder}/tmp.XXXXXXXX`
38
39// A bare mktemp in the text: the name at a command boundary, its no-value
40// options, and then the end of the command, or a `#` comment after a space.
41const BARE = /(^|[\s;&|(`])mktemp((?:[ \t]+-[dqu]+)*)(?=[ \t]*(?:$|[;&|)`\n])|[ \t]+#)/gm
42
43// A folder the rewrite can quote: an absolute path of plain characters.
44const PLAIN_PATH = /^\/[A-Za-z0-9._@+\/-]+$/
45
46// The line with every bare mktemp the text match finds pointed at `folder`, or
47// undefined when there is nothing to point or the folder cannot be quoted.
48// The caller reads the result again and keeps it only when readsAsPointed.
49export function pointMktemp(line: string, folder: string): string | undefined {
50 if (!PLAIN_PATH.test(folder)) return undefined
51 const rewritten = line.replace(BARE, (_, lead: string, flags: string) => `${lead}mktemp${flags} '${templateOf(folder)}'`)
52 return rewritten === line ? undefined : rewritten
53}
54
55// Whether the rewritten line reads exactly as the line did, apart from each
56// bare mktemp gaining the template word: the same statements, the same words,
57// redirects, heredocs and unknowns, in the same order.
58export function readsAsPointed(before: ShellParse, after: ShellParse, folder: string): boolean {
59 const template = templateOf(folder)
60 if (!hasBareMktemp(before) || JSON.stringify(after.unknowns) !== JSON.stringify(before.unknowns)) return false
61 if (after.statements.length !== before.statements.length) return false
62 const expected = before.statements.map(s => (isBareMktemp(s) ? { ...s, words: [...s.words, template], args: [...s.args, template] } : s))
63 return after.statements.every((s, i) => JSON.stringify(s) === JSON.stringify(expected[i]))
64}
65
66// The scratch root an agent's folder goes in: the first of core's roots that
67// is not ~/.claude/plans, so the session scratchpad when there is one, and
68// ~/Developer/scratchpad when there is not, as the agents' prose orders them.
69export const rootOf = (roots: readonly string[]): string | undefined => roots.find(root => !root.endsWith('/.claude/plans'))
70
71// The folder's name prefix: the agent's bare type (`watson-direct`), in plain
72// characters.
73export const prefixOf = (type: string): string => (type.split(':').pop() ?? 'agent').replace(/[^A-Za-z0-9_-]/g, '') || 'agent'
74
75// The statuses of a loop that is not over: not started, in a turn, held, or
76// between turns until a message wakes it.
77const LIVE: ReadonlySet<string> = new Set(['pending', 'running', 'waiting', 'idle'])
78
79// Whether a run still has a live child: an agent its loop spawned (for the
80// top-level `run`, one with no parent) that is not over. A child may read the
81// run's folder, as Holmes's helpers read his checkout, so the folder stays.
82export const hasLiveChild = (agents: readonly { parentId?: string; status: string }[], agentId: string | undefined): boolean =>
83 agents.some(agent => agent.parentId === agentId && LIVE.has(agent.status))
84
85// Whether `folder` may be deleted: a folder directly or deeper inside one of
86// the scratch roots, never a root itself.
87export const isDeletable = (folder: string, roots: readonly string[]): boolean =>
88 PLAIN_PATH.test(folder) && !folder.split('/').includes('..') && roots.some(root => folder.startsWith(`${root}/`) && folder.length > root.length + 1)
89
90// What leaves room for the engine's own end step out of the end's budget, and
91// the most the sweep's rm may take of it.
92const END_MARGIN_MS = 150
93const END_RM_CAP_MS = 1_000
94
95// The session end's sweep: the recorded folders one rm may delete, the ones
96// under a scratch root, and the time it may take, or undefined when there is
97// nothing to delete or too little time left. A folder left out stays recorded.
98export function sweepOf(folders: readonly string[], roots: readonly string[], remainingMs: number): { doomed: string[]; timeoutMs: number } | undefined {
99 const doomed = folders.filter(folder => isDeletable(folder, roots))
100 const timeoutMs = Math.min(remainingMs, END_RM_CAP_MS) - END_MARGIN_MS
101 return doomed.length === 0 || timeoutMs <= 0 ? undefined : { doomed, timeoutMs }
102}
103hooks/mods/spawn.ts 232 lines1import type { EngineInterface } from 'claude-code'
2
3import type { DevTeamEffort } from '../../types'
4
5// workbench-core's $.workbench contract, read off the noun itself: dev-team
6// lists core under `dependencies`, and the engine types the noun on `$`.
7type Workbench = EngineInterface['workbench']
8export type CallerLane = Awaited<ReturnType<Workbench['callerLane']>>
9
10export const PLUGIN = 'workbench-dev-team'
11
12export type Family = 'watson' | 'holmes' | 'lestrade'
13
14// The agent types a family answers to: the public type, and each mode type
15// bin/compose-agents.sh builds from it. A dispatch of any of them is routed by
16// its token, so a mode type dispatched by name still runs the mode its prompt
17// calls for.
18const FAMILIES: Readonly<Record<Family, readonly string[]>> = {
19 watson: ['watson', 'watson-direct', 'watson-index'],
20 holmes: ['holmes', 'holmes-local', 'holmes-index'],
21 lestrade: ['lestrade', 'lestrade-item', 'lestrade-sweep'],
22}
23
24export function familyOf(subagentType: string | undefined): Family | undefined {
25 if (typeof subagentType !== 'string') return undefined
26 const [plugin, name] = subagentType.split(':')
27 if (plugin !== PLUGIN || name === undefined) return undefined
28 return (Object.keys(FAMILIES) as Family[]).find(family => FAMILIES[family].includes(name))
29}
30
31// The tokens. A token picks a mode only when it is the whole prompt: one
32// non-blank line, and that line the token, which is how workbench-core's
33// briefCheck reads the `item-id` and `repo-sweep` shapes. A brief that only
34// mentions `Item ID: 9`, in its Context or anywhere else, is a brief, so it
35// runs the off-board mode and the agent's own rule that a mention is not a
36// dispatch token still applies. Watson and Holmes take `Item ID: <n>` or one
37// bare id (a plain integer, a UUID, or a PVTI_ id) for The Index mode. Lestrade
38// takes `Item ID: <n>` or a bare integer for Item mode, and
39// `Repo sweep: <owner/repo>` for Sweep mode. Whitespace is the five ASCII
40// characters core's check uses, so an exotic space makes a line no token.
41const SPACE = '[ \\t\\r\\v\\f]*'
42const ITEM_ID = new RegExp(`^${SPACE}Item ID:${SPACE}[0-9]+${SPACE}$`)
43const BARE_INTEGER = new RegExp(`^${SPACE}[0-9]+${SPACE}$`)
44const BARE_ID = new RegExp(
45 `^${SPACE}(?:[0-9]+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|PVTI_[A-Za-z0-9_-]+)${SPACE}$`,
46)
47const REPO_SWEEP = new RegExp(`^${SPACE}Repo sweep:${SPACE}[^ \\t\\r\\v\\f/]+/[^ \\t\\r\\v\\f/]+${SPACE}$`)
48const NONBLANK = /[^ \t\r\v\f\n]/
49
50// Whether the whole prompt is one token: a single non-blank line it matches.
51function isWhole(prompt: string, ...tokens: RegExp[]): boolean {
52 const lines = prompt.split('\n').filter(line => NONBLANK.test(line))
53 return lines.length === 1 && tokens.some(token => token.test(lines[0] ?? ''))
54}
55
56// The item id of a prompt that is the whole token `Item ID: <n>`, or undefined.
57export function itemIdOf(prompt: string): string | undefined {
58 if (!isWhole(prompt, ITEM_ID)) return undefined
59 return /[0-9]+/.exec(prompt.split('\n').find(line => NONBLANK.test(line)) ?? '')?.[0]
60}
61
62// The mode agent a dispatch runs, as a full type. Anything but a whole-prompt
63// token is Direct mode for Watson and Local mode for Holmes, as their files
64// say. Lestrade has no prose mode, so a prompt that is no token stays on the
65// public type, which decides for itself.
66export function modeTypeOf(family: Family, prompt: string): string {
67 switch (family) {
68 case 'watson':
69 return `${PLUGIN}:${isWhole(prompt, ITEM_ID, BARE_ID) ? 'watson-index' : 'watson-direct'}`
70 case 'holmes':
71 return `${PLUGIN}:${isWhole(prompt, ITEM_ID, BARE_ID) ? 'holmes-index' : 'holmes-local'}`
72 case 'lestrade':
73 if (isWhole(prompt, ITEM_ID, BARE_INTEGER)) return `${PLUGIN}:lestrade-item`
74 if (isWhole(prompt, REPO_SWEEP)) return `${PLUGIN}:lestrade-sweep`
75 return `${PLUGIN}:lestrade`
76 }
77}
78
79// What the /config rows give one family's interactive dispatch, read through
80// configTextOf. The values are the person's, so each is checked before it is
81// used: a model is an alias or a full id with an optional bracketed suffix
82// (`claude-opus-5-5[1m]`), and an effort is a level. turn.step refuses a
83// numeric effort from a hook ("a number is internal-only"), so a number is not
84// one. A value outside that shape, and a missing one, leave the knob unset, so
85// the agent file's own value applies. A bad value never blocks a dispatch, as
86// on the scheduled path.
87export type Knobs = { model?: string; effort?: DevTeamEffort }
88
89const MODEL = /^[A-Za-z0-9][A-Za-z0-9._-]*(?:\[[A-Za-z0-9]+\])?$/
90const LEVELS: readonly string[] = ['low', 'medium', 'high', 'xhigh', 'max']
91
92export function knobsOf(configText: string | undefined, family: Family): Knobs {
93 if (configText === undefined) return {}
94 let config: unknown
95 try {
96 config = JSON.parse(configText)
97 } catch {
98 return {}
99 }
100 const entry = (config as { agents?: Record<string, unknown> } | null)?.agents?.[family]
101 if (entry === null || typeof entry !== 'object') return {}
102 const { model, effort } = entry as { model?: unknown; effort?: unknown }
103 const knobs: Knobs = {}
104 if (typeof model === 'string' && MODEL.test(model)) knobs.model = model
105 if (typeof effort === 'string' && LEVELS.includes(effort.toLowerCase())) knobs.effort = effort.toLowerCase() as DevTeamEffort
106 return knobs
107}
108
109// The knobs the review agents read at run time: whether Holmes and Lestrade
110// fan out to helpers, and the model the helpers run on. The mod adds them to
111// the prompt of the three modes that read them, so no agent reads the file:
112// at spawn for an interactive dispatch, and on prompt.submit for the top-level
113// run bin/dispatch-agent.sh starts, which raises no agent.spawn.
114export const CONFIG_MODES: Readonly<Record<string, Family>> = {
115 [`${PLUGIN}:holmes-local`]: 'holmes',
116 [`${PLUGIN}:holmes-index`]: 'holmes',
117 [`${PLUGIN}:lestrade-item`]: 'lestrade',
118}
119
120// The plugin's /config rows, as the config text knobsOf and configLineOf read:
121// one entry per agent, keyed as the old config file keyed it, so
122// `watsonModel` is `agents.watson.model`. A row with no value is left out.
123const ROW_KNOBS = ['model', 'effort', 'fanout', 'lensModel'] as const
124export function configTextOf(options: Readonly<Record<string, unknown>> | undefined): string {
125 const entry = (family: Family) =>
126 Object.fromEntries(
127 ROW_KNOBS.map(knob => [knob, options?.[`${family}${knob.charAt(0).toUpperCase()}${knob.slice(1)}`]] as const).filter(([, value]) => value !== undefined),
128 )
129 return JSON.stringify({ agents: Object.fromEntries((Object.keys(FAMILIES) as Family[]).map(family => [family, entry(family)])) })
130}
131
132// The line's label, which the agents' prose names.
133export const CONFIG_LABEL = 'Dev-team config:'
134
135// The line the mod adds for one family, from the config's text. Only a
136// `false` turns the fan-out off, so a missing or malformed value leaves it on,
137// as the agents' default is. A lensModel outside the model shape is unset, and
138// the helpers then run on the agent's own model.
139export function configLineOf(configText: string | undefined, family: Family): string {
140 let entry: unknown
141 try {
142 entry = (JSON.parse(configText ?? '') as { agents?: Record<string, unknown> } | null)?.agents?.[family]
143 } catch {
144 entry = undefined
145 }
146 const { fanout, lensModel } = entry !== null && typeof entry === 'object' ? (entry as { fanout?: unknown; lensModel?: unknown }) : {}
147 const model = typeof lensModel === 'string' && MODEL.test(lensModel) ? lensModel : undefined
148 return `${CONFIG_LABEL} fanout ${fanout === false ? 'off' : 'on'}; lensModel ${model ?? 'unset'}.`
149}
150
151// The prompt with the config line added once, after a blank line.
152export const withConfigLine = (prompt: string, line: string): string =>
153 prompt.includes(CONFIG_LABEL) ? prompt : `${prompt.replace(/\s+$/, '')}\n\n${line}`
154
155// ── Holmes's helpers run on holmes-lens ──────────────────────────────────────
156
157export const LENS_TYPE = `${PLUGIN}:holmes-lens`
158
159// Holmes in any mode: the public type and its two mode types, by full or bare
160// name. Not holmes-lens, which holds no Agent tool.
161const HOLMES_MODE = /(^|[:/])holmes(-local|-index)?$/iu
162export const isHolmesMode = (type: string | undefined): boolean => type !== undefined && HOLMES_MODE.test(type.trim())
163
164// The type a Holmes spawn runs as: holmes-lens, whatever the call named, or a
165// refusal for a fork or a teammate, which cannot be retyped.
166export function lensSpawnOf(e: { subagentType: string; fork: boolean; isTeammate?: true }): { subagentType: string } | { deny: string } {
167 if (e.subagentType === LENS_TYPE) return { subagentType: LENS_TYPE }
168 if (e.fork || e.isTeammate) return { deny: lensDeny(e.fork ? 'a fork' : 'a teammate') }
169 return { subagentType: LENS_TYPE }
170}
171
172export function lensDeny(what: string): string {
173 return [
174 `🛑 Blocked: Holmes spawned ${what}.`,
175 '',
176 `Helper rule (${PLUGIN}). Every helper Holmes spawns runs on ${LENS_TYPE}, the read-only helper, and ${what} cannot be retyped to it. ` +
177 `Dispatch the helper with subagent_type "${LENS_TYPE}".`,
178 ].join('\n')
179}
180
181// Whether a type is one of the dev-team's agents, the helper included: the
182// types the mod gives a scratch folder and a context budget.
183export const isDevTeamType = (type: string | undefined): boolean => type !== undefined && (familyOf(type) !== undefined || type === LENS_TYPE)
184
185// ── The default-branch check ─────────────────────────────────────────────────
186
187export const DEFAULT_BRANCHES: readonly string[] = ['main', 'master', 'trunk']
188
189// A brief's Workdir: the path, and whether the slot records a workspace
190// decision. The path runs to the first " (", and the slot records a decision
191// when the text after the path names a branch or a worktree, as
192// `/repo (branch: main, Mike chose main)` does. Undefined when the brief has
193// no Workdir line.
194export function workdirOf(prompt: string): { path: string; isRecorded: boolean } | undefined {
195 const line = prompt.split('\n').find(l => /^[ \t]*Workdir:/.test(l))
196 if (line === undefined) return undefined
197 const value = line.replace(/^[ \t]*Workdir:/, '').trim()
198 const cut = value.indexOf(' (')
199 const path = (cut === -1 ? value : value.slice(0, cut)).trim()
200 return { path, isRecorded: /\b(branch|worktree)\b/i.test(value.slice(path.length)) }
201}
202
203export function branchDeny(path: string, branch: string): string {
204 return [
205 `🛑 Blocked: a Watson Direct-mode dispatch onto ${branch}, with no branch recorded in Workdir:.`,
206 '',
207 `Workspace check (${PLUGIN}). The repo at ${path} is on its default branch, ${branch}, and the brief's Workdir: names only the path. ` +
208 'Ask the human which branch the work goes on, through AskUserQuestion, and propose a branch name. ' +
209 `Then record the answer beside the path, for example "Workdir: ${path} (branch: fix/short-name)", or "(branch: ${branch}, <who> chose to work on ${branch})" when the human picks ${branch}, and dispatch again.`,
210 ].join('\n')
211}
212
213export function branchUnreadDeny(path: string): string {
214 return [
215 '🛑 Blocked: a Watson Direct-mode dispatch whose branch could not be read.',
216 '',
217 `Workspace check (${PLUGIN}). git did not answer for ${path}, so the check cannot tell whether the repo is on its default branch. ` +
218 'Ask the human which branch the work goes on, record it beside the path in Workdir:, for example "(branch: fix/short-name)", and dispatch again.',
219 ].join('\n')
220}
221
222export const isGated = (lane: CallerLane, isOn: boolean): boolean => lane === 'main' && isOn
223
224export function spawnFailedDeny(): string {
225 return [
226 '🛑 Blocked: an Agent dispatch the dev-team spawn rules could not judge.',
227 '',
228 `Spawn rules (${PLUGIN}). The helper rule or the workspace check failed while reading this dispatch, so it is refused rather than let through unjudged. ` +
229 'Dispatch again. If it keeps failing, report it to the human as a defect in workbench-dev-team.',
230 ].join('\n')
231}
232types/index.d.ts 80 lines1// The type contract of workbench-dev-team's hooks module: the values it keeps
2// in $.state for the session, each one per agent. `claude plugin validate` holds every $.state key
3// the module names to this file.
4//
5// The module adds no noun to $. It builds on workbench-core's $.workbench, which
6// the engine types on $ because .claude-plugin/plugin.json lists workbench-core
7// under "dependencies".
8
9// ── The runs pane (hooks/mods/runs.ts) ──────────────────────────────────────
10
11export type DevTeamAgent = 'lestrade' | 'holmes' | 'watson'
12
13// running the dispatcher's process for the run is alive
14// done the run ended with no error line
15// failed the run ended on an API, execution or other error line
16// refused the API refused the run's output (the content filter)
17// budget-killed the run hit its USD budget cap
18// escalated the breaker escalated the item after this run, its last
19export type RunState = 'running' | 'done' | 'failed' | 'refused' | 'budget-killed' | 'escalated'
20
21// One run. `target` is "item <id>" or "sweep <owner>-<repo>", `startedAt` the
22// stamp in its log's name, and `refusals` the log's "Permission denied:"
23// lines, one per tool call a rule, hook or prompt refused.
24export type RunRow = { agent: DevTeamAgent; target: string; startedAt: string; state: RunState; refusals: number; log: string }
25
26// What the runs pane draws: the rows, newest first, or why there are none.
27export type RunsView = { rows: RunRow[]; error?: string }
28
29// ── The board pane (hooks/mods/board.ts) ────────────────────────────────────
30
31export type BoardItem = { id: number; number: number | null; isPr: boolean; repo: string | null; title: string | null; claimedAt: string | null }
32
33// A lane: its items, at most `limit` of them, or the list tool's own error.
34export type BoardLane = { limit: number; items: BoardItem[] } | { error: string }
35
36export type Board = { unrefined: BoardLane; review: BoardLane; development: BoardLane }
37
38// What the board pane draws:
39// attemptedAt when the last fetch started (0: never); the cadence counts from it
40// board the last board fetched, and boardAt, when that fetch started
41// error why the last fetch failed, when it did
42// escalated the items the breaker escalated, read from the log folder
43export type BoardView = { attemptedAt: number; board?: Board; boardAt?: number; error?: string; escalated: string[] }
44
45// An effort the config may give an agent: a level, as a hook may set a model
46// request's `effort`.
47export type DevTeamEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
48
49declare module 'claude-code' {
50 interface PluginState {
51 'workbench-dev-team': {
52 // The effort each dev-team sub-agent runs at, keyed by its agentId: set
53 // when agent.spawn starts it, read by every turn.step of its loop.
54 effort: StateFamily<DevTeamEffort>
55 // The type each dev-team sub-agent runs as, holmes-lens included, keyed
56 // by its agentId: set when agent.spawn starts it. The scratch folder, the
57 // context budget and the holmes-lens rule read it.
58 agentType: StateFamily<string>
59 // Each dev-team agent's scratch folder, keyed by its agentId, or `run`
60 // for the top-level loop of a `claude -p --agent` run: made at its first
61 // bare mktemp, deleted and set to "" when its run completes.
62 scratch: StateFamily<string>
63 // Every scratch folder the mod made and has not deleted yet. A family
64 // cannot be listed, so session.end reads this to delete what each run's
65 // end left behind for a child that was still live.
66 scratchFolders: string[]
67 // Whether the human was told this run passed its context budget, keyed
68 // as scratch is, so the notice comes once per run.
69 overBudget: StateFamily<boolean>
70 backgroundTasks: StateFamily<{ id: string; output?: string }[]>
71 // What the runs pane draws: the newest dispatched runs, read from the
72 // dispatch logs while the pane is open.
73 runs: RunsView
74 // What the board pane draws: The Index's three lanes as last fetched,
75 // when the last fetch started, and the items the breaker escalated.
76 board: BoardView
77 }
78 }
79}
80