| 1 | # Fleet and sub-agents |
| 2 | |
| 3 | > 阅读简体中文版:[zh_hans/SUBAGENTS.md](zh_hans/SUBAGENTS.md) |
| 4 | |
| 5 | Fleet manages saved models and role assignments for these same sub-agents. |
| 6 | Use `agent` for an individual assignment and `workflow` for phases with |
| 7 | dependencies and completion checks. See [Workflow authoring](WORKFLOW_AUTHORING.md) |
| 8 | for plans that use the Fleet model shortlist. |
| 9 | |
| 10 | Fleet roles are the user-facing vocabulary for delegated work: a parent |
| 11 | launches a focused `general`, `explore`, `planner`, `reviewer`, `implement`, |
| 12 | `test`, or `advisor` through `agent` and gets back an `agent_id`, declared |
| 13 | deliverables, and effective limits while the worker runs. The default receipt is |
| 14 | compact; request addressed detail when you need the transcript handle or ledger. |
| 15 | The internal runtime type is `FleetRole` (formerly |
| 16 | `SubAgentType`); the older role spellings (`worker`, `scout`, `plan`, |
| 17 | `review`, `builder`, `verifier`, `consultant`, `oracle`, …) remain accepted only as a persisted/deserialize |
| 18 | compatibility adapter. New prompts and config should use fleet |
| 19 | names. |
| 20 | |
| 21 | Child assignments run through the same `Engine::run_turn` planner, executor, |
| 22 | Session and approval inbox as ordinary turns. The private captured ChildGrant |
| 23 | narrows tool actions, shell, workspace, network and descendant depth at the final |
| 24 | execution boundary. The existing SubAgentManager still owns launch slots, |
| 25 | coordination, worker checkpoints and terminal delivery; it does not run another |
| 26 | model/tool loop. Work uses the full explicit owner limit. At the limit the host |
| 27 | preserves a partial-result receipt without an extra model reporting request. |
| 28 | |
| 29 | Transient provider failures use Core's dispatch and retry boundaries. An interrupted |
| 30 | worker can resume from a continuable checkpoint using `agent` follow-up. An |
| 31 | exhausted budget ends the worker; its saved transcript can still seed a new |
| 32 | worker through `start` with `resume_from`. The receipt labels clipped assistant text and |
| 33 | reports how many characters it shows. Use addressed `agent` status with |
| 34 | `detail: true` and `handle_read` on the returned `transcript_handle` to |
| 35 | inspect the retained record. Each actually dispatched attempt carries its original |
| 36 | session, route and source identity: provider usage is billed once, then projected |
| 37 | to the worker ledger. A successful response without usage and an unknown request outcome retain |
| 38 | distinct coverage gaps; neither is priced as zero. For work that must survive |
| 39 | process restarts, sleep or remote execution, use Fleet or a Workflow-backed run. |
| 40 | |
| 41 | Sub-agents inherit the parent's permitted tool registry, including `agent` |
| 42 | coordination. Spawning obeys one absolute depth ceiling: the root is depth 0, |
| 43 | its child is depth 1, and a child at `max_spawn_depth` cannot spawn again. |
| 44 | The default maximum delegation depth is 3 (`[subagents] max_depth`). Explicit operator, role and saved-profile |
| 45 | limits may raise or lower descendant authority (`0` disables child delegation); model requests cannot choose caps. Recovery and transcript |
| 46 | forking retain the source's position and bounds; they do not buy another |
| 47 | generation. The removed `agent_open`/`agent_eval`/`agent_close` lifecycle tools |
| 48 | are absent from every registry. |
| 49 | |
| 50 | Healthy children continue after an ordinary parent response. Their completion |
| 51 | returns through the existing Engine inbox and can wake the parent for another |
| 52 | normal turn. Explicit interruption or cancellation remains authoritative. |
| 53 | `detached: true` additionally opts a subtree out of parent-turn cancellation; |
| 54 | it does not remove child budgets or the headless host's deadline. |
| 55 | |
| 56 | This doc covers roles and individual worker controls. Use `workflow` to coordinate |
| 57 | multiple assignments through the same worker runtime; see the per-role prompts in |
| 58 | `crates/engine/src/tools/subagent/mod.rs` (`*_AGENT_INTRO`) and the in-line |
| 59 | tool description. |
| 60 | |
| 61 | ## Role taxonomy |
| 62 | |
| 63 | The `type` field on `agent` selects a fleet posture for the child |
| 64 | (`agent_type` is accepted as a compatibility alias). Each role is a distinct |
| 65 | stance toward the work — not just a different label. |
| 66 | |
| 67 | ## Maintainer posture |
| 68 | |
| 69 | Sub-agents help Codewhale move faster, but the parent agent still owns the |
| 70 | maintainer decision. Use children to gather evidence, review patches, and run |
| 71 | verification while keeping the community posture in |
| 72 | [`AGENT_ETHOS.md`](AGENT_ETHOS.md): issues are open intake, and contributed |
| 73 | work needs clear credit. |
| 74 | |
| 75 | When a child reviews community work, the parent should still inspect the |
| 76 | diff, linked issues, tests, and CI before landing, closing, or deferring the |
| 77 | contribution. A sub-agent's result is a working set, not a substitute for |
| 78 | stewardship. |
| 79 | |
| 80 | | Role | Stance | Writes? | Network? | Shell posture | Typical use | |
| 81 | |---------------|----------------------------------------|---------|----------|---------------|----------------------------------------------| |
| 82 | | `general` | flexible; do whatever the parent says | yes | yes | yes | the default; multi-step tasks | |
| 83 | | `explore` | read-only; map the relevant code fast | no | yes | bounded inspection | "find every call site of `Foo`; check the PR with gh" | |
| 84 | | `planner` | analyse and produce a strategy | no | yes | read-only probes | "design the migration; don't execute" | |
| 85 | | `reviewer` | read-and-grade with severity scores | no | yes | bounded inspection | "audit this PR for bugs" | |
| 86 | | `implement` | land a specific change with min edit | yes | yes | yes | "rewrite `bar.rs::Foo::bar` to do X" | |
| 87 | | `test` | run tests / validation, report outcome | no | yes | bounded verification (no writes) | "verify the diff with the bounded test checks; report PASS/FAIL" | |
| 88 | | `advisor` | short-lived, high-reasoning counsel | no | yes | none | "what are we missing in this design?" | |
| 89 | | `custom` | explicit narrow tool allowlist | inherits | inherits | inherits | hand-picked tools on the parent's posture | |
| 90 | |
| 91 | A role's default is what the role *intends*, and the parent's effective |
| 92 | posture is always the ceiling (a child never widens beyond its parent). |
| 93 | Read-only roles withhold **workspace writes** by intent; nothing else is |
| 94 | taken away by default — every role keeps network reads, and `custom` |
| 95 | inherits the parent's write/network/shell posture and is narrowed only by |
| 96 | its explicit tool list or the spawning call. The focused worker's header |
| 97 | states the effective posture (`scout · read-only · network · read-only |
| 98 | shell`) from the runtime's own permission snapshot. |
| 99 | |
| 100 | **Delegation moves work, never authority.** A read-only parent may delegate |
| 101 | to `implement`, but the child's effective write, network, shell, and tool |
| 102 | permissions remain within the parent's live posture. Inspection roles can use |
| 103 | the classified read-only shell surface and, where native enforcement is |
| 104 | available, the explicit read-only analysis mode described below. A different |
| 105 | role name or `read_only` flag cannot grant a shell tool the caller lacks. |
| 106 | The clamp (`ChildAuthority::clamp` in `fleet/exact.rs`) intersects every field |
| 107 | with the narrower side. Deny lists are unioned, so |
| 108 | `inherit_disallowed_tools: false` cannot drop any operator or ancestor denial. |
| 109 | Resuming a saved worker intersects its saved posture with the current caller's |
| 110 | posture again. This containment is pinned by |
| 111 | `a_read_only_parents_delegation_never_widens_authority` in |
| 112 | `crates/engine/src/fleet/exact.rs` tests. |
| 113 | |
| 114 | Inside the process, the resolved authority is one object — |
| 115 | `ChildGrant` in `crates/agent-contract/src/worker_profile.rs`: `files` |
| 116 | (none/read/write), `shell` (none/inspect/verify/full), `network`, `desktop` |
| 117 | (never granted to a child), the named tool `surface`, the caller's explicit |
| 118 | `scope`, and remaining `spawn` depth. A role is a preset over that object |
| 119 | (`ChildGrant::for_role`); `ChildGrant::resolve` intersects it with the |
| 120 | parent-derived profile. The child's tool catalog, its dispatch refusals, and |
| 121 | its capability envelope all read the same fields — a tool that is visible is |
| 122 | callable, and a tool that is denied never appears. |
| 123 | |
| 124 | The session's **permission posture** applies inside every child exactly as |
| 125 | it applies to the parent turn: under Auto-Review the same deterministic |
| 126 | floor and one-shot model guardian decide a worker's held calls (never a |
| 127 | prompt; an unavailable guardian denies, fail closed), and on return a child |
| 128 | that ran tool calls has its calls-only action list reviewed once against the |
| 129 | root owner's requests — prepending a sanitized `[Auto-Review warning: ...]` |
| 130 | notice to the returned report on a concern or unavailable check and surfacing |
| 131 | child blocks (without retry grants) in the parent's blocked-actions list; under Ask a held call |
| 132 | the role cannot delegate is raised as an approval prompt in the parent's |
| 133 | UI and the worker waits visibly (`waiting for user`), or is denied with the |
| 134 | reason on hosts that cannot prompt; Full Access applies |
| 135 | exactly as it does to the parent turn, so a call the person granted is not |
| 136 | stranded by the Auto-Review floor. Each decision nobody was prompted for is a |
| 137 | one-line note in that worker's transcript (visible when it is focused) and |
| 138 | an audit-log record. See `docs/MODES.md`. |
| 139 | |
| 140 | Each role's full system prompt lives in |
| 141 | `crates/engine/src/tools/subagent/mod.rs` (search for |
| 142 | `*_AGENT_INTRO`). The prompt prefix loads automatically when the |
| 143 | child agent boots; the parent's assignment prompt becomes the first |
| 144 | turn's user message. |
| 145 | |
| 146 | ## Context forking |
| 147 | |
| 148 | `agent` starts fresh by default: the child gets its role prompt plus the |
| 149 | task you pass. Use `fork_context: true` when the child should continue from |
| 150 | the parent's current request prefix instead. (`fork_context` is not in the |
| 151 | advertised schema — it stays parse-accepted for compat callers, and |
| 152 | auto-forking for read-only roles continues unchanged.) In fork mode the runtime keeps the |
| 153 | parent prefill/prompt prefix byte-identical where available, appends a |
| 154 | structured state snapshot, then adds the sub-agent role instructions and task |
| 155 | at the tail. That preserves DeepSeek prefix-cache reuse while giving the child |
| 156 | the context needed for continuation, review, summarization, or compaction work. |
| 157 | |
| 158 | Use fresh sessions for independent exploration. Use forked sessions when the |
| 159 | task depends on decisions, files, todos, or plan state already in the parent |
| 160 | transcript. |
| 161 | |
| 162 | Forked state shows the parent's To-do snapshot — the sole Work surface, written |
| 163 | by `todo_write`. The child's `<codewhale:fork_state>` block carries the bounded |
| 164 | body rendered by `crates/engine/src/todo_snapshot.rs`, so a fork continues from the |
| 165 | parent's real progress position rather than a paraphrase. That To-do section is |
| 166 | resolved when the spawn happens, so a `todo_write` earlier in the same parent |
| 167 | turn is included. |
| 168 | |
| 169 | **The list is shown once, at that spawn, and never re-sent.** No sub-agent |
| 170 | request re-states a To-do list, and neither does a parent request. Each agent |
| 171 | keeps its own private list (#4810); what it knows about that list comes from its |
| 172 | own `todo_write` calls (each sends the whole list) and the short receipts they |
| 173 | returned, which are ordinary messages in its own transcript. A worker therefore cannot read or write a parent's or a |
| 174 | sibling's list, and a forked child cannot mutate the snapshot it was handed or |
| 175 | keep reading later parent changes. |
| 176 | |
| 177 | That same private list is what the child's in-transcript card shows. A |
| 178 | delegate card renders a bounded projection of **its own** agent's To-do — the |
| 179 | settled/total count, the in-progress item always included, up to three rows, and an |
| 180 | explicit `… +N more` when the bound elides the rest — built by |
| 181 | `card_todo_projection` from the same snapshot, priority order, and sanitizer the |
| 182 | model-facing body uses. A card only ever consumes an envelope whose `agent_id` |
| 183 | matches it, so a parent's list never appears under a child and no sibling's list |
| 184 | appears under another. An agent that has stated no work shows no To-do rows at |
| 185 | all rather than a placeholder task, and a terminal card keeps the last snapshot |
| 186 | its agent actually published. Fanout cards stay a dot grid and do not show child |
| 187 | To-do: with many workers behind one card there is no truthful place to hang a |
| 188 | single list. A child To-do appears only when the runtime already represents |
| 189 | that child as its own delegate card. |
| 190 | |
| 191 | The durable Runtime ledger (projected through fleet task status) still owns |
| 192 | lifecycle state. `update_plan` is no longer registered. Strategy that used to |
| 193 | go there now goes in the response body, and lifecycle state goes in |
| 194 | `todo_write`. |
| 195 | |
| 196 | ## Worktree isolation |
| 197 | |
| 198 | For parallel edit lanes, launch the child with `worktree: true`. Codewhale |
| 199 | creates a fresh git worktree and branch for that child, runs the child from the |
| 200 | isolated checkout, and reports the resulting workspace/branch in the returned |
| 201 | session projection and worker record. By default the branch is |
| 202 | `codex/agent-<name>-<id>` and the checkout lives beside the parent repo under |
| 203 | `.codewhale-worktrees/`, so the parent checkout stays clean. |
| 204 | |
| 205 | Isolation is not write authority. A prompt-only start with no role/profile or |
| 206 | write declaration remains read-only, and read-only roles need no write scope. |
| 207 | Explicitly selected write-capable roles such as `general` and `implement` |
| 208 | inherit the parent's write ceiling and default to the workspace |
| 209 | (`write_roots: ["."]`) unless narrowed. Prefer explicit, disjoint `exact_files` |
| 210 | or `write_roots` for parallel work; `coordination_contracts` can reserve named |
| 211 | shared contracts. If only `deliverables` supplies a writer's scope, those files |
| 212 | become the exact-file scope. |
| 213 | |
| 214 | `write_authority` is optional typed narrowing: `read_only` admits no write |
| 215 | scope, `workspace_write` uses the shared checkout, and `worktree_write` |
| 216 | requires actual worktree isolation. Incompatible role/scope declarations fail |
| 217 | before admission. Active overlapping shared claims fail before mutation; a |
| 218 | real isolated worktree may proceed in parallel. A `custom` role requires |
| 219 | explicit write-capable authority to claim writes; otherwise it starts |
| 220 | read-only. |
| 221 | |
| 222 | A read-only role (`explore`, `planner`, `reviewer`, `test`, `advisor`) that is |
| 223 | given `deliverables`, `write_roots`, `exact_files` or `coordination_contracts` |
| 224 | is refused at start, before any model call, with the roles and saved profiles |
| 225 | on the current roster that can write. The child is never started only to |
| 226 | discover it cannot do the job. |
| 227 | |
| 228 | Every write-capable child (`general`, `implement`, `custom`) is told how to |
| 229 | work in a checkout: use its own worktree (the isolated one it was given, or |
| 230 | ask the parent for `worktree=true` when others may write the same checkout), |
| 231 | one agent per worktree, base new work on current upstream main, never switch, |
| 232 | reset, stash or clean a shared checkout, commit coherent slices in its own |
| 233 | worktree and report branch and SHA, and leave pushing, merging and cleanup to |
| 234 | the parent unless the brief assigns them. |
| 235 | |
| 236 | Read-only is not file-only. A normally write-capable agent narrowed with |
| 237 | `write_authority: "read_only"` keeps the existing classifier-bounded inspection |
| 238 | shell when its parent permits it: Git history/status, search, and allowed `gh` |
| 239 | log reads, not arbitrary commands or test programs (with permission `deny` |
| 240 | rules configured, dynamic shell forms such as loops, command substitutions, and |
| 241 | globs are refused). Workflow read-only steps |
| 242 | likewise use the effective role's tools instead of imposing a second File-only |
| 243 | list; a `test` role retains its bounded verification interface. Explicit tool |
| 244 | allowlists, `deny_all_tools`, parent denials, network limits, and mutation checks |
| 245 | still apply. A parent without shell access cannot delegate it. |
| 246 | |
| 247 | Optional fields: |
| 248 | |
| 249 | - `worktree_branch`: exact branch to create. |
| 250 | - `worktree_base`: git ref to branch from; defaults to `HEAD`. |
| 251 | - `worktree_path`: exact checkout path. Relative and absolute paths must stay |
| 252 | under the default sibling `.codewhale-worktrees/<repo>/` root, and a link |
| 253 | anywhere on the way down to the checkout, including at the root itself, is |
| 254 | refused. Any worktree request keeps the approval card, even for a read-only |
| 255 | role, and that includes `workspace_policy: "worktree"`. |
| 256 | |
| 257 | `cwd` may be combined with `worktree`: the requested directory becomes the |
| 258 | discovery anchor the repo root (and the new checkout) is resolved from |
| 259 | (`prepare_child_workspace`). Without `worktree`, `cwd` remains the manual |
| 260 | escape hatch for an already-created directory inside the parent workspace. |
| 261 | |
| 262 | ### File deliverables and edit claims |
| 263 | |
| 264 | Put required files in `deliverables`; keep the human outcome in |
| 265 | `expected_artifact`. For example, call `agent` with: |
| 266 | |
| 267 | ```json |
| 268 | { |
| 269 | "action": "start", |
| 270 | "type": "implement", |
| 271 | "prompt": "Summarize the local routing evidence in reports/routing.md.", |
| 272 | "exact_files": ["reports/routing.md"], |
| 273 | "deliverables": ["reports/routing.md"], |
| 274 | "expected_artifact": "A concise report with source references and open gaps" |
| 275 | } |
| 276 | ``` |
| 277 | |
| 278 | At most 16 repo-relative file paths are accepted. Absolute paths, traversal, |
| 279 | repository metadata paths, and symlink traversal are refused. Completion checks |
| 280 | each file against the admitted scope and reports its path, status, and byte |
| 281 | count where available. The terminal statuses are `present`, `missing`, `empty`, |
| 282 | `not_file`, `out_of_scope`, `invalid_path`, and `unreadable`. |
| 283 | `present` means a nonempty regular file exists; it does not prove the report is |
| 284 | correct or that tests passed. |
| 285 | |
| 286 | A missing or invalid required file sets `verification.status` to |
| 287 | `deliverable_missing` with the individual verdicts. Successful file checks can |
| 288 | produce `deliverables_present`; they do not turn a child self-report into an |
| 289 | independent quality gate. The completion notice includes the actual verdicts, |
| 290 | including when a worker fails or exhausts a budget. |
| 291 | |
| 292 | Edit claims are checked separately against the spawn-time git HEAD and dirty |
| 293 | file contents. Explicit changed-file declarations can produce |
| 294 | `claim_mismatch` when a claimed file did not change, or when a successful |
| 295 | bounded write receipt changed a file the child did not declare. A peer's |
| 296 | change inside a worker's broad scope is not enough to attribute that write to |
| 297 | the worker. `path:LINE` and `path:LINE-LINE` evidence citations, including |
| 298 | sentence punctuation and Markdown links, never count as edit claims. |
| 299 | |
| 300 | ### Read-only shell commands |
| 301 | |
| 302 | Scout, reviewer and planner agents, agents narrowed with |
| 303 | `write_authority: "read_only"`, and durable Fleet workers with a read-only |
| 304 | shell grant all judge `bash` calls by the same read-only grammar: |
| 305 | |
| 306 | - inspection programs: `ls`, `pwd`, `cat`, `head`, `tail`, `wc`, `which`, |
| 307 | `stat`, `file`, `du`, `df`, `grep`, `rg`, `fd`, `find` without `-exec` or |
| 308 | `-delete`, and `sed -n <range>p`; |
| 309 | - `git status`, `log`, `diff`, `show`, `ls-files`, `blame` and `grep`, |
| 310 | optionally after `-C <dir>` or `--no-pager`; |
| 311 | - the text filters `sort`, `uniq`, `cut`, `tr` and `comm`, and literal |
| 312 | `echo`/`printf`; |
| 313 | - with a network grant, `gh` issue/pr/release/repo/run/workflow view or list |
| 314 | reads. |
| 315 | |
| 316 | `npm view` is refused even with a network grant: npm configuration can select |
| 317 | executable helpers, so package metadata reads are outside this bounded grammar. |
| 318 | |
| 319 | Admitted commands can be joined with `|`, `&&`, `||` and `;`, for example |
| 320 | `git diff HEAD && echo '=== FILES ===' && ls -la`. A leading `cd <dir> &&` |
| 321 | sets the working directory, and that directory must be inside the workspace. |
| 322 | The only redirects are `2>/dev/null`, `>/dev/null` and `2>&1`. Quoted text is |
| 323 | data, so `rg 'a && b' src` is one search. Other redirects, `$` or backtick |
| 324 | expansion, subshells, backgrounding, inline environment assignments, and any |
| 325 | other program (such as `python`, `awk`, `jq` or `cargo`) are refused. Options |
| 326 | and path operands are still checked, and each `gh` or `npm` read needs the |
| 327 | network grant wherever it appears in the command. |
| 328 | |
| 329 | A refused command comes back to the agent as an error result that names the |
| 330 | rule, for example |
| 331 | `[shell.readonly.command] program: `touch` is not a read-only inspection command`, |
| 332 | followed by what the agent can do instead. The agent keeps working, and |
| 333 | repeated refusals without progress end it as failed rather than completed. |
| 334 | |
| 335 | ### Reading beside a writer |
| 336 | |
| 337 | Read-only tools and classifier-approved shell reads can run while a peer owns |
| 338 | a shared write claim. For arbitrary analysis code, call `bash` with explicit |
| 339 | `read_only: true`: |
| 340 | |
| 341 | ```json |
| 342 | { |
| 343 | "action": "run", |
| 344 | "read_only": true, |
| 345 | "command": "python3 -c \"import sqlite3; db = sqlite3.connect('file:cache/index.db?mode=ro', uri=True); print(db.execute('SELECT name FROM sqlite_schema').fetchall())\"" |
| 346 | } |
| 347 | ``` |
| 348 | |
| 349 | This mode requires native filesystem read-only isolation. Outbound network |
| 350 | follows the caller's own shell and is on only when the session runs in Full |
| 351 | Access, its sandbox allows network, its `[network]` policy does not default to |
| 352 | deny, and the agent keeps its network grant; in Ask or Auto-Review, where a |
| 353 | networked command needs an approval this mode never asks for, it stays offline. |
| 354 | With network on, `curl` and HTTPS clients work. `read_only` blocks local file |
| 355 | writes, not requests that change remote services. On macOS the mode then reaches |
| 356 | hosts over IPv4, the system DNS resolver, and a local proxy named in |
| 357 | `HTTP_PROXY`, `HTTPS_PROXY` or `ALL_PROXY`, but not IPv6, another port on this |
| 358 | machine's own addresses, or a local socket. On Linux it shares the host network |
| 359 | namespace, including loopback and abstract unix sockets, as a networked |
| 360 | workspace-write shell does. A networked run records `sandbox_network: true` in |
| 361 | its tool-result metadata. It accepts only foreground `run` with `command`, |
| 362 | optional `cwd`, and `timeout_ms`. Background or interactive modes, stdin, |
| 363 | sandbox escalation, and external execution backends are incompatible. If native |
| 364 | enforcement is absent or cannot be prepared, the call refuses before executing |
| 365 | the command; the flag never falls back to trusting a promise that the code only |
| 366 | reads. Existing role, tool, and ancestor policy restrictions still apply. |
| 367 | |
| 368 | For a write refusal outside your own scope, `agent(action="claim", ...)` can |
| 369 | add permitted paths to your claim. It cannot take a live peer's claim. Wait for |
| 370 | that peer, choose disjoint bounded writes, or use a separate worktree for code |
| 371 | that needs writes. `action="release"` only clears claims whose owners are no |
| 372 | longer live; it is not a way to unlock another running worker's files. |
| 373 | |
| 374 | ## Delegation briefs |
| 375 | |
| 376 | The parent should pass a compact brief instead of a loose paragraph. Use the |
| 377 | structured `dependencies` and `acceptance` arrays for bounded prerequisite facts |
| 378 | and observable checks; keep the focused objective in `prompt`. Do not copy raw |
| 379 | parent reasoning or an unbounded transcript. |
| 380 | |
| 381 | Default shape for the brief — a plain sentence beats the template when the |
| 382 | delegation is trivial: |
| 383 | |
| 384 | ``` |
| 385 | QUESTION: |
| 386 | SCOPE: |
| 387 | ALREADY_KNOWN: |
| 388 | EFFORT: quick | medium | thorough |
| 389 | STOP_CONDITION: |
| 390 | OUTPUT: VERDICT, EVIDENCE, GAPS, NEXT |
| 391 | ``` |
| 392 | |
| 393 | `scout` briefs request read-only investigation with enough evidence to answer |
| 394 | the question reliably. Let the task determine the depth of investigation. |
| 395 | Do not repeat `ALREADY_KNOWN` work unless evidence contradicts it. Builder and |
| 396 | repair-style briefs should use checkpoints before scope expansion or after |
| 397 | repeated failures, then adapt and continue the remaining authorized work. |
| 398 | |
| 399 | Good delegation prompt examples: |
| 400 | |
| 401 | ```text |
| 402 | QUESTION: Does PR #N introduce release-risk behavior around provider routing? |
| 403 | SCOPE: PR #N diff, linked issue, provider routing tests, docs/PROVIDERS.md. |
| 404 | ALREADY_KNOWN: Branch is <release-branch>; workspace version is <live-version>. |
| 405 | EFFORT: medium |
| 406 | STOP_CONDITION: Return once you have either one BLOCKER/MAJOR issue or enough evidence for no MAJOR+ issues. |
| 407 | OUTPUT: VERDICT, EVIDENCE with file:line refs or PR refs, GAPS, NEXT. |
| 408 | ``` |
| 409 | |
| 410 | ```text |
| 411 | QUESTION: Where is the child-agent prompt assembled? |
| 412 | SCOPE: crates/engine/src/prompts*, crates/engine/src/tools/subagent/*. |
| 413 | ALREADY_KNOWN: The model-facing launcher is only `agent`; do not look for removed lifecycle tools. |
| 414 | EFFORT: quick |
| 415 | STOP_CONDITION: Stop after identifying the prompt source files and the function that wraps assignment text. |
| 416 | OUTPUT: VERDICT, EVIDENCE, GAPS, NEXT. |
| 417 | ``` |
| 418 | |
| 419 | ```text |
| 420 | QUESTION: Is the focused prompt/subagent test filter valid, and what fails if not? |
| 421 | SCOPE: cargo test -p codewhale-tui --lib --locked prompt; subagent filter if needed. |
| 422 | ALREADY_KNOWN: Do not fix failures; capture exact command, exit code, and first relevant assertion. |
| 423 | EFFORT: medium |
| 424 | STOP_CONDITION: Stop after one clean PASS or one reproducible failing assertion with command evidence. |
| 425 | OUTPUT: VERDICT, EVIDENCE, GAPS, NEXT. |
| 426 | ``` |
| 427 | |
| 428 | ### When to pick which role |
| 429 | |
| 430 | - **`general`** — when the task is "do this whole thing", not "go |
| 431 | look", "design", or "verify". This is the right default; reach for |
| 432 | a more specific role only when the posture matters. |
| 433 | - **`explore`** — when the parent needs evidence before deciding what |
| 434 | to do next. Scouts are cheap and fast; open 2–3 in parallel |
| 435 | for independent regions. |
| 436 | They should orient first: confirm the project root, read relevant |
| 437 | `AGENTS.md`/`README.md` guidance in unfamiliar trees, search only the |
| 438 | likely scope, and return `path:line-range` evidence instead of a narrative |
| 439 | tour. The role name to use is `explore`. |
| 440 | - **`planner`** — when the parent has an objective but no executable |
| 441 | decomposition. Planners write artifacts (`todo_write` items, |
| 442 | strategy in the response body) but don't carry them out. |
| 443 | - **`reviewer`** — when there's already a change and the parent wants |
| 444 | it graded. Reviewers run under read-only posture, so the runtime |
| 445 | refuses patch attempts — describe the fix in the finding and the |
| 446 | parent dispatches a builder when the verdict is "fix it". |
| 447 | - **`implement`** — when the change is already specified and just |
| 448 | needs to land. Builders stay tightly scoped: minimum edit, no |
| 449 | drive-by refactoring, run a quick verification before handing back. |
| 450 | - **`test`** — when the parent needs an authoritative pass/fail |
| 451 | on the test suite or other validation. The verifier posture never |
| 452 | writes — the runtime refuses fix attempts — so capture the failing |
| 453 | assertion + stack and put fix candidates under RISKS for the parent |
| 454 | to dispatch. Shell is clamped to the bounded built-in verification |
| 455 | surface: Run tests/verifiers (pass `cwd` when the checks live in a |
| 456 | subdirectory), Git fetch for remote refs, Git merge_tree for merge |
| 457 | results. The write ceiling is read-only and unbounded shell forms |
| 458 | are refused (#5186). A refused probe is reported to the parent, |
| 459 | never worked around (#6298). |
| 460 | - **`advisor`** — when the operator wants a high-leverage second opinion |
| 461 | before cheaper execution continues. Consultants read enough to ground a |
| 462 | recommendation; their grant carries no writes and no shell, so the |
| 463 | runtime refuses both. `oracle` and |
| 464 | `consultant` remain accepted only when loading older requests or persisted |
| 465 | records; new prompts, receipts, and UI use `advisor`. |
| 466 | - **`custom`** — only when the parent needs to constrain the tool |
| 467 | set explicitly. Pass the allowlist via the `allowed_tools` field |
| 468 | on legacy/internal sub-agent records; the model-facing `agent` tool keeps the |
| 469 | public schema intentionally small. |
| 470 | |
| 471 | ### Aliases |
| 472 | |
| 473 | The model can spell each role multiple ways: |
| 474 | |
| 475 | | Canonical | Aliases | |
| 476 | |---------------|------------------------------------------------------------------| |
| 477 | | `general` | `worker`, `default`, `general-purpose`, `general_purpose` | |
| 478 | | `explore` | `scout`, `explorer`, `exploration` | |
| 479 | | `planner` | `plan`, `planning`, `awaiter` | |
| 480 | | `reviewer` | `review`, `code-review`, `code_review` | |
| 481 | | `implement` | `builder`, `implementer`, `implementation` | |
| 482 | | `test` | `verifier`, `verify`, `verification`, `validator`, `tester` | |
| 483 | | `advisor` | `consultant`, `oracle` (compatibility input only) | |
| 484 | | `custom` | (none; explicit `allowed_tools` array required) | |
| 485 | |
| 486 | All matching is case-insensitive. Unknown values produce a typed |
| 487 | error listing the accepted set, so the model can self-correct on |
| 488 | the next turn. |
| 489 | |
| 490 | ## Concurrency cap |
| 491 | |
| 492 | Up to **64** sub-agents run concurrently by default (`DEFAULT_MAX_SUBAGENTS`), |
| 493 | configurable via `[subagents].max_concurrent` in `~/.codewhale/config.toml` up to |
| 494 | the hard ceiling of **128** (`MAX_SUBAGENTS`). The session admits a bounded |
| 495 | queue of up to **1024** running plus queued sub-agents by default |
| 496 | (`MAX_SUBAGENT_ADMISSION`, `crates/tui/src/config/subagent_limits.rs:21`), so a turn can |
| 497 | request broad fan-out and let the manager drain it without creating an |
| 498 | unbounded population. |
| 499 | |
| 500 | By default every admitted child may start immediately — there is no artificial |
| 501 | throttle beyond the rate-limit governor described below. Request the fan-out the work actually needs and let the runtime |
| 502 | queue and drain it; the caps above are enforcement, not a reason to |
| 503 | pre-refuse valid work. If you want gentler fan-out, lower `[subagents].launch_concurrency` |
| 504 | (how many direct children start at once); children beyond that limit **queue** |
| 505 | for a launch slot rather than bursting. `launch_concurrency` defaults to the |
| 506 | resolved `max_subagents` cap. (The pre-v0.8.61 `interactive_max_launch` key is |
| 507 | still accepted as a deprecated alias; the new key wins when both are set.) |
| 508 | |
| 509 | High-fanout Workflows can tune that bounded population with `[subagents] |
| 510 | max_admitted` (aliases: `max_total`, `admission_limit`). That total ceiling |
| 511 | counts both **running** and **queued** agents, while `launch_concurrency` keeps |
| 512 | instantaneous execution bounded. Completed / failed / cancelled records persist |
| 513 | for inspection but don't occupy an admission slot. Agents that lost their |
| 514 | `task_handle` (e.g. across a process restart) also don't count against the cap. |
| 515 | |
| 516 | ### Rate-limit governor |
| 517 | |
| 518 | The one automatic throttle is the rate-limit governor. It watches provider |
| 519 | rate limits (HTTP 429) across a 60-second window. After repeated limits it |
| 520 | shrinks the number of launch slots; under a sustained burst it pauses new |
| 521 | launches entirely. Steady successes add slots back one at a time. It never |
| 522 | interrupts an agent that is already running, and quota exhaustion is not |
| 523 | treated as a throttle. |
| 524 | |
| 525 | While the governor is holding launches back, it says so in two places: |
| 526 | |
| 527 | - a queued agent's row gives the reason, for example |
| 528 | `launch slots throttled to 4/8 after 2 provider rate limit(s) in the last 60s` |
| 529 | or `launches paused after 4 provider rate limit(s) in the last 60s`, and the |
| 530 | time its owner-configured wall budget ends, if one exists; |
| 531 | - `GET /v1/agent-runs` returns a `governor` object next to `runs`, with |
| 532 | `launch_slots`, `max_launch_slots`, `paused`, `recent_rate_limits`, and a |
| 533 | `status` line while launches are held back. It describes launches made by the |
| 534 | runtime serving the request (Fleet runs). |
| 535 | |
| 536 | Known limitation: the `/subagents` register header does not show the governor |
| 537 | line yet; the TUI receives agent lists from the Engine without governor state. |
| 538 | |
| 539 | Provider profiles let one config stay aggressive for direct API routes while |
| 540 | keeping subscription or aggregator routes gentle. Every key under |
| 541 | `[subagents.providers.<provider>]` inherits from `[subagents]` when omitted. |
| 542 | Provider keys accept canonical names such as `deepseek`, `zai`, `openrouter`, |
| 543 | and aliases such as `glm` for Z.ai: |
| 544 | |
| 545 | ```toml |
| 546 | [subagents] |
| 547 | # Global fallback for providers without a profile. |
| 548 | max_concurrent = 20 |
| 549 | launch_concurrency = 20 |
| 550 | max_admitted = 200 |
| 551 | # Operator-selected Runtime delegation depth (defaults to 3 when omitted; 0 disables child delegation). |
| 552 | # This explicit value restricts descendants to six levels. |
| 553 | max_depth = 6 |
| 554 | # A positive value sets a step limit for each child. Zero leaves it unbounded. |
| 555 | default_max_steps = 0 |
| 556 | default_wall_time_secs = 0 |
| 557 | |
| 558 | [subagents.providers.deepseek] |
| 559 | # Direct API key with room to fan out. |
| 560 | max_concurrent = 20 |
| 561 | launch_concurrency = 20 |
| 562 | max_admitted = 200 |
| 563 | |
| 564 | [subagents.providers.glm] |
| 565 | # Z.ai / GLM subscription-style route: keep pressure tight. |
| 566 | max_concurrent = 4 |
| 567 | launch_concurrency = 3 |
| 568 | max_admitted = 12 |
| 569 | max_depth = 2 |
| 570 | api_timeout_secs = 180 |
| 571 | heartbeat_timeout_secs = 240 |
| 572 | |
| 573 | [subagents.providers.openrouter] |
| 574 | max_concurrent = 5 |
| 575 | launch_concurrency = 3 |
| 576 | max_admitted = 20 |
| 577 | |
| 578 | [subagents.providers.anthropic] |
| 579 | max_concurrent = 3 |
| 580 | launch_concurrency = 2 |
| 581 | max_admitted = 12 |
| 582 | ``` |
| 583 | |
| 584 | Use `/config subagents status` to see both the global values and the active |
| 585 | provider's resolved fanout, depth, and timeout profile. |
| 586 | |
| 587 | ## Advertised agent-tool fields |
| 588 | |
| 589 | The model-facing `agent` schema exposes these controls: |
| 590 | |
| 591 | | Purpose | Fields | |
| 592 | | --- | --- | |
| 593 | | Launch and route | `action`, `prompt`, `type`, `profile`, `name`, `model`, `model_strength`, `thinking` | |
| 594 | | Scope and outputs | `worktree`, `cwd`, `write_authority`, `write_roots`, `exact_files`, `coordination_contracts`, `deliverables`, `expected_artifact` | |
| 595 | | Coordinate and recover | `agent_id`, `agent_ids`, `all_parked`, `message`, `until`, `detached`, `resume_from` | |
| 596 | | Inspect | `detail`, `offset`, `limit` | |
| 597 | |
| 598 | `start` requires `prompt`. `message` requires a target and message; |
| 599 | `followup` requires a message and exactly one target form: `agent_id`/`name`, |
| 600 | `agent_ids`, or `all_parked: true`. `peek`, `interrupt`, and `cancel` require a |
| 601 | target. `claim` requires scope entries. These action requirements are validated |
| 602 | before execution. |
| 603 | |
| 604 | `agent(action="roster")` reports each built-in role's resolved provider, model, |
| 605 | reasoning effort, known route limits and capability provenance. It uses the |
| 606 | same resolver as execution. An explicit saved profile wins first, followed by |
| 607 | a manual role pin in the current configuration, then a unique saved member |
| 608 | pinning that semantic role. Conflicting task `model` or `model_strength` choices |
| 609 | fail before admission. For an unpinned role, per-task `model` precedes |
| 610 | `model_strength`, then inherited role defaults and the session route. |
| 611 | When a Pod is selected, the `models` rows list its exact routes in saved order. |
| 612 | Use a listed `provider/model` selector for a task on an unpinned role; the session |
| 613 | model remains allowed. Off-list choices fail with the allowed routes, and a bare |
| 614 | model shared by multiple providers requires an exact selector. Without selected |
| 615 | models, current-provider overrides and `model_strength` retain their behavior; |
| 616 | foreign-provider requests fail. These choices do not change child authority. |
| 617 | |
| 618 | The `profiles` rows expose saved members from the existing selected Fleet or |
| 619 | trusted config/personal/workspace/plugin layers, with bounded identities and the |
| 620 | same route/cost evidence. `profile="bug-hunter"` loads that member's instructions, |
| 621 | role, provider/model pin and depth limit. Conflicting type or model requests are |
| 622 | refused; explicit `thinking` overrides the saved tier. Missing providers, revoked |
| 623 | plugin authority and disabled project profiles fail before child admission. |
| 624 | Discovery never creates a profile or enrolls a model. These identity choices use |
| 625 | the existing child lifecycle; a saved profile alone does not create a continuing |
| 626 | Bot conversation or a computer lease. |
| 627 | |
| 628 | Cost classes describe current uncached text input/output rates, not the total |
| 629 | price of a future task. Missing or routing-dependent prices remain unknown; |
| 630 | subscription/local routes are labelled not money metered. Discovery makes no |
| 631 | provider request. A route equal to the session's own route reports |
| 632 | `reachability` as `configured`; every other route reports `unverified` with a |
| 633 | `reachability_note`. |
| 634 | |
| 635 | **Parse-accepted but unadvertised (compat).** Other inputs remain accepted |
| 636 | for saved transcripts, ACP/MCP clients, fleet execution data, and |
| 637 | internal/operator compatibility. Runtime validates and intersects them with |
| 638 | live policy: |
| 639 | |
| 640 | - delegation compatibility: `max_depth`, `maxDepth`, or `max_spawn_depth`; |
| 641 | model-facing calls ignore these values and inherit depth from the operator |
| 642 | and selected profile. Exact Fleet authority still supplies its validated |
| 643 | depth ceiling. |
| 644 | - workspace/isolation: `workspace_policy`, `fork_context`, |
| 645 | `worktree_path`, `worktree_branch`, `worktree_base` |
| 646 | - spawn contract: `deliberate`, `dependencies`, `acceptance`, `allowed_tools` |
| 647 | - lifecycle extras: `timeout_secs` (wait), `reason` (interrupt), |
| 648 | `include_archived` (status) |
| 649 | |
| 650 | Compatibility input is not a way to widen inherited authority or remove a |
| 651 | finite budget. |
| 652 | |
| 653 | ## Child limits and completion |
| 654 | |
| 655 | Children have no default model-turn or wall-clock limit. They continue until |
| 656 | completion, a need for user input, cancellation, or an explicit owner limit. |
| 657 | Elapsed time and step counts do not establish whether useful work is finished. |
| 658 | The runtime does not inject percentage-based instructions to stop exploring or |
| 659 | wrap up early. |
| 660 | |
| 661 | The model-facing `agent` tool does not advertise `max_steps`, `wall_time_secs`, |
| 662 | or `max_output_tokens`. Valid legacy inputs still parse, but do not constrain |
| 663 | model-launched children. A launch receipt lists `ignored_limit_fields` when |
| 664 | those inputs are supplied; `effective_limits` shows what actually applies. |
| 665 | Models should specify the task, write scope, deliverables and acceptance criteria, |
| 666 | not guess how many turns or minutes completion will require. |
| 667 | |
| 668 | An operator can deliberately set `[subagents] default_max_steps` or |
| 669 | `default_wall_time_secs`. Omission or zero leaves every role without a default step or time limit. |
| 670 | `explore` children inherit at most `medium` reasoning effort unless an explicit |
| 671 | `thinking` value is supplied. Positive owner |
| 672 | limits and role, parent and saved-run bounds remain authoritative; a child |
| 673 | cannot remove them. There is no additional 2,000-turn or 24-hour child ceiling. |
| 674 | Continuations preserve an existing run's remaining steps and absolute deadline. |
| 675 | |
| 676 | Concurrency limits queue work rather than giving it a guessed completion budget. |
| 677 | Without an owner deadline, a queued child waits for a slot or cancellation. With |
| 678 | an explicit wall budget, its queue wait is bounded by that duration; if no slot |
| 679 | opens it reports `never started` with zero work. After launch its work clock |
| 680 | restarts within any inherited absolute deadline, which is persisted for |
| 681 | continuation. The queued row reports the wait reason and any actual deadline. |
| 682 | |
| 683 | For example: |
| 684 | |
| 685 | ```json |
| 686 | { |
| 687 | "action": "start", |
| 688 | "type": "reviewer", |
| 689 | "prompt": "Review the parser diff and report concrete regressions with file and line evidence." |
| 690 | } |
| 691 | ``` |
| 692 | |
| 693 | ### Usage and partial results |
| 694 | |
| 695 | Token usage is tracked, never used as a run-wide kill budget. Legacy |
| 696 | `token_budget` input is ignored. Provider-reported usage is the accounting |
| 697 | source; missing usage remains unknown. Context compaction lets a child |
| 698 | continue as its conversation grows. Provider context windows and output limits |
| 699 | still apply to individual requests, and incomplete tool arguments are never |
| 700 | executed. |
| 701 | |
| 702 | Runtime `agent.completed` events and `/v1/agent-runs` worker records carry |
| 703 | an optional `limit_kind` of `step` or `wall_time` when the host recorded that |
| 704 | cause. Older receipts may omit it. |
| 705 | |
| 706 | When an explicit owner step or time limit ends a run, the existing hand-back |
| 707 | path preserves partial work and attempts one tools-disabled report within the |
| 708 | remaining allowance. Its fixed input/output allowance is at most 8,192 tokens, |
| 709 | with at most 1,024 output tokens. A step limit of at least two reserves one turn; |
| 710 | a wall limit reserves at most 10 seconds for reporting. These reserves do not |
| 711 | create a limit on an otherwise unbounded run. |
| 712 | |
| 713 | The outcome remains `BudgetExhausted` rather than successful completion, even |
| 714 | when a useful partial report is available. If reporting cannot run, the receipt |
| 715 | retains recorded work and explains why. Cancellation remains available during |
| 716 | work and queue waits. Unknown provider usage is never reported as zero. |
| 717 | |
| 718 | ## Per-role models (#3018) |
| 719 | |
| 720 | Children can run on a different model than the parent. Structured role pins, |
| 721 | the legacy model map, and convenience keys feed one override map. Structured |
| 722 | `[subagents.roles.<role>]` entries win over `[subagents.models]`, which wins over |
| 723 | the convenience keys. Keys are case-insensitive; within the structured table, |
| 724 | a canonical role key wins over its legacy alias: |
| 725 | |
| 726 | ```toml |
| 727 | [subagents] |
| 728 | default_model = "deepseek-v4-flash" # fallback for every role |
| 729 | worker_model = "deepseek-v4-pro" # worker |
| 730 | scout_model = "deepseek-v4-flash" # scout |
| 731 | planner_model = "deepseek-v4-flash" # planner |
| 732 | reviewer_model = "deepseek-v4-pro" # reviewer |
| 733 | custom_model = "deepseek-v4-pro" # custom |
| 734 | |
| 735 | [subagents.models] |
| 736 | # Free-form role → model map; any role alias accepted by agent works. |
| 737 | builder = "deepseek-v4-pro" |
| 738 | |
| 739 | [subagents.roles.reviewer] |
| 740 | model = "deepseek/deepseek-v4-pro" |
| 741 | ``` |
| 742 | |
| 743 | These are manual pins for direct and Workflow `agent` starts. A task may restate |
| 744 | the same model or exact provider/model pair, but cannot change the pin with |
| 745 | `model` or `model_strength`. The refusal names the roles (unpinned `type` |
| 746 | values) and saved profiles on the current roster that do accept the requested |
| 747 | model. An explicit saved profile takes precedence over a |
| 748 | manual role pin. A type-only start also selects a unique saved role pin when |
| 749 | there is no manual override; ambiguous saved roles fail instead of choosing one. |
| 750 | Durable Fleet runs retain their selected member's frozen route. |
| 751 | |
| 752 | A structured role pin may list approved replacement routes: |
| 753 | |
| 754 | ```toml |
| 755 | [subagents.roles.reviewer] |
| 756 | model = "xai/grok-4.6" |
| 757 | replacements = ["deepseek/deepseek-v4-pro"] |
| 758 | ``` |
| 759 | |
| 760 | When the pinned route refuses the agent's **first** request (exhausted quota, |
| 761 | rejected credentials or authorization, or an unavailable model), the agent |
| 762 | retries that same request on the next listed route, keeping its role, |
| 763 | permissions, tools, scope and budgets. Listing a route authorizes sending the |
| 764 | agent's task to that provider, so each entry must name `provider/model`; at |
| 765 | most three are allowed and each is tried once. The route receipt records the |
| 766 | effective route, `route_source = "role.replacement"`, and a note with the |
| 767 | original route, the reason and the attempt. Replacement never happens after |
| 768 | the agent has run a tool, never for content-policy, context-length or |
| 769 | invalid-request errors, never for Codewhale's own permission denials, and never |
| 770 | for exact Fleet members or task-level `model` choices, which stay exact. |
| 771 | |
| 772 | Structured role pins accept `provider/model`, preserving the configured provider's |
| 773 | exact identity and the complete model suffix. Unknown providers, empty pairs, |
| 774 | and cross-provider `auto` choices fail before admission. A bare structured model |
| 775 | inherits the session provider. For a namespaced model, qualify it explicitly, |
| 776 | for example `openrouter/deepseek/deepseek-v4-pro`. Legacy scalar and |
| 777 | `[subagents.models]` values keep their full provider-owned id, including slashes; |
| 778 | they do not change providers. |
| 779 | |
| 780 | The legacy convenience keys `explorer_model`, `awaiter_model`, and |
| 781 | `review_model` remain accepted as deprecated aliases so existing config files |
| 782 | do not break. |
| 783 | |
| 784 | Model ids may be **any model the active provider accepts** — validation is |
| 785 | provider-aware and happens at spawn time, not load time. On the official |
| 786 | DeepSeek API only DeepSeek ids are accepted; every other provider passes the |
| 787 | id through to the provider API, which is the authority. A non-DeepSeek |
| 788 | example: |
| 789 | |
| 790 | ```toml |
| 791 | provider = "moonshot" |
| 792 | model = "kimi-k2.7-code" |
| 793 | |
| 794 | [subagents] |
| 795 | worker_model = "kimi-k2.6" |
| 796 | ``` |
| 797 | |
| 798 | Model ids are validated the same way when applied to a child route; an invalid |
| 799 | id on the official DeepSeek API fails the spawn with the accepted-id list |
| 800 | instead of an opaque provider 400. |
| 801 | |
| 802 | With `/model auto`, sub-agent routing is provider-aware too: providers with a |
| 803 | known big/cheap pair (DeepSeek, and the hosted DeepSeek routes on NVIDIA NIM, |
| 804 | OpenRouter, Novita, SiliconFlow, SGLang, vLLM) route between that pair; |
| 805 | providers without a known cheap tier (e.g. Ollama, Moonshot) skip the |
| 806 | network router and keep children on the session model. |
| 807 | |
| 808 | ## Per-profile provider routes (#3965) |
| 809 | |
| 810 | `[subagents.models]` changes the child model within the active provider. A slash |
| 811 | in that legacy input does not grant another provider. To pin a different provider, |
| 812 | use a structured `[subagents.roles.<role>]` declaration as above, or use a |
| 813 | fleet/AgentProfile and select it with `profile` or its unique saved role. |
| 814 | The profile's explicit `provider` + |
| 815 | `model` fields win over the parent session route; omitting `provider` preserves |
| 816 | the existing inherit behavior. |
| 817 | |
| 818 | Example: keep the parent session on DeepSeek, but run a formatter child on a |
| 819 | local LM Studio OpenAI-compatible endpoint: |
| 820 | |
| 821 | ```toml |
| 822 | # ~/.codewhale/config.toml or workspace config |
| 823 | provider = "deepseek" |
| 824 | |
| 825 | [providers.deepseek] |
| 826 | api_key = "YOUR_DEEPSEEK_KEY" |
| 827 | |
| 828 | [providers.lm-studio] |
| 829 | kind = "openai-compatible" |
| 830 | base_url = "http://127.0.0.1:1234/v1" |
| 831 | api_key = "lm-studio" |
| 832 | model = "qwen-2.5-7b" |
| 833 | ``` |
| 834 | |
| 835 | ```toml |
| 836 | # .codewhale/agents/local-formatter.toml |
| 837 | id = "local-formatter" |
| 838 | role_hint = "formatter" |
| 839 | provider = "lm-studio" |
| 840 | model = "qwen-2.5-7b" |
| 841 | reasoning_effort = "off" |
| 842 | |
| 843 | [instructions] |
| 844 | text = "Use small, local edits. Keep formatting changes mechanical." |
| 845 | ``` |
| 846 | |
| 847 | Then call `agent(profile: "local-formatter", prompt: "...")`. In-process |
| 848 | children build a client for `lm-studio`; fleet workers forward |
| 849 | `--provider lm-studio` to `codewhale exec`, which resolves the same |
| 850 | `[providers.lm-studio]` table. Unknown or unconfigured provider ids fail the |
| 851 | spawn rather than silently falling back to the parent provider. |
| 852 | |
| 853 | ## Per-step API timeout (#1806, #1808) |
| 854 | |
| 855 | Each sub-agent step wraps its provider streaming call in a |
| 856 | per-step timeout so a single stuck request can't pin the parent's |
| 857 | completion wakeup channel indefinitely. The default is `600` seconds. |
| 858 | A timeout after possible dispatch interrupts the step with a preserved |
| 859 | checkpoint and unknown request outcome. Only a transient connection timeout |
| 860 | proven to precede dispatch uses the existing backoff, up to 5 retries. Ordinary |
| 861 | rate limits retain their bounded retry policy; stream interruptions do not |
| 862 | automatically reissue inference. |
| 863 | Long-thinking children that legitimately exceed that, for example |
| 864 | heavy plan or review work behind `agent`, can extend the timeout in |
| 865 | `~/.codewhale/config.toml`: |
| 866 | |
| 867 | ```toml |
| 868 | [subagents] |
| 869 | api_timeout_secs = 900 # 15 minutes; clamped to 1..=3600 |
| 870 | ``` |
| 871 | |
| 872 | Values are clamped to `1..=3600`. `0` and `unset` keep the `600` |
| 873 | second default. |
| 874 | |
| 875 | ## Stale-agent heartbeat (#2614) |
| 876 | |
| 877 | Running agents also track manager-visible progress. If a child stops emitting |
| 878 | progress for the heartbeat window, the manager auto-cancels it, releases its |
| 879 | sub-agent slot, and keeps the cancelled record inspectable through the returned |
| 880 | transcript handle and persisted worker record. The default is 5 minutes |
| 881 | (resolved to at least 30 seconds above `api_timeout_secs`, so 630 seconds |
| 882 | with the 600-second default API timeout): |
| 883 | |
| 884 | ```toml |
| 885 | [subagents] |
| 886 | heartbeat_timeout_secs = 300 # clamped to 30..=3600 |
| 887 | ``` |
| 888 | |
| 889 | The effective heartbeat is kept at least 30 seconds above |
| 890 | `api_timeout_secs`, so a configured long model request is not cancelled before |
| 891 | its own request timeout can fire. |
| 892 | |
| 893 | ## Lifecycle |
| 894 | |
| 895 | Each opened session produces a record that progresses through: |
| 896 | |
| 897 | ``` |
| 898 | Pending → Running → (Completed | Failed(reason) | Cancelled | Interrupted(reason) | BudgetExhausted) |
| 899 | ``` |
| 900 | |
| 901 | An explicit interrupt, exhausted provider retries, or recovery of an orphaned |
| 902 | running record can leave an `Interrupted` worker with a checkpoint. Inspect |
| 903 | `needs_continuation` and the recorded reason; use `followup` for continuable |
| 904 | work. `BudgetExhausted` includes the specific token, step, or wall-time cause; |
| 905 | continuation cannot replenish an exhausted allowance. |
| 906 | |
| 907 | `wait` observes workers. A timeout returns current outcomes and never parks, |
| 908 | cancels, or resumes them. `until: "completion"` returns when one child settles; |
| 909 | `until: "all"` joins the workers running when that call starts; |
| 910 | `until: "activity"` can return on progress. A later spawn is not silently added to an |
| 911 | earlier join. |
| 912 | |
| 913 | An ordinary parent response leaves healthy children running. The same Engine |
| 914 | turn loop consumes their completion notices and can continue the parent. |
| 915 | Headless `codewhale exec` defers a successful final receipt until its existing |
| 916 | Engine reports no live children and no queued child completions. Its original |
| 917 | wall-clock deadline still bounds that settlement, including autonomous parent |
| 918 | turns. Cancellation, deadline exhaustion, a fatal event, or a lost Engine |
| 919 | channel stops settlement and returns the appropriate interrupted or failed |
| 920 | receipt with recorded partial usage. It does not report successful child |
| 921 | completion merely because the parent's first response ended. |
| 922 | |
| 923 | ### Session boundaries (#405) |
| 924 | |
| 925 | Each `SubAgentManager` instance assigns itself a fresh `session_boot_id` on |
| 926 | construction. Every new session stamps the agent with that id; the workspace |
| 927 | state file records it for restart recovery. |
| 928 | |
| 929 | Work-bar/status projections focus on current-session agents by default. |
| 930 | Prior-session agents that are not still running are treated as archived records |
| 931 | so the model does not mistake stale work for live work. This is a |
| 932 | *prior-session* rule only: agents that finished in the CURRENT session keep |
| 933 | their work-bar rows for the rest of the session (quiet completion), and their |
| 934 | details still open from those rows. |
| 935 | |
| 936 | Records that loaded from a pre-#405 persisted state file (no |
| 937 | `session_boot_id` field) classify as prior-session because the |
| 938 | manager can't match them to the current boot. |
| 939 | |
| 940 | ## Run receipts, follow-up, and takeover |
| 941 | |
| 942 | Each compatibility sub-agent has a persisted worker record in |
| 943 | `.codewhale/state/subagents.v1.json`. The record is the current run-ledger |
| 944 | slice for sub-agent lanes until those lanes are backed directly by the fleet |
| 945 | ledger: it stores `run_id`, objective, role/model, |
| 946 | workspace/branch, lifecycle events, artifact refs, follow-up target, takeover |
| 947 | target, usage provenance, and verification provenance. |
| 948 | |
| 949 | The normal parent flow is to keep working and consume the completion event. |
| 950 | Default start and status receipts are compact; full snapshots and worker |
| 951 | records are diagnostic detail, not repeated in every response. |
| 952 | |
| 953 | ### Continue an existing worker |
| 954 | |
| 955 | `message` sends a note to a running child. A child with a live input channel |
| 956 | receives it at its next step boundary without being interrupted, and the |
| 957 | receipt says `delivered: "next_step"`. If that channel has closed, the note |
| 958 | stays queued (`queued: true`) until a later `followup` delivers it. Children |
| 959 | that are not running do not accept messages. `followup` wakes a running child |
| 960 | or resumes a continuable checkpoint: |
| 961 | |
| 962 | ```json |
| 963 | {"action":"followup","agent_id":"child-previous-id","message":"Continue the assignment using the recorded evidence."} |
| 964 | ``` |
| 965 | |
| 966 | Use the returned `agent_id` for subsequent waits and messages. The receipt's |
| 967 | `from` and `to` identify the original target and its current continuation. |
| 968 | The original receipt is retained. Retrying through an old ID follows the |
| 969 | persisted continuation chain and does not create a duplicate worker. If the |
| 970 | current successor is running, the follow-up is delivered there; if it has |
| 971 | already settled and cannot continue, the response says no message was |
| 972 | delivered. Duplicate workers are prevented, but repeated messages to a running |
| 973 | worker are still repeated messages. |
| 974 | |
| 975 | For a batch, choose exactly one target form: |
| 976 | |
| 977 | ```json |
| 978 | {"action":"followup","agent_ids":["child-a","child-b"],"message":"Continue the remaining checks."} |
| 979 | ``` |
| 980 | |
| 981 | ```json |
| 982 | {"action":"followup","all_parked":true,"message":"Continue the parked assignments."} |
| 983 | ``` |
| 984 | |
| 985 | Explicit batches accept up to 32 distinct IDs. `all_parked` selects parked |
| 986 | children you control and refuses more than 32 so you can choose explicit |
| 987 | batches. Bulk responses return separate `results` and `errors`; a failing |
| 988 | target does not roll back a successful continuation. Parent/descendant control |
| 989 | checks apply to both the addressed record and its current successor. |
| 990 | |
| 991 | Use `start` with `resume_from` only to create a separate worker from a settled |
| 992 | child's transcript, for example to assign a new review. Each such start is a |
| 993 | new worker. Missing, running, or cross-workspace sources are refused; the |
| 994 | source's authority and budget bounds still apply. This is distinct from |
| 995 | continuing parked work with `followup`. |
| 996 | |
| 997 | ### Compact status and full transcript retrieval |
| 998 | |
| 999 | Unscoped `agent(action="status")` returns a session-scoped page bounded to |
| 1000 | 8 KiB. `offset` and `limit` page the roster; the default and maximum limit is |
| 1001 | 20. Follow `next_offset`, since the byte bound can return fewer rows than |
| 1002 | requested. The model-facing roster wire uses one stable `columns` header and |
| 1003 | an array of values per entry in `agents`; pair each row with the header instead |
| 1004 | of reading it as an object. `null` means absent or unreported, and a measured |
| 1005 | zero stays numeric `0`. The header is present even on an empty page. |
| 1006 | Rows include worker and parent IDs, current depth, state, |
| 1007 | elapsed time, own token total, recent activity, pending input, and continuation |
| 1008 | lineage (`resumed_from` / `resumed_as`). Verification includes the verdict, |
| 1009 | nonempty deliverable counts and a short warning when needed. Names, steps, |
| 1010 | routes, effective limits (including maximum depth), and token breakdowns remain |
| 1011 | available in the unchanged object projection when addressing one `agent_id`. |
| 1012 | Aggregate usage counts each worker's own reported tokens once and reports its |
| 1013 | coverage: `unreported_usage_workers` counts workers with a response whose usage |
| 1014 | is missing, `partially_reported_workers` counts those among them that also |
| 1015 | reported some, and `complete` is true only when every counted worker has |
| 1016 | reported usage, none has a missing response, and none is still running or |
| 1017 | waiting. Completion receipts additionally report measured descendant usage, |
| 1018 | deduplicate continuation lineage, and distinguish unknown usage from zero. A worker's |
| 1019 | `has_unreported_usage` and the descendant/subtree `unreported_usage_workers` and |
| 1020 | `partially_reported_workers` counts identify missing responses even when later |
| 1021 | responses provide a measured subtotal. Their `complete` additionally requires |
| 1022 | every descendant to have finished. |
| 1023 | |
| 1024 | Request one worker's detail when investigating a failure: |
| 1025 | |
| 1026 | ```json |
| 1027 | {"action":"status","agent_id":"child-a","detail":true,"offset":0,"limit":20} |
| 1028 | ``` |
| 1029 | |
| 1030 | Addressed `peek` (one `agent_id`) also reads that worker's live transcript and |
| 1031 | returns `recent_activity`: its last 12 tool calls in order, each with `tool`, |
| 1032 | `input_preview` (the command for shell calls, otherwise compact JSON), |
| 1033 | `result_preview`, and `is_error`. It adds `last_assistant_text` and a |
| 1034 | `work_summary` with `tool_calls_total`, per-tool `tool_counts`, `edit_calls` |
| 1035 | (file-writing calls) and `last_activity_at`. When the peek would pass its 8 KiB |
| 1036 | budget, the oldest calls are dropped first and `recent_activity_omitted` says |
| 1037 | how many. A missing or unreadable transcript leaves `recent_activity` empty and |
| 1038 | names the reason in `recent_activity_unavailable`; the peek itself still |
| 1039 | succeeds. |
| 1040 | |
| 1041 | Addressed `peek` also accepts `detail: true`. Detail remains bounded to 32 KiB; |
| 1042 | message/event archives and deliverable verdicts are paged, and omission fields |
| 1043 | identify truncated detail. Use the returned typed `transcript_handle` with |
| 1044 | `handle_read` for the complete retained transcript. The handle's lookup |
| 1045 | coordinates are preserved even when diagnostic prose is omitted. Unscoped |
| 1046 | `detail: true` does not expand the entire roster into transcripts. |
| 1047 | |
| 1048 | Artifacts are symbolic refs. Treat `result_summary` as a child self-report and |
| 1049 | inspect the specific `verification.status` and its evidence before relying on |
| 1050 | it. `usage.status` remains `unknown` until provider usage is reported, then |
| 1051 | becomes `reported` or `budget_exhausted` for a spent token scope. Neither a |
| 1052 | file's `present` verdict nor a completed lifecycle state proves a test gate. |
| 1053 | |
| 1054 | ## Output contract |
| 1055 | |
| 1056 | Non-scout sub-agents end with five Markdown headings, in this order: |
| 1057 | |
| 1058 | ``` |
| 1059 | ### SUMMARY one paragraph; what you did and what happened |
| 1060 | ### EVIDENCE path:line-range citations and key findings; one bullet each |
| 1061 | ### CHANGES files modified, with one-line descriptions; "None." if read-only |
| 1062 | ### RISKS what could go wrong / what the parent should double-check |
| 1063 | ### BLOCKERS what stopped you; "None." if you finished cleanly |
| 1064 | ``` |
| 1065 | |
| 1066 | Use `### HEADING` lines, with `EVIDENCE` before `CHANGES`. List edited |
| 1067 | repo-relative file paths under `### CHANGES`; blank lines before the bullets |
| 1068 | are allowed. Begin each bullet with its file path, followed by a description; |
| 1069 | quote paths containing spaces or literal trailing punctuation. The verifier |
| 1070 | also accepts older explicit `CHANGES:`, |
| 1071 | `Changed files:`, and `Files changed:` declarations. Evidence citations and |
| 1072 | paths under `RISKS` are not declarations of edits. The five-heading prompt |
| 1073 | contract is `SUBAGENT_OUTPUT_FORMAT` in |
| 1074 | `crates/engine/src/prompts/text.rs`. `prompt_documents_structured_subagent_briefs` |
| 1075 | in `crates/engine/src/prompts.rs` asserts every heading against it. |
| 1076 | |
| 1077 | Scouts are the carve-out (#5189 F5): they end with `### SUMMARY` and |
| 1078 | `### EVIDENCE` only (`SUBAGENT_SCOUT_OUTPUT_FORMAT` in |
| 1079 | `crates/engine/src/prompts/text.rs`). `FleetRole::system_prompt` in |
| 1080 | `crates/engine/src/tools/subagent/mod.rs` injects the scout contract for |
| 1081 | `FleetRole::Scout` and the five-heading contract for every other role. A |
| 1082 | subagent test pins that scouts contain `## Output contract (scout)` and do |
| 1083 | not contain `### BLOCKERS`. |
| 1084 | |
| 1085 | The parent reads `EVIDENCE` as a working set for the next turn, so |
| 1086 | scouts and reviewers should be precise here. |
| 1087 | |
| 1088 | ## What a child knows at start |
| 1089 | |
| 1090 | A child's system prompt carries, after its role contract and memory: |
| 1091 | |
| 1092 | - **Inherited instructions.** The same user-level and project-level |
| 1093 | instructions pinned for the parent session (`AGENTS.md`/`CLAUDE.md` chain, |
| 1094 | rules, constitution), each scope capped at 64 KiB with a truncation marker |
| 1095 | pointing back to the source file. They are already within the parent's |
| 1096 | instruction budget; the cap protects a child on a smaller context window. |
| 1097 | A forked child receives them once, in its system prompt, not again in the |
| 1098 | forked context block. They narrow behaviour only; they never widen the |
| 1099 | child's permissions. |
| 1100 | - **Identity and capabilities.** Its workspace path, whether it is an isolated |
| 1101 | worktree and on which branch, its file, shell, network and delegation grants |
| 1102 | (resolved from the same grant the tool registry enforces), whether an |
| 1103 | approval prompt can be answered for it, and the rule that a step needing a |
| 1104 | missing capability comes back to the parent as a BLOCKER with the exact |
| 1105 | command or edit, instead of a workaround. |
| 1106 | |
| 1107 | Both sit in the child's frozen system prefix: they are fixed for that child's |
| 1108 | lifetime and do not change its KV-cache prefix between turns. |
| 1109 | |
| 1110 | ## Memory and the `remember` tool (#489) |
| 1111 | |
| 1112 | Sub-agents share the parent's native memory store when memory is enabled |
| 1113 | (`[memory] enabled = true` or `DEEPSEEK_MEMORY=on`). They can |
| 1114 | append durable notes via the `remember` tool — handy for a |
| 1115 | scout that discovers a project convention worth carrying across |
| 1116 | sessions, or a verifier that learns "this test is flaky". |
| 1117 | |
| 1118 | A child also *reads* the same reviewed memory the parent reads. Its system |
| 1119 | prompt carries the parent session's `codewhale.memory.context.v1` packet, |
| 1120 | followed by the same `## Memory Hygiene` guidance the root prompt uses |
| 1121 | (`crates/engine/src/tools/subagent/mod.rs`, `subagent_memory_section`), so a |
| 1122 | rule the user pinned — a deployment gate, a working-directory rule — binds the |
| 1123 | child that actually edits files rather than only the orchestrator. The packet |
| 1124 | is re-composed from the inherited `memory_path` instead of copied out of the |
| 1125 | parent's prompt, so a memory edited mid-session reaches a later spawn, and an |
| 1126 | isolated worktree still resolves to the same workspace scope through its |
| 1127 | shared git remote. Children record no context receipt of their own; the root |
| 1128 | session's preparation is the receipt for those bytes. With memory disabled, |
| 1129 | path absent, empty store, or every entry reviewed off, nothing is injected — |
| 1130 | no empty envelope. |
| 1131 | |
| 1132 | Consequences worth knowing: the packet is untrusted evidence with the same |
| 1133 | standing it has for the parent (it is not an authority channel), and it sits |
| 1134 | in the child's stable prefix, so a memory edit changes child prompt bytes the |
| 1135 | same way it changes the parent's pinned header. A workspace identity is |
| 1136 | resolved from the child's own workspace; a non-git workspace with a child |
| 1137 | `cwd` in a subdirectory resolves to a different identity and therefore misses |
| 1138 | workspace-scoped memory (global memory still applies). |
| 1139 | |
| 1140 | `remember` takes a `scope` of `global` or `workspace` |
| 1141 | (`crates/engine/src/tools/remember.rs`, schema enum plus scope handling) and |
| 1142 | writes through `NativeMemoryStore` to `~/.codewhale/memory/global/MEMORY.md` |
| 1143 | or `~/.codewhale/memory/workspace/<id>/MEMORY.md`. Writes do not go through |
| 1144 | the standard write-approval flow. See `docs/MEMORY.md` for the full layout. |
| 1145 | |
| 1146 | ## Implementation notes |
| 1147 | |
| 1148 | - Source: `crates/engine/src/tools/subagent/mod.rs`. |
| 1149 | - Persisted state: `<workspace>/.codewhale/state/subagents.v1.json`. Schema |
| 1150 | version `1` (forward-compatible — new optional fields use |
| 1151 | `#[serde(default)]`). |
| 1152 | - Settled records normally expire after `COMPLETED_AGENT_RETENTION` |
| 1153 | (default 1h), with a normal retained-record target of 256. Running / |
| 1154 | starting / waiting workers and the continuation identities and budget |
| 1155 | lineage needed by live work are preserved. Cleanup cannot discard an old |
| 1156 | ID while its continuation is still active or erase usage history needed |
| 1157 | to enforce an active scope. |
| 1158 | - `SubAgentRuntime::background_runtime()` starts from `child_runtime()` but |
| 1159 | replaces the turn-scoped child token with a fresh cancellation token, so |
| 1160 | parent turn cancellation does not stop detached background sessions. |
| 1161 | - The `is_running` check ignores agents whose `task_handle` is |
| 1162 | `None`; this avoids counting persisted-but-detached records |
| 1163 | toward the concurrency cap (#509). |
| 1164 | - `SharedSubAgentManager` is `Arc<RwLock<...>>` — read paths use |
| 1165 | read locks so `/agents` and the workbar projection don't block |
| 1166 | the main loop during multi-agent fan-out (#510). |
| 1167 | |
| 1168 | Personal and trusted workspace agent directories accept both TOML and Markdown files. |
| 1169 | A Markdown profile uses the same YAML frontmatter and instruction body as an imported |
| 1170 | Claude Code agent. Files in the same directory must declare unique names across both formats. |
| 1171 | |
| 1172 | ```markdown |
| 1173 | --- |
| 1174 | name: reviewer |
| 1175 | description: Inspect changes for regressions |
| 1176 | tools: Read, Grep |
| 1177 | --- |
| 1178 | Review the changed behavior and cite the relevant source. |
| 1179 | ``` |
| 1180 | |
| 1181 | |
| 1182 | Personal profiles use the same format at |
| 1183 | `$CODEWHALE_HOME/agents/<id>.toml` (normally `~/.codewhale/agents/`). For example: |
| 1184 | |
| 1185 | ```toml |
| 1186 | # ~/.codewhale/agents/reasoner.toml |
| 1187 | base_role = "explore" |
| 1188 | provider = "openrouter" |
| 1189 | model = "qwen/qwen3.7-plus" |
| 1190 | reasoning_effort = "high" |
| 1191 | |
| 1192 | [permissions] |
| 1193 | allow_shell = false |
| 1194 | trust = false |
| 1195 | ``` |
| 1196 | |
| 1197 | Select it with `agent(action: "start", profile: "reasoner", prompt: "...")`. |
| 1198 | The provider must also be configured in `config.toml`. The receipt names the |
| 1199 | resolved profile, its personal/project origin, provider/model and effective |
| 1200 | reasoning effort. Effort is normalized to the selected model's supported tiers; |
| 1201 | an explicit `thinking` request overrides the saved preference. |
| 1202 | |
| 1203 | `allow_shell` and `trust` belong under `[permissions]`, not at the top level. |
| 1204 | A profile cannot grant `allow_shell = true`, `trust = true`, or disable approval. |
| 1205 | Use the appropriate `base_role` for the task; the parent session's live policy |
| 1206 | remains the authority ceiling. These profile fields are not a way to grant |
| 1207 | additional access. |
| 1208 | |
| 1209 | A malformed, unreadable or duplicate profile now causes an explicit selection |
| 1210 | error, including when its name matches a built-in role. It never silently |
| 1211 | substitutes a lower roster layer. Repair the file and retry; profiles are reloaded |
| 1212 | for each launch. `agent(action: "roster")` reports affected profile identities and |
| 1213 | paths in `profile_load_issues` without exposing parser excerpts. Other valid |
| 1214 | profiles remain available, and a valid project override still wins over a broken |
| 1215 | personal definition. Fleet run creation performs the same check before storing |
| 1216 | a run or launching workers. |
| 1217 |