--- name: orchestration description: Delegate work to subagents safely and efficiently - follow the measured default batch workflow (plan once, builders.min_per_area to builders.max_per_area writing builders per independent area, default 2-4, in worktrees, fresh audit per item, one release per batch), decide how many subagents to run, pick model and effort per role from the active model preset (credo-preset.sh stage, with its attempt chains), keep parallel tracks on disjoint files (item `touches:` overlap check) and within machine resources (resource gate, `heavy:` items), give each code track a set-up git worktree (hydra or native, automatic), monitor them without flooding your context, inherit security to every subagent, and use return-and-resume so a subagent can ask a question and continue with full context. Use whenever you are about to spawn one or more subagents, run work in parallel, or coordinate delegated tasks. Applies to any agent that delegates, including subagents that spawn their own helpers. --- # orchestration How to delegate work to subagents so results come back correct, parallel work does not collide, and the delegating agent's context stays lean. This is the reusable delegation core; the session skills reference it instead of restating it. ## When this fires - You are about to spawn a subagent for any non-trivial task. - You have two or more independent tasks that could run in parallel. - You are coordinating or monitoring already-running subagents. - A subagent returns needing a decision, and you must route the answer back. ## Delegation-first Prefer delegating substantive work to a subagent over doing it inline in the main context. The main agent orchestrates: it splits work, dispatches, integrates results, and commits. Reserve the main context for coordination and user interaction, not for large reads or long builds that a subagent can carry. ## How many subagents (situational, no colony rule) - The delegating agent decides the count based on the actual work. For a build batch the measured default is "Default batch workflow" below; beyond that there is no rule to always fan out wide. Large colonies are expensive; use them only ad hoc when a specific task genuinely benefits. - Parallelism is wanted. Writing builders run per independent area, at least `builders.min_per_area` (default 2) and at most `builders.max_per_area` (default 4), both in the credo config. They are further limited by (a) file overlap (`touches:`, below), since items that touch the same files never run in parallel, and (b) the resource gate (below). - Read-only agents (explore, research, audit, verify, tests, deploy, also clarify) have no fixed limit. They write no files, so they need no overlap check (the resource gate still applies to every start). ### Idle capacity (passive and autonomous mode) In passive and autonomous mode the main agent leaves no idle capacity. After every agent result and every owner message it starts builders for buildable `2_go` items with disjoint files, up to `builders.max_per_area` per independent area (overlap check and resource gate as always). Active mode has no idle-capacity rule. ### Speed orders (fastfast) and the builder cap fastfast skips audit, full suite and verify and moves the item to the FRONT of the build queue. The builder cap (`builders.max_per_area`, or a lower cap in the repo's `.credo/RULES.md`), the same-files-never-parallel rule (item `touches:` overlap) and the resource gate normally stay in force. One exception: a fastfast item MAY get ONE extra builder slot above the cap. - The main agent grants it alone only when the case is clearly simple: (a) its `touches:` do not overlap any running builder, (b) no migration and no shared hot file, (c) a small, bounded change. - In doubt it asks the owner first (Ask tool in an interactive session, naming the running builders). In an autonomous run with the owner absent it does not ask: the item waits for the next free slot (it may jump ahead of queued items, never stop a running builder). - The resource gate always stays in force. Builders of a fastfast item run only the relevant/changed tests; the full suite runs at its usual point ("When the full suite runs" below; only at the release when DOGMA-PERMISSIONS §8eyz is `[x]`). ## Default batch workflow (measured) The default for building a batch of `2_go` items - the best workflow measured so far, in two unattended benchmark runs on real items. The numbers are current measurements and may be tuned; values marked tentative have too few trials yet. Deviate only when the work clearly calls for it, and say why. 1. **Cut the batch once.** The task agent cuts its own batch from `2_go/` (credo `role-task`, "Where the work comes from"). The plan role never hands out batches; it only reports that new GO items are ready (credo `role-plan`, "No batches handed out"). Order: an explicit owner order first, else the lower item id first. A planning subagent may analyse the cut, but the task agent decides it. Order by dependencies: tooling, then shared foundations, then features. Cut batches by SHARED SURFACES, not only by files: two items that each added an element to the same UI bar conflicted although they touched different modules. Central registry files (command, route, menu or plugin registries, shared indexes, a single CHANGELOG) are shared surfaces: items touching the same one run sequentially or in one bundle. Better still, avoid the shared surface: prefer fragment files (one `changelog.d/` fragment per item, assembled at release) and self-registration (auto-discovery instead of a central list), so parallel items never edit the same registry file. Tricky items (algorithms, detection, quality or numeric results) get their acceptance measurement (data set + target value) into the DoD at this step, BEFORE any build (credo `items`, Success Criteria). 2. **Build in parallel: `builders.min_per_area` to `builders.max_per_area` writing builders per independent area** (default 2-4, credo config), each in its own worktree (below). A bundle is 2-3 small, related, low-risk items in one worktree with one audit; it counts as one builder. Measured: 3-5 parallel builders cut wall time from about 120 min to 15-22 min per item. Above 4-5 builders shared resources become the limit (one browser automation, one test runtime, the 5h budget). The overlap check and the resource gate below still apply. 3. **Audit every item** with a fresh subagent that reads the source, runs the tests and fixes small findings itself ("Delegating audit subagents" below). After a MAJOR or FAIL that the auditor does not fix itself, a FRESH fix agent takes over (never a resumed builder); fix rounds follow the preset stage ladder ("Fix rounds after a failing audit" below). Not optional. A MAJOR defect was found in 14 of 18 single items (run 1) and 7 of 12 (run 2); in run 2 no single item passed its first audit. 4. **Merge as audits pass**, one branch at a time. **One release per batch when a release is due** (automatic only with `release.auto`), with ONE full test suite run before it: it caught 3 bugs that every changed-only test run had missed. After the release, run the worktree cleanup once; the same checkbox rule as at item close decides (credo `items` skill, "Worktree cleanup at item close"). 5. **Budget gate** before the batch and before each heavy step: credo `budget` skill, "Batch budget gate". Stop each agent right after its final report (TaskStop) - leftover agents and test servers keep burning budget (owner rule). ### When the full suite runs The repo's `DOGMA-PERMISSIONS.md` (repo root) decides; read it before the first merge or release of a batch and follow it. - If `§8eyz` ("run ALL tests only at release") is `[x]`, the full suite runs ONLY at the release - the commit that bundles several items with the version bump, never a tag. Not at a merge, not per item, not per builder. - If `§8eyz` is `[ ]` or the file is missing, the full suite runs where dogma places it (stage `all` from `§ly5v`, the Final Verification step), else once before the batch release (step 4 above). - In both cases builders and per-item audits run only the relevant/changed tests (dogma `relevant` stage, else the changed tests). ### Full check only in the main agent - A builder or reviewer never runs the project's full suite or full check (dogma stage `all`, a `--full` flag, "all tests"). It runs the tests of the modules it touched plus the project's fast check (dogma `relevant`, read-only via dogma's `scripts/test-commands.sh get relevant`) and reports. Never write a full-check line into a build or review brief, also not when the repo's `.credo/RULES.md` is silent. - The main agent merges the finished items in a batch and then runs ONE full check (where "When the full suite runs" above places it), not one per builder. - Parallel builders whose checks share a serialising lock (a `flock`, a single test DB or device) run one after another anyway: cap the number of parallel builders at what that lock can serve (usually 1-2 checks at a time), treat a long lock-bound check like a heavy item (`heavy: true`, below), and still gate every start with `credo-resource-check.sh`. - The spawn hook warns (context + visible line, never a deny) when a build, review or hard brief contains the project's `all` stage command, a full-check command from a `.credo/RULES.md` line about the full check, or a marker (`--full`, "full suite", "full check", "all tests"); negated or main-agent clauses stay silent. Fix the brief and re-spawn. Off with `CREDO_BRIEF_CHECK=0`. - No separate queue watchdog: lock paths are project-specific, so a generic one is not cheap. Long waits stay visible through the subagent rule "bounded wait or report blocked on X" and the background guard (no background work outlives a report). ### Brief rules for builders and auditors Add to every builder and audit brief (besides the item path, the main-checkout path and the security block): - In its OWN worktree the agent commits on its branch; push, merge and release stay with the main agent ("Parallel safety" below). Say so explicitly - a generic "subagents never commit" rule otherwise stalls it. - Every new CLI command or flag gets its GUI counterpart in the same item, and vice versa, where the project has both. - Tick only fully met DoD points, never with a caveat. - Before reporting done, the builder runs an adversarial self-check ("try to break it": edge cases, bad input, failure paths, a second run) and lists in its report what it tried; for a tricky item it also measures against the acceptance measurement in the DoD and reports the value (credo `items`, Build-completion gate). - A builder receives only the universal-prompt and its stage's subagent-prompt, not the mainagent-prompt. When it may decide agent-owned questions, the main agent appends the output of `"${CLAUDE_PLUGIN_ROOT}/scripts/credo-preset.sh" mainagent --field prompt` to the brief (a repeated universal-prompt is harmless). - Questions that come up during the build follow the agent decision rule (credo `items`, "Clarify owner and the agent decision rule"): the builder decides uncritical ones itself per the mainagent-prompt in its brief and logs them in the item History; it returns `{status: needs_decision, question}` only for the escalated ones (the user's taste or preference, deleting user data, installs beyond the item's `## Freigaben`, money beyond an approved budget, safety, a change to the verbatim requirement, and points the preset says to note and present). Items it creates (slices, follow-ups, build questions) get `clarify_owner: agent`, `parent: ` and a `created by agent` first History line; while the parent is not GO'd they stay human-owned, so a not yet GO'd user item is never sliced into agent-GO'able children. - Builders run the fast check (dogma `relevant` stage, else the changed tests), not the full suite. An audit of a branch touching shared core files runs the whole core test folder. - Background work is allowed, but never outlives the report. A subagent may run background jobs (`run_in_background` Bash, Monitor, background agents) to work in parallel; before its final report it stops every background task it started that is still running (TaskStop / kill) and never finishes with own background work alive - each one that ends later wakes the finished agent again and floods the main agent with notifications. Waiting on a queue or lock: a bounded foreground wait (with a timeout) or report "blocked on X", never an endless poll loop. The SubagentStop hook (`credo-subagent-bg-guard.py`) lists own background tasks still running and refuses the finish, at most twice per agent. This holds for every subagent brief, not only builders and auditors ("Monitoring without context flooding" below). - Browser tabs never outlive the report either. The Playwright browser is shared and lives in the main session: an agent that opens a tab (or browser context) closes it before its final report (`browser_tabs` close; `browser_close` when it opened the browser), stops its own verify server and says so in the report. The same SubagentStop hook lists tabs it opened and did not close and refuses the finish (same two-block limit, fail open). - No-block commands, in every subagent brief (huge commands are error-prone, often stopped by hooks or review prompts and stall an unattended run; the goal is to steer, not to block work): no long inline code (`python -c`, `node -e`, `perl -e`, `ruby -e`, `bash -c`, `powershell -Command`, a heredoc or pipe into an interpreter) - split the work into several smaller commands (allowed), or Write the script (.py/.sh/.ps1) to the session TMPDIR (`$TMPDIR`, normally `/tmp/credo-tmp-//`) or scratchpad and run it in a separate call with a literal path (PowerShell from WSL: `powershell.exe -File "$(wslpath -w )"`); delete each throwaway script once it is no longer needed with `python3 /scripts/credo-cleanup.py own-rm ` (no prompt for the session's own TMPDIR and scratchpad files, for the main agent and its subagents alike; a file changed in the last 2 minutes is only reported, the done-gate purge takes it later); never write and run a file in the same command; no `VAR=$(...); $VAR/script` calls, literal paths only; multi-file edits with the Edit tool per file and a literal path (or one literal `sed` per file), never `for f in ...; do sed -i ... $f` or any `$var` as a target path (more readable, reviewable, and it passes dogma without a prompt); read files with the Read tool (no `cat` loops to dump sources), no for-loops over files, redirects (`>`, `>>`) only into the session TMPDIR or scratchpad; `./node_modules/.bin/` instead of `npx` for an installed tool; Playwright `browser_run_code` with the `filename` parameter for long code. The SubagentStart inject carries the same block and the PreToolUse inline guard denies inline code over `guards.inline_code_max` characters (default 1500), but the brief names it anyway, and the main agent follows it itself. - Every brief carries the repo's mandatory brief lines from `.credo/RULES.md` (for example a path-safety note), copied verbatim. A repo's `.credo/RULES.md` overrides these defaults, and the subagent reads that file first. - Blocker and owner-decision claims are proposals. The main agent reads the source the subagent cites (file:line or command output) before it asks the owner or declares a blocker, especially for a claim from a model below its own. It also checks the requirements log, so a point the owner already decided is never asked again (credo `items`, "Never re-ask a decided point"). ### Fix rounds after a failing audit (default) - **Fresh fix agent.** After an audit with a MAJOR or FAIL verdict that the auditor did not fix itself, spawn a FRESH fix agent. Its brief holds only the audit findings (report path), the branch / worktree state and the test commands - plus the item path and the security block as in every brief. Never resume the builder's context for a fix round: one item needed about 1.45M builder tokens over 3 resumed rounds. - **Stage ladder, no fixed fail count.** Fix rounds follow only the active preset stage ladder. The active preset (always one: the configured `preset:`, else the built-in `balanced`) is the only source of the escalation stages for fix rounds: the model, the effort, the attempts per stage and when back-to-human comes. Each fix round is the next attempt of `credo-preset.sh stage ` ("Model presets" below). Each stage allows its configured attempts (`until-done` has no attempt cap; the budget caps stop it), then `back-to-human`. Skill texts and audit agents keep no fail count and no brake of their own. While the ladder has attempts left, whether another fix round runs is the main agent's decision, never an owner question; an audit subagent never declares a brake itself, it reports the attempt count. The item goes back to the owner only at back-to-human or for a genuine owner decision (the escalation list and the Named-Decision-Test, credo `items`). The until-done hand-back on the same failure twice without progress is part of the preset semantics. By default the same finding returning unchanged twice is an early hand-back as well; a repo's `.credo/RULES.md` can switch that default off. For the hand-back, `credo-item-move.sh clarify` sets `clarify_owner: human` and logs it, with the audit reports named in the History (`--keep-owner` only for an agent-internal re-clarify); say so in the next reply or report. - **Only DoD findings get fix rounds.** MINOR and NIT findings the DoD does not order and residual cases start no fix round. The auditor fixes them once, or they go into the project's collection item (credo `items`, "Scope of an item"). - **Polish items** (`polish: true`, credo `items`, "Polish items"): no fix round loop. One light audit, one best-effort fix pass, leftovers into `## Verify`, then done. The model and effort stay as the user set them. - This is not return-and-resume (below): that keeps a subagent's context for a mid-task decision; a post-audit fix round always starts fresh. ### Being measured (not default yet) - Merge conflicts on central registry files: one run needed 5 resolver agents and about 400k tokens. Cutting batches by shared surfaces and moving to fragment files (step 1) is the current mitigation. ## Parallel code tracks: touches and resource gate ### (a) File overlap - `touches:` An item may carry the optional frontmatter field `touches:` - a list of paths or globs the item will likely edit (credo `items` skill). The plan / clarify agent sets it, at the latest at GO. - It is GUIDANCE, not a contract. Until implementation it is the source of truth for planning parallelism. - Before spawning builders, run `"${CLAUDE_PLUGIN_ROOT}/scripts/credo-touches-check.sh" ...` over the candidate items. Exit 0 = no overlap, 3 = overlapping pairs printed (`--json` for a structured result); items without `touches:` are listed as `unknown`. - Overlapping items run SEQUENTIALLY, never in parallel. - Right before spawning, quickly re-check that the listed paths still exist and fit (files may have been renamed or moved since planning). If that check disagrees, the main agent's re-assessment wins: it updates the item's `touches:` / plan instead of sending a subagent down a wrong track. - Items without `touches:` (`unknown`): the main agent classifies them itself, best-effort, from the item text and plan. Parallel is the default; run them sequentially only in serious doubt, or when clearly foreseeable conflicts that are not easy to resolve would occur. ### (b) Resource gate - `credo-resource-check.sh` Before every agent start, in every session mode, run `"${CLAUDE_PLUGIN_ROOT}/scripts/credo-resource-check.sh"` (add `--disk-gb --path ` when the item has `disk_gb`, see "Disk space" below). It prints `ok` (exit 0) or `wait:` (exit 5). - It checks CPU (the 1-minute load per CPU) against `resources.max_busy_percent` (credo config, default 94) and RAM (the used share) against `resources.max_ram_percent` (default 80). Under WSL it also checks the Windows host's RAM and CPU load, since that is the owner's machine. At a limit or above it answers `wait`. There is no agent-count gate. The check runs before every start, however many agents are running. - On `wait`: start no new agent. Re-check when the next running agent finishes (its completion notification) - no polling loop, no sleep loop. - Fail-safe: unreadable system values never block (`ok` plus a note on stderr). ### Disk space - `disk_gb` and the reserve Free disk is checked at every start too, because a full drive stalls every track. Pass the item's `disk_gb` (credo `items` skill) with the check: ``` "${CLAUDE_PLUGIN_ROOT}/scripts/credo-resource-check.sh" --disk-gb --path ``` - `--path` is any path on the target drive (the repo or worktree the track writes to). - The free space must cover `disk_gb` plus `resources.disk_reserve_gb` (credo config, default 3 GB). An item without `disk_gb` needs only the reserve. - On `wait:low free disk ...` the item does not start. It stays in `2_go` and is retried when the next running agent finishes, like a RAM wait (no polling loop). - Autonomous mode: the first disk wait of an item sends ONE ntfy "waiting for disk space" per item (`credo-ntfy-send.sh`, credo `session-autonomous`, "Per-task and per-question ntfy", at `default` priority). Further waits of that item stay silent. - Fail-safe: an unreadable disk value never blocks (`ok` plus a note on stderr). ### Heavy items - `heavy: true` An item with the optional frontmatter `heavy: true` (model or benchmark tests, large downloads): - never runs in parallel to another heavy item, and - like every start, starts only when `credo-resource-check.sh` says `ok`. ### Worktrees for every code track (hydra or native, automatic) Every code track that works in a git worktree follows this flow, also a single isolated build track, not only parallel ones. Before ANY worktree run, decide the flow (once per batch or track, without any user command): ``` "${CLAUDE_PLUGIN_ROOT}/scripts/credo-worktree-flow.sh" # flow=hydra|ask|native, setup=