Multi-Agent Orchestration
PM-style multi-agent local execution orchestration. It answers one question: how multiple agents can work in parallel in the same repository using independent worktrees/sessions, with the current main session acting as a PM that can inspect, wrap up, and control quota consumption.
PM is the main session responsible for decomposition, task assignment, acceptance, and wrap-up, not bound to specific products. Codex can act as a PM to coordinate Claude Code or OpenCode workers; Claude Code can also act as a PM to coordinate Codex or OpenCode workers. The Skill only defines protocols for roles, isolation, startup, status, and wrap-up.
1. Boundaries
Use this Skill:
- When 2 or more local Agents/Codex/Claude sessions need to work in parallel.
- When tasks require independent worktrees, independent branches, and independent PRs.
- When the PM session needs to start, monitor, correct, and wrap up multiple workers.
- When simple tasks need to be routed to Claude Code, Codex, OpenCode, or other CLI workers to control token consumption of the main session and quota consumption of different models.
Do not use this Skill:
- For single short tasks, single-file modifications, or one-time Q&A.
- For task status management, responsible person tracking, or dependency management: use .
- For branch naming, commit formatting, PR merge, push, or conflict resolution: use .
- For external Agent email triggers: use corresponding external collaboration/email Skills.
2. Execution Modes
| Mode | Applicable Scenarios | Default Isolation |
|---|
| PM Direct Processing | Lightweight, low-risk tasks with no parallel value | Current workspace |
| Same-host Subagent | Narrow-range analysis, review, or local revisions | Usually no new worktree |
| Claude Code Agent Teams | Claude Code acts as PM and requires team-style collaboration | worktree + branch |
| tmux Independent CLI Session | Requires cross-product workers, long context, independent quota, or independent processes | worktree + branch |
| Claude Code agent view | Needs to use official backend sessions, peek/reply/attach, and overview | Can use Claude official /, or manual worktree |
| ACP adapter | Project provides stable adapter and requires structured event flow | Determined by adapter, still recommends worktree + branch |
Priority is determined by project rules. If the user or project explicitly requires tmux/independent session/starting workers, enter the anti-escape gate.
2.1 Anti-Escape Gate
Mandatory session trigger conditions:
- User explicitly mentions , , , ,
you act as PM/orchestrator
, , or project rules require tmux/independent session.
- Tasks require independent quota, long context, continuous background operation, manual takeover, or simultaneous execution of 2 or more local workers.
After triggering, the PM must complete the startup gate before any business implementation:
- Create or confirm the isolated worktree, semantic branch, and Session Context path.
- Start the tmux session; Claude official can be used as a dedicated equivalent entry for Claude.
- Use // to verify session survival, and confirm that the pane cwd or agent cwd points to the target worktree.
- Send a Bootstrap-only prompt or Full worker prompt to the worker, which must include Branch, Worktree, Session Context, Runtime Profile, Allowed files, Forbidden files, and verification commands.
- Confirm that appears within 1-2 minutes; if not, only send checkpoint-only corrections or restart the worker, do not directly take over business implementation.
Downgrade rules:
- When tmux is explicitly required, Agent Teams, Subagent, or PM Direct Processing are not equivalent substitutes; unless the user explicitly agrees to downgrade.
- When independent session is explicitly required but tmux is not specified, tmux is used by default; Claude official is available. Agent view/Agent Teams can only be substituted if they can prove independent background sessions, independent cwd/worktree, and inspectable status.
- When the gate fails, the PM must report the blockage and failure points; only orchestration layer files such as worker prompts, Skill documents, monitoring scripts, or local collaboration configurations can be directly modified.
- If the PM triggers an exception to directly process business code, the final report must state the exception reason, specific gate failure points for not using the session, and whether the user approved the downgrade.
2.2 Roles and Backends
Clarify roles first, then select backends:
| Role | Responsibilities | Who Can Serve |
|---|
| PM | Reads task sources, groups tasks, starts workers, inspects, accepts, merges, and wraps up | Current Codex, Claude Code, OpenCode, or other main sessions |
| Worker | Completes limited tasks within the specified worktree/branch | Claude Code, Codex, OpenCode, custom CLI, shell scripts, future ACP agents |
| Reviewer | Checks diffs, tests, scope, and risks | PM, another worker, code-review subagent |
PM Proxy Discipline:
- If the user explicitly requires the current session to act as PM/orchestrator/multi-agent orchestrator, the PM does not directly write business code by default; if §2.1 is triggered simultaneously, the startup gate must be passed first.
- The core value of PM lies in token efficiency, model/quota routing, multi-threaded execution, scope control, and acceptance wrap-up; task implementation is prioritized to be assigned to worktree workers, independent CLI sessions, Agent Teams, or Subagents.
- Exceptions where PM can directly modify code: extremely small tasks with no parallel value, user explicitly requires PM to do it directly, worker fails to correct continuously and only narrow-range wrap-up remains, or immediate repair of orchestration documents/configurations generated by PM itself. Under explicit tmux/independent session requirements, these exceptions must first obtain user confirmation or record gate failures.
- If the PM bypasses exceptions to directly modify code, the reason should be explained in the final report; regular implementation should be completed through worker outputs, PM corrections, and PR reviews.
Backend Selection Rules:
- It doesn't matter what the current main session is; by default, "who starts the orchestration, who is the PM".
- When needing to start Claude Code via a third-party Anthropic-compatible API, select Claude Code as the worker backend; this is the default quota mode for Claude Code workers.
- Only when the user explicitly requires Claude subscription/OAuth, use profiles and clear third-party provider environment variables.
- When needing to consume Codex/OpenAI quota or use Codex configurations, select Codex as the worker backend.
- When needing to consume configured providers/models of OpenCode, or use OpenCode's / capabilities, select OpenCode as the worker backend.
- When needing to consume quota from WorkBuddy/CodeBuddy or QoderWork platforms (reuse desktop login state, zero API Key, includes daily free models), select / as the worker backend; this is a cross-tool exception (§2.3), suitable for quota diversion or evaluation fan-out. Both are uniformly generated by
render-runtime-profile.sh
(including Qoder's SDK variable clearing, CodeBuddy's ); external CLI backend worker spawn uses snapshot-copy-into-worktree (DEC-037) by default for self-containment.
- Other Agents can also serve as custom CLI workers as long as they can be started with one command and read/write files in the specified cwd.
- When stable process lifecycle and manual takeover are required, prioritize ; when §2.1 is triggered, is the default execution layer, not a suggestion that can be silently skipped.
- ACP is only enabled when the adapter is stable and can output structured status; do not add uncertainty for the protocol when there is no adapter.
Backend → Default Model Quick Reference (same-host workers still prioritize §2.3; the following defaults only take effect when PM actively cross-tools or the user explicitly specifies the backend):
| Backend | Default Model (Preferred → Alternative) | Applicable Scenarios | Notes |
|---|
| Claude Code | See personal config (regular/high-end vs simple+multimodal, route by task not rotation) | Default main host; concurrency limit for the same provider see , overflow to cross-platform backend | Detailed provider mapping see config/claude-provider-registry.example.json
|
| Codex | (See §2.4 codex_policy) | When explicitly required by user | High intelligence but expensive quota, not actively assigned by default |
| OpenCode | opencode:<provider>/<model>
| OpenCode has available quota | Follow OpenCode profile |
| (QoderWork CN) | See personal config backend_model_routing.qoderclicn
| User actively requests / main concurrency is full and overflows (cross-platform/cross-quota to avoid concurrency) | SDK variables need to be cleared |
| (WorkBuddy/CodeBuddy) | See personal config backend_model_routing.codebuddy
| User actively requests / main concurrency is full and overflows (cross-platform/cross-quota to avoid concurrency) | Default with |
This table does not list specific models—model and framework selection is personal preference (each person has different available provider/platform quotas). Specific models are all in
config/orchestration-personal.json
(yours) +
(general template); this table only lists backend capabilities + model configuration field locations, and if missing, PM reads according to §2.4 personal preferences.
Environment/Profile Discipline:
- When starting workers, PM must explicitly write , settings/profile path, model source, and key environment variable handling methods, do not assume that Claude Code, Codex, and OpenCode share the same shell environment.
- For Claude Code third-party API providers, it is recommended to use the provider registry:
config/claude-provider-registry.example.json
describes , /, , and for multiple providers; the real registry is placed in ignored local files, and real keys are prioritized in environment variables. The old single provider --settings <*.settings.json>
path is retained for compatibility.
- Claude Code third-party API provider profiles must retain //default model mapping; do not apply OAuth clearing commands. The registry mode dynamically generates these env via wrapper, eliminating the need to maintain a settings file for each model.
- Claude Code third-party API providers must explicitly pass , and the settings file should also include /. Only passing is not enough to isolate the user-level or inherit in the environment; actual tests show mixed states where settings point to GLM, but the interface and actual default model still display MiniMax.
- By default, Claude Code third-party API providers generate the
scripts/claude-provider-env.sh
wrapper command via scripts/render-runtime-profile.sh
. The wrapper first clears inherited Claude/Anthropic provider routing variables, then imports env from the target settings JSON, or parses env from the provider/model intent in the registry; supplements /, sets CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1
, and injects --setting-sources project,local
into to avoid provider/model pollution from user-level for this worker.
- Only use
--no-provider-env-isolation
to bypass the wrapper during troubleshooting; PM must record this exception in the Wave plan and of , and check the banner/STATUS provider after startup.
- Only Claude Code subscription/OAuth profiles clear third-party provider environment variables to avoid mistakenly using external APIs.
- Codex/OpenAI workers, OpenCode workers, and custom CLI workers use their respective profiles; do not treat Anthropic provider environment variables as general worker environments.
- Worker bootstrap must write
which claude/codex/opencode
, version number, cwd, key profile name, and runtime information such as into , making it easier for PM to judge whether "different environments" affect the task.
2.3 Same-Host Priority: Do Not Default to Cross-Agent Tools
By default, let workers run in the same Agent tool as the PM: if Claude Code acts as PM, use Claude Code workers; if Codex acts as PM, use Codex workers; same for OpenCode. Do not default to routing workers to another Agent tool for "quota diversion". This takes precedence over the multi-backend routing suggestions in §2.2.
Why same-host by default:
- Same-host workers share a set of auth/settings/context conventions, with the lowest startup and troubleshooting costs; cross-tool introduces different profiles, different env, different CLI behaviors, increasing orchestration layer uncertainty.
- The core benefits of multi-agent are parallelism + scope isolation (independent worktree/session) + PM wrap-up, not "cross-tool". Parallel value comes from independent worktree/session/quota lane, regardless of whether tools are changed.
- Cross-tool is only used when there are clear reasons (see below), not by default.
Auth Conventions for Same-Host Workers (important, avoid environment misjudgment):
- When Claude Code PM starts Claude Code workers, the worker process inherits the PM's provider env (third-party API's /, or OAuth session). Even if the in the target worktree is empty or default, the worker can run using the PM's provider, no additional required.
- Only when multiple Claude Code workers need to be assigned to different providers (e.g., some use minimax, some use glm), use different settings files to distinguish slots; at this time, all are still Claude Code workers, no cross-tool.
- The standard for judging "whether the worker has obtained the provider env": worker bootstrap writes available version and provider source into ; PM decides whether to supplement settings or downgrade only when seeing empty provider source or 401/403 errors, instead of defaulting to cross-tool first.
When Cross-Tool is Allowed (exception, not default):
- The current host provider's quota/rate limit/concurrency slots are insufficient to support this Wave, and cannot be solved by "reducing concurrency/splitting to next Wave".
- A certain worker task is obviously more suitable for the model capabilities of another tool (e.g., ultra-long context research, specific code stack).
- The user explicitly requires mixed workers (e.g., "Claude Code acts as PM, rewrite workers use Codex").
Hard Requirements for Triggering Cross-Tool: PM must write in the Wave plan why cross-tool is used, each worker's backend/profile/auth source, and additional troubleshooting points brought by cross-tool. The provider slot allocation in §3.1 still applies, but slots are all in the PM host tool by default; cross-tool slots are explicit exceptions that need to be marked in the Wave summary.
2.4 Personal Routing Preferences (User-Level, Customizable by Anyone)
§2.2/§2.3 provide skill-level default rules, but each user's "main/rotation/which backend for which model" is a personal preference that should not be hard-coded into the skill. Mechanism:
- Configuration Path:
config/orchestration-personal.json
(in the skill directory, but gitignore and not stored in the repository—each person places their actual preferences locally; do not commit to the repository to avoid solidifying personal models/frameworks into the general skill. is the general template stored in the repository).
- Template Path:
config/orchestration-personal.example.json
(schema documentation / clean template for fork users).
- Reading Timing: PM reads
config/orchestration-personal.json
before assigning workers; if missing, falls back to defaults.
- Scope: Only declares "preferences" (host, model rotation, codex policy, default model for cross-tool backends), not real tokens/keys/endpoints—those are still managed by
config/claude-provider-registry.*.json
.
Field Definitions (aligned with example schema):
| Field | Meaning | Default Fallback |
|---|
| PM's main host tool (the Agent tool you use: //) | |
main_force.task_routing.high_end
| Model for regular/high-end tasks (self-selected) | None (required) |
main_force.task_routing.simple_multimodal
| Model for simple tasks + multimodal/image interpretation (self-selected) | None |
main_force.task_routing.default
| Fallback when task type is unknown (usually = high_end) | None |
concurrency.max_per_provider
| Concurrency limit for the same provider (try to keep low to avoid rate limit affecting other tasks) | User-defined (example 3) |
concurrency.overflow_strategy
| Which backends to overflow to when exceeding the limit (different platforms/quotas to avoid concurrency) | User-defined |
| / | (backward compatible) |
backend_model_routing.<backend>.default_models
| Default models for cross-platform backends (preferred first); = CLI name you commonly use | Empty → cross-platform overflow not enabled |
Codex Hard Rule (the most important one in personal preferences):
- When
codex_policy.policy = "explicit_only"
, PM does not actively route any workers to Codex; only when the user explicitly says "use Codex" in the current round is it unlocked, and written into the Wave plan.
- This is independent of §2.3 same-host priority: even if §2.3 same-host tool is Codex host, PM still judges whether to assign workers to Codex according to this policy.
- To restore Codex availability by default, change .
Relationship with §2.2/§2.3/§3.3:
- §2.2 backend table → §2.4 personal preferences → §3.3 project-level provider slot defaults → final backend/model selection. Priority: §2.3 (do not actively cross-tool) overrides §2.2 (multi-backend), §2.4 personal preferences override §2.2 default model table, §3.3 project-level provider slot plan overrides §2.4 general host.
- §2.4 field naming is deliberately not conflicting with §3.3 project-level provider slots: project-level slots write "which slot to use for which worker in this Wave" (including model, max_concurrency); §2.4 writes "my personal preference for default host/which backend for which model". The former is implemented in the Wave plan, the latter in PM's task assignment decisions.
TODO (Future Enhancement):
scripts/render-runtime-profile.sh
automatically reads personal config (parses
→ default
, parses
→ whether codex backend is allowed, parses
backend_model_routing.<backend>.default_models
→ cross-tool default) is currently
not implemented; this time only implements configuration + documentation + manual compliance by PM, avoiding introducing new uncertainty by modifying scripts without supervision. When needed, start a new worker, do not modify it casually in PM tasks.
3. Standard Process
- Read Task Sources and Project Configurations: If the project provides
.claude/orchestration.config.json
or equivalent configuration, first read trunk, task sources, verification commands, copyable configurations, and hook boundaries; then use to judge executable items, dependencies, and ownership.
- Group Tasks First: Do not default to one worker per Issue. Tasks with overlapping file scopes, belonging to the same chapter/module, or having dependency chains should be grouped and executed sequentially.
- Judge Parallel Safety: Only split into multiple worktrees for parallel execution when file scopes are clear, no shared migration/lock files/schema, and acceptance criteria are independent.
- Judge Whether to Trigger Anti-Escape Gate: As long as the user or project explicitly requires tmux/independent session/starting workers, execute according to §2.1; do not write business code before the gate is passed.
- Select Worker Backend and Runtime Profile: Select Claude Code/Codex/OpenCode/custom CLI/shell/ACP according to task complexity, current quota, model preferences, and whether independent processes are needed.
- PM Creates Isolated Environment: By default, PM creates worktree, branch, and session context directory, then passes the path to the worker; only when Claude Code official Agent Teams/agent view explicitly uses its own capability is Claude Code allowed to create, but PM still needs to verify the branch, path, and isolation status.
- Start Worker and Verify Gate: Give each worker clear target files, allowed modification scope, verification commands, session context directory, commit and PR requirements; confirm session survival, correct cwd/branch, appears, or bootstrap correction has been sent.
- PM Inspection: Prioritize viewing
.claude/agent-sessions/<session-id>/STATUS.json
, , , git status, commit/PR status; for Claude official Agent Teams, prioritize reading and , with , tmux pane, or agent view as fallback observation. Intervene when off-topic, blocked, scope expanded, or no phased commits.
- PM Accepts Instead of Writing: PM performs scope check, test review, and review on worker results; when problems are found, prioritize sending correction instructions or assigning to reviewer/another worker, do not default to modifying business code by yourself.
- Wrap-Up: After the worker commits and opens a PR, PM performs scope check, triggers review, merges and cleans up according to .
- PM Must Perform Practical Verification: Before the worker claims "completion" for any software function modification (regardless of L1/L2/L3), PM must actually start the dev server (Vite dev/Tauri dev/corresponding entry), use Playwright MCP or screenshots to actually open the application, click buttons, switch tabs, adjust windows, input text, and write verification evidence (DOM measurement, key assertions, screenshots) into or corresponding . Claiming "completion" only because typecheck/unit test/lint/build all pass is insufficient—these only prove "code can compile", not "function really works".
3.1 Wave-Based Orchestration
Wave is a group of parallel workers started under the same base ref and same batch of conflict assumptions. It is used to record "how many rounds of parallel execution have been carried out in this project", control concurrency risks, and allow PM to review provider/model performance after each round.
Before starting a Wave, PM must clearly write:
- , base ref, goal, worker list, branch/worktree/session for each worker.
- Type of each worker: (low-risk UI wiring), (shared contract/dependency change), (Rust/Tauri/native dependency), , .
- Runtime profile/provider/model/registry or settings/profile path/quota source/concurrency slot. When there are more than 3-4 workers, do not press them on a single API provider or the same provider key; should divert across Claude providers, Codex/OpenAI, OpenCode, local/OSS profiles.
- Shared risks: , lock files, , , global layout, DEC number, or the same module entry.
- Expected number of PRs, wrap-up order, entry conditions for next Wave.
The number of concurrent workers is not fixed at 3. When file scopes are independent, verification commands are independent, and no shared contract conflicts, the default target can be increased to 4-6 workers; pure documents, translation, i18n, non-overlapping UI wiring can have more. When involving shared dependencies, lock files, Tauri command, global layout, DEC race, or the same module entry, reduce to 1-3 workers and execute in dependency order.
Provider slot allocation is an explicit plan by PM, not automatically guessed by scripts:
- A slot represents a concurrent quota lane:
backend + settings/profile path + provider + model + max_concurrency
.
- For Claude Code third-party providers, it is recommended to distinguish by registry + provider id + model alias, e.g.,
config/claude-providers.local.json
+ ; old paths can also be distinguished by specific settings files, e.g., config/<your-provider>.settings.json
. Real registry/settings files remain locally ignored and not submitted; specific provider/model used see personal config.
- Codex is distinguished by Codex profile/model; OpenCode is distinguished by profile; custom workers specify the actual command source.
- By default, a maximum of 3 workers are placed in the same provider/settings file; only when tasks are low-risk and the previous Wave performed stably can it be increased to 4. When 5-6 workers are needed, prioritize splitting to the second provider or Codex/OpenCode/local profile.
- High-risk tasks (shared contracts, Tauri/Rust, native dependencies, lock files) are prioritized to profiles with the best instruction compliance and verification performance in the previous Wave, and usually only 1 worker is opened per high-risk shared domain.
- If there is only one available settings/profile locally, do not start 5-6 workers to凑 numbers; reduce the concurrency cap to 3-4, and remaining tasks enter the next Wave.
6-Worker Example:
| Worker | Task Risk | Backend | Settings/Profile | Slot |
|---|
| W1 | High | Claude Code | config/<provider-a>.settings.json
| |
| W2 | Medium | Claude Code | config/<provider-a>.settings.json
| |
| W3 | Low | Claude Code | config/<provider-b>.settings.json
| |
| W4 | Low | Claude Code | config/<provider-b>.settings.json
| |
| W5 | Docs/Research | Codex | | |
| W6 | Repetitive Low-Risk | OpenCode/custom | <provider/model or command label>
| |
When wrapping up a Wave, PM records each worker's
/
/
/
/
, and evaluates model/provider performance: Isolation Gate, STATUS heartbeat, commit rhythm, scope compliance, verification pass rate, number of review fixes, diff quality, blockage/hallucination/environment misjudgment. Adjust task allocation in the next Wave based on this evaluation: assign high-risk tasks to profiles with better instruction compliance and engineering reliability, assign low-risk repetitive tasks to profiles with better cost or throughput.
3.2 Goal-Driven Multi-Wave Loop
Orchestration Goal is the PM-level goal loop, used to make multiple rounds of Waves continue to advance until conditions are met. It does not hand all tasks to a single worker; PM still takes the next batch of safely parallelizable items from the task source according to Waves, and workers still only execute their narrow-scope tasks.
Before starting the Goal Loop, PM must clearly write the Goal Contract, template see
templates/orchestration-goal.md
:
- Task source: e.g., , GitHub Issues, issue file in project configuration.
- Success criteria: e.g., no executable pending tasks within the target scope, all started workers enter ///, trunk verification passes, documents are synchronized.
- Autonomy level: (only plan the next Wave), (can automatically start the next Wave), (can automatically review worker results), (merge according to when project rules allow).
- Upper limits: maximum number of waves, maximum workers per round, total workers, budget/time, provider concurrency slots.
- Continue conditions and stop conditions.
PM can use Claude Code/Codex's
in supported hosts to wrap the PM loop, but
only responsible for making PM continue to execute the loop, not replacing the worktree, tmux, checkpoint, review, and merge gates of this Skill. The Goal prompt must clearly state "PM does not directly implement business code; implementation is still completed by workers".
After wrapping up each Wave, PM decides whether to continue automatically in the following order:
- Read the task source, close completed items, identify executable pending tasks, dependencies, file scopes, and shared risks.
- Confirm that the current Wave has no unprocessed failed/blocked workers, unaccepted PRs, base drift, conflicts, trunk verification failures, or sensitive/destructive operations.
- Adjust concurrency based on the provider/model evaluation of the previous Wave: maintain or slightly increase if cleanly passed, reduce concurrency if conflicts, scope overstepping, verification failures, or rate limits occur.
- If there are still safely parallelizable tasks, create the next Wave; if only high-conflict/high-risk tasks remain, reduce to 1-2 workers or stop to request user confirmation.
- If success criteria are met, write final goal summary and stop.
Automatic Continue Conditions:
- All workers in the previous Wave are , , , or clearly and will not affect the next Wave.
- All merge actions have been processed according to , base ref, local trunk, and remote trunk are consistent or differences have been clearly recorded.
- Required verifications pass; skipped verifications have clear reasons and do not affect the next Wave.
- Allowed/forbidden files for the next batch of tasks are clear, and there are no unresolved shared lock files, schema, global layout, or DEC number race.
- Provider concurrency slots are sufficient, and there is no continuous rate limit, long delay, or degradation of worker instruction compliance.
Conditions to Stop and Report:
- Any worker is , and affects the next Wave, or continuous correction fails twice.
- PR conflicts, base drift, trunk verification failure, unstable tests, insufficient merge permissions, or unclear GitHub/CI status.
- The next batch of tasks requires user product judgment, destructive file operations, sensitive network processing, key/privacy processing, or automatic merge not authorized by project rules.
- Task source is ambiguous, dependencies are not met, file scopes are highly overlapping, or only high-risk tasks such as shared contracts/lock files/Tauri command remain.
- Reach the wave, worker, time, budget, or provider upper limits in the Goal Contract.
3.3 Optional Project Config
Projects can place
.claude/orchestration.config.json
, template see
templates/project-config.json
. This configuration only declares project defaults, does not replace PM judgment, and does not allow silent execution of destructive actions.
Configuration can declare:
- Trunk/base ref, task source, default worktree/session context path.
- Verification commands split by worker type.
- Default provider slot plan, referenced by Goal/Wave startup list.
- Non-sensitive configuration files that can be copied to worktree, e.g., or read-only templates.
- Post-create/pre-merge hook commands.
叠加 with §2.4 Personal Preferences (User-Level vs Project-Level):
| Dimension | User-Level (§2.4) | Project-Level (§3.3) |
|---|
| Path | config/orchestration-personal.json
| .claude/orchestration.config.json
|
| Content | Personal main host, default model rotation, Codex policy, default model for cross-tool backends | Trunk/task source/verification commands/default provider slot plan for this project/hooks |
| Who Writes | User themselves | Project maintainers |
| Who Reads | PM before assigning workers | PM before starting Wave |
| Priority | Low (personal general preferences) | High (project overrides personal) |
Example: Personal preference host=claude-code + model=<your model>; project-level provider slot plan writes "W3/W4 of this Wave use <a certain provider>"—then W3/W4 use this provider, other workers still follow personal preferences. The two do not conflict and should not copy each other; project-level does not write personal preference fields (avoid dotfile into repository).
Configuration Security Rules:
- Never copy , real settings, tokens, keys, cookies, certificates, or account credentials by default.
- only allows non-sensitive files; must stop and report when is hit.
- Hooks are only declarations by default. PM only runs them when authorized by project rules or user explicitly; should display the command before running, and dry-run if necessary.
- does not automatically read project configuration, copy configuration, or execute hooks, avoiding upgrading optional conventions into implicit side effects.
- If configuration is missing or fields are unclear, PM returns to Skill defaults: trunk=, no configuration copied, no hooks run, only use verification commands explicitly listed in worker prompts.
4. Naming Rules
Define once, reference consistently everywhere (hard constraint, tested pitfalls). branch/worktree/session/run-dir/spec must be derived from the
same source, and referenced exactly consistently everywhere (PM Wave plan,
parameters, Branch/Worktree/Session Context written in worker prompt, METADATA.json, regression library
). In actual tests, PM accidentally stripped the
prefix from
, or branch and session name did not match, directly causing worker's Isolation Gate (self-check of
/
git branch --show-current
) to intercept, sentinel to fail to find
, and wrap-up
to verify empty diff. Avoidance:
- PM writes the
{branch, worktree, session, run-dir}
quadruple once in the Wave plan, and all subsequent /correction/wrap-up commands are copied from this quadruple, not re-typed or simplified midway.
- internally derives from a single source: → (worktree-safe) → default
WORKTREE=.claude/worktrees/tmux-<safe_branch>
→ SESSION_CONTEXT=<worktree>/.claude/agent-sessions/<session>
. PM only needs to ensure that the passed and are consistent and complete, and the helper will not decouple worktree from branch.
- The naming quadruple for cross-model/evaluation scenarios includes model identification (see model-aware naming convention of ), and the entire link uses the same , avoiding PM using different abbreviations in different links.
Branch names are for remote collaboration and PRs, must reflect task semantics, do not write execution sources.
text
docs/ch01-agent-intro
research/issue-13-ch08-materials
fix/agent-session-shell
Worktree paths are only for local isolation, should add execution source prefix:
text
.claude/worktrees/tmux-ch01-agent-intro
.claude/worktrees/team-agent-session-shell
.claude/worktrees/subagent-copyedit-ch02
Do not write
,
,
,
into branch names. Branch type prefixes and commit/PR formats follow
.
Creation Example:
bash
git worktree add .claude/worktrees/tmux-ch01-agent-intro -b docs/ch01-agent-intro
git worktree add .claude/worktrees/team-agent-shell -b fix/agent-session-shell
4.1 Session Context Directory
Worker's local status is uniformly written to
.claude/agent-sessions/<session-id>/
in the current worktree (hereinafter referred to as
Session Context), reusing the project's existing
collaboration space, clearly distinguished from Claude Code official Agent Teams status sources.
text
.claude/agent-sessions/legal-ch01/METADATA.json
.claude/agent-sessions/legal-ch01/STATUS.json
.claude/agent-sessions/legal-ch01/RESULT.md
.claude/agent-sessions/legal-ch01/PATCH_SUMMARY.md
Claude Code official Agent Teams is another set of mechanisms: team configuration is in user directory
~/.claude/teams/<team-name>/config.json
, task status is in
~/.claude/tasks/<team-name>/
, inbox is in
~/.claude/teams/<team-name>/inboxes/
. When using official Agent Teams, prioritize reading and writing these official status sources; do not create
in the project to impersonate official teams.
is for PM inspection status, not part of business diff. Both PM and worker must confirm that it does not enter commit/push/PR; if needed, PM ignores it in the local exclude of the corresponding worktree.
5. Worker Prompt Template
Worker prompts should provide sufficient context like starting a subagent: task source, acceptance criteria, allowed files, forbidden files, verification commands, checkpoint protocol, isolation self-check, and PM correction protocol must be clearly written. Do not only give a sentence like "implement a certain function", otherwise workers may expand environment, dependencies, or related technical debts into their own tasks.
The template is placed in
templates/worker-prompt.md
, containing two copyable paragraphs:
- Bootstrap-only prompt: only creates , suitable for the first message of high-latency providers or high-effort models.
- Full worker prompt: organized by Context/Background/Mission/Scope/Deliverables/Process/Verification/Autonomy/Out of Scope/PM Correction, close to the writing style when assigning subagents.
For high-latency providers or high-effort models, prioritize two-stage startup: the first message uses Bootstrap-only prompt to create
Session Context/STATUS.json
and report runtime; after PM confirms the checkpoint, send the Full worker prompt. This avoids workers having no observable status before long thinking.
5.1 Template Usage Discipline (Must Read, Tested Pitfalls)
When assigning workers, PM
must use the Full Worker Prompt skeleton from templates/worker-prompt.md
, and fill business tasks (Issue/task card/
content) into Background/Mission/Scope/Deliverables/Verification fields.
Do not use custom simplified prompts (e.g., only write a BOOTSTRAP.md pointing to business files) to replace the template skeleton—even if the business
file is written in detail, without the hard constraints of the orchestration layer skeleton, workers will still lose control at the process layer.
These paragraphs in the template are hard constraints for worker observability and wrap-up correctness, and omitting them will directly lead to wrap-up failure (the following consequences have corresponding actual tests):
- Isolation Gate: Worker first confirms /, otherwise may modify by mistake in main or wrong worktree.
- Heartbeat cadence (force update STATUS every 10 minutes, even write if no progress): PM relies on to detect silent workers. Omitting it causes workers to write initial STATUS once and never update again, distorting PM inspection signals and making it impossible to judge stuck points.
- Commit Cadence + "commit is a mandatory wrap-up step": Even if the task requires "no push/no PR", workers must first + their outputs. Omitting it causes workers to modify files without committing, and PM verifies empty diff when wrapping up with
git diff --check main...HEAD
(HEAD is still at base, false pass), and PM has to commit for workers. Especially after rebase/reset, reconfirm that changes have been committed.
- Canonical terminal status (literal ): The sentinel state machine matches literal . Omitting it causes workers to write synonyms like /, sentinel does not exit, PM is not woken up by harness, and worker becomes orphan until timeout.
Business task files (
, etc.) can be attached to Mission/Scope for workers to read, but
the orchestration layer skeleton (Isolation Gate/Heartbeat/Commit/done literal) must come from the template, cannot rely on business files or custom BOOTSTRAP for fallback. If PM finds himself writing BOOTSTRAP instead of using the template, he should stop and instead apply
templates/worker-prompt.md
before assigning.
6. Startup Methods
Default tool surface remains convergent:
- : Perform preflight once before starting Wave on a new machine.
- : Registry/settings-derived env isolation wrapper for Claude Code third-party provider workers.
render-runtime-profile.sh
: Render backend/settings/profile/model/slot and startup command for each worker.
- : Create worktree, Session Context, and tmux session.
- : One per worker, PM starts with , wakes up PM when worker reaches terminal state (see §7.2).
- : Inspection for multiple workers/Waves; use only for single worker or host wake-up.
Project configuration template see
templates/project-config.json
. PM can copy trunk, verification commands, and provider slots from it to the current Goal/Wave plan, but scripts will not automatically apply this configuration.
Other scripts are only used in corresponding scenarios:
for read-only overview,
for dry-run cleanup,
/
only for Skill self-test,
is only optional visualization aid, not part of the default startup path.
By default, use
to create worktree, Session Context, and tmux session; it only responsible for isolation and startup, PM still must send
templates/worker-prompt.md
and confirm
. Startup commands for different backends/profiles can be generated first with
scripts/render-runtime-profile.sh
to reduce manual environment differences.
bash
eval "$(bash scripts/render-runtime-profile.sh \
--backend claude-code \
--runtime-profile minimax \
--api-provider minimax \
--model m3 \
--provider-slot minimax-1 \
--provider-registry config/claude-providers.local.json)"
bash scripts/spawn-worker.sh \
--project /path/to/repo \
--branch docs/ch01-agent-intro \
--session legal-ch01 \
--worker-backend "$WORKER_BACKEND" \
--runtime-profile "$RUNTIME_PROFILE" \
--api-provider "$API_PROVIDER" \
--model "$MODEL" \
--provider-slot "$PROVIDER_SLOT" \
--env-isolation "$PROVIDER_ENV_ISOLATION" \
--verify-cmd 'npm run typecheck' \
--command "$WORKER_COMMAND"
After startup, must pass the minimum gate:
is alive, pane cwd points to worktree,
git branch --show-current
equals target branch,
Session Context/METADATA.json
has recorded base/runtime/verification,
Session Context/STATUS.json
appears within 1-2 minutes. If failed, stop session or send bootstrap correction, do not continue implementation in PM main directory.
Common Worker Commands:
- Claude Code third-party provider (recommended registry): Use
render-runtime-profile.sh --backend claude-code --provider-registry <local-registry.json> --api-provider <provider-id> --model <model-alias>
to generate command; by default wraps scripts/claude-provider-env.sh
, and parses model alias into real claude --model <provider-model>
. Real registry is not submitted; template see config/claude-provider-registry.example.json
.
- Claude Code third-party provider (compatible settings): Can also use
render-runtime-profile.sh --backend claude-code --settings <local-provider.settings.json> --model <provider-model>
to generate command; real settings are not submitted; template see config/claude-provider-settings.example.json
. After startup, must check banner model name; if still displays user default provider, stop worker first to troubleshoot registry/settings/wrapper/environment inheritance.
- Claude Code subscription/OAuth:
env -u ANTHROPIC_API_KEY -u ANTHROPIC_AUTH_TOKEN -u ANTHROPIC_BASE_URL claude --permission-mode auto
.
- Claude Code batch processing: Use
render-runtime-profile.sh --backend claude-code --mode batch --settings <settings> --model <provider-model> --prompt-file /tmp/task.prompt.md
to generate; third-party providers also wrap by default, and batch output is automatically wrapped with to handle redirection.
- Codex:
codex exec -a never -s danger-full-access - < /tmp/task.prompt.md
.
- OpenCode:
opencode run --format json --model <provider/model> "$(cat /tmp/task.prompt.md)"
, or interactive opencode --model <provider/model>
.
- WorkBuddy/CodeBuddy (): Use
render-runtime-profile.sh --backend codebuddy --model <platform model> [--no-mcp] [--dangerously-skip-permissions]
to generate; uses WorkBuddy desktop login state and platform quota, no API Key required. See references/08-workbuddy-cli-worker.md
for details.
- QoderWork CN (): Use
render-runtime-profile.sh --backend qoderwork-cn --model <platform model> [--no-mcp] [--dangerously-skip-permissions]
to generate; script automatically prepends to clear SDK variables and handles binary paths with spaces. See references/07-qoderwork-cli-worker.md
for details.
- Custom CLI: Any command that can run in specified cwd, receive prompt, and save checkpoint to disk.
redirect must be wrapped with (FaroPDF Wave 1 practice, see [DEC-033]):
internally
tmux new-session -d -s "$SESSION" -c "$WORKTREE" "$COMMAND"
directly exec command (not via shell), so shell metachar like
/
/
/
are not expanded. If
contains
redirect, must wrap with
bash -lc 'real-command < /tmp/prompt.md'
, otherwise worker process gets no stdin and exits immediately, sentinel waits until
timeout. Wrong:
--command 'claude -p < /tmp/x.md'
; Correct:
--command "bash -lc 'claude -p < /tmp/x.md'"
.
claude batch mode has autocompact thrash risk (FaroPDF Wave 1 practice, see [DEC-033]):
is print-and-exit one-time run mode, PM cannot correct midway. Large prompt (>5KB) + large project codebase will trigger claude internal
3 times and then automatically terminate, worker never reaches terminal state, sentinel waits until
. Avoidance: (a) split prompt to <3KB; (b) use interactive
+
to deliver prompt (correctable); (c) narrow scope worker (avoid claude loading entire codebase context).
Do not set : PM focuses on detecting whether workers are really advancing, not limiting the number of turns. Long tasks are controlled via
, phased commits,
stale events, and PM corrections.
Claude Code agent view/official backend sessions can be used as Claude-specific backends:
,
,
,
or
when version supports. Use local
/
as standard before use; only can replace tmux if it can prove independent cwd/worktree, inspectable status, and takable sessions.
Agent Teams is suitable for Claude Code team-style collaboration; still need to use worktree isolation and point
to worktree with source prefix. ACP is only enabled when adapter is stable and can output structured status. Subagent is only used for lightweight, narrow-boundary, low-input tasks; upgrade to tmux/agent view/Agent Teams when long-time writing, independent PR submission, or integration across large amounts of materials is needed.
7. Inspection and Intervention
PM Inspection Signals:
- Whether worktree has files saved to disk, commits, PRs.
- Whether
.claude/agent-sessions/<session-id>/METADATA.json
records base ref, runtime profile, provider slot, verification commands, and PR placeholder.
- Whether
.claude/agent-sessions/<session-id>/STATUS.json
is updated, whether it reports blocked/needs_input/done.
- Whether
.claude/agent-sessions/<session-id>/RESULT.md
and exist, whether the summary is sufficient for PM to accept without reading full logs.
- Whether tmux pane reads materials for a long time, waits for confirmation, goes off-topic online, repeatedly plans without execution.
- Whether workers expand modification scope or touch shared files.
- Whether PR diff only covers declared scope.
Intervention Rules:
- Continue waiting when there is continuous output, checkpoint update, or file growth.
- When
Session Context/STATUS.json
still does not appear 1-2 minutes after startup, first send checkpoint-only correction; if still no response, interrupt current thinking and resend bootstrap instruction, do not directly take over implementation.
- When no files are saved for a long time but still planning, first send a narrower command "write target file first".
- When workers skip 10-15 minutes STATUS heartbeat or 30-60 minutes phased commit, PM actively sends correction, requiring immediate STATUS update or submission of current verified phase; if no STATUS/commit/file progress change within 5 minutes, upgrade to restart worker, assign reviewer, or PM narrow-range wrap-up.
- When mild off-topic, scope expansion, starting to fix environment/dependencies, waiting for confirmation, or verification method deviation is found, prioritize sending correction instructions via tmux/agent view/inbox, let workers return to scope execution by themselves.
- Only stop the session and take over by PM when continuous correction fails twice, workers continue to touch forbidden scope, prepare to execute destructive Git/file operations, leak sensitive information, or cannot recover in the original session.
- Retain worktree and before failure, restart, or stop, avoid losing saved outputs.
tmux Correction Example:
bash
tmux send-keys -t legal-ch01 -l -- "PM correction: stop dependency/runtime changes now. Return to ISS-017 only. Do not modify package files or environment config. Update .claude/agent-sessions/legal-ch01/STATUS.json with needs_input=false and continue with the OCR quality report scope."
sleep 0.1
tmux send-keys -t legal-ch01 Enter
Correction prompt should include four things: what to stop, which task to return to, which files/actions are still forbidden, next minimal executable action. Do not only write "you are off-topic".
Complete fields see
references/03-checkpoint-files.md
, copyable templates see
templates/checkpoint-status.json
,
templates/checkpoint-result.md
, and
templates/checkpoint-patch-summary.md
. PM defaults to reading only these checkpoints and final diff, does not pull full logs regularly.
Optional Automatic PM Monitoring Script (retains multi-dimensional inspection capabilities for Agent Teams inbox, task status, Git SHA, PR status, and tmux session):
bash
bash scripts/pm-monitor.sh \
--project /path/to/repo \
--team-dir ~/.claude/teams/team-name \
--tasks-dir ~/.claude/tasks/tasks-uuid \
--claude-agents-cwd /path/to/repo \
--wave-id wave-5 \
--commit-stale-threshold 1800 \
--progress-stale-threshold 1800 \
--interval 60 \
--log-file .claude/agent-sessions/pm-monitor/events.log \
--branch docs/ch01-agent-intro:legal-ch01
Economical Inspection Rules:
- Do not let PM main session manually read worker logs every few minutes; this will offset token efficiency of multi-agent.
- Use for lightweight check, run once by PM when needing to judge whether to intervene, only read event lines.
- For long tasks, run
pm-monitor.sh --log-file ...
in independent shell/tmux/background job, script continuously writes event logs; PM only reads a small amount of logs when status changes, user asks, PR wraps up, or logs show //.
- Current script only responsible for outputting events and writing logs; whether to automatically wake up PM depends on whether the host environment provides automation/monitor/webhook. When no host wake-up capability, default to or low-frequency reading of log tail, still saves context compared to repeated foreground inspection.
- only records structured signals necessary for PM decision-making, detailed implementation instructions continue to be written in and .
- Use
scripts/worktree-status.sh
for read-only overview of single worker; use scripts/clean-worktree.sh
for cleanup, default dry-run, explicit required for real deletion.
7.1 Active Waiting and Host Wake-Up
is a single worker waiter, not a substitute for
. It mainly reads one
, exits and outputs paths of
/
when
,
,
, or
. Suitable for connecting "notify PM when worker completes" to different hosts.
Status Source Hierarchy:
- is static context written by PM at startup, records base/runtime/provider/verification, not used as completion judgment.
- // are main protocols for completion, blockage, verification, and wrap-up.
- is diagnostic window, only read tail output when checkpoint is missing, expired, terminal, or explicitly requested.
- Do not use tmux pane text to judge task completion; completion criteria are still checkpoint, git diff, verification, and PR status.
Claude Code PM:
-
Bash background/run-in-background can only let the waiter run in the background, does not guarantee triggering or waking up current PM/agent session; especially when multiple workers are waiting simultaneously, no completion message may be returned.
-
Do not treat background Bash as a reliable completion notification mechanism. At most, it serves as a log writer or manually viewable background job; PM still must rely on
,
,
, tmux/agent view explicit inspection to wrap up.
-
Single worker can temporarily use background Bash to run
, but must record log file or retain queryable command when starting; default to
for multiple workers/Waves, do not start a background wait for each worker and expect host to callback one by one.
-
Limited Condition Exception: The Sentinel mode described in §7.2 is a "limited condition working variant" of this rule—single worker single sentinel, started with
, harness 100% re-invoke works. Before Wave 6 enables sentinel, still follow the above conservative judgment.
bash
bash scripts/wait-worker.sh \
--worktree .claude/worktrees/tmux-ch01-agent-intro \
--session legal-ch01 \
--tmux-session legal-ch01 \
--interval 30
Codex PM:
- Codex CLI's background shell will not automatically push completion events back to current conversation; do not assume it is equivalent to Claude Code .
- In Codex App, prioritize connecting to heartbeat automation of current thread; complete prompt see
templates/codex-heartbeat-wait.md
. Must use tool first when creating, modifying, or deleting automation, do not write raw RRULE manually.
- When no heartbeat/automation capability, Codex PM uses or for low-frequency manual inspection; still use for long tasks to continuously record events.
is responsible for waiting one worker to terminal state; it outputs terminal state, not responsible for waking up host. Multiple workers, PR status, git SHA, gate, and stale events are still handled by
.
7.2 Sentinel bash Mode (Event-Driven PM Wake-Up)
Applicable: After Wave 6, each worker is matched with a sentinel, PM is woken up by harness task-notification
event-driven, zero idle token consumption, retains multi-round correction capability. Design basis see
references/04-sentinel-design.md
; DEC-031 supersede DEC-030 limited condition judgment.
Mode: Each worker is matched with a
process. Sentinel polls
,
when reading
done | failed | blocked | stopped
, captures tmux pane tail,
,
. Sentinel is started by PM with
, exit triggers harness
task-notification → PM is re-invoke.
PM-Side Calling Mode: Two Bash calls per worker:
bash
# 1) Foreground: create worktree + start worker + verify gate
bash scripts/spawn-worker.sh \
--project /path/to/repo \
--branch docs/ch01-agent-intro \
--session legal-ch01 \
--with-sentinel \ # Only print SPAWN_WORKER_SENTINEL_CMD, not start internally
--command "$WORKER_COMMAND"
# 2) Background: sentinel event-driven wake
# Copy the SPAWN_WORKER_SENTINEL_CMD line from spawn-worker.sh output
bash scripts/sentinel.sh \
--status-file .claude/worktrees/tmux-docs-ch01-agent-intro/.claude/agent-sessions/legal-ch01/STATUS.json \
--tmux-session legal-ch01 \
--poll-interval 5 \
--max-wait 7200
# ↑ Start with Bash run_in_background=true
Why not start sentinel inside spawn-worker.sh:
- is fg tool, sentinel is bg tool, separate responsibilities
- Avoid forking multiple backgrounds in single Bash call (higher rejection rate in auto mode)
- PM explicit opt-in to receive sentinel notifications () is prerequisite for harness re-invoke
Sentinel Event Namespace (independent of
):
| Event | Trigger |
|---|
| On startup |
| STATUS.json missing |
| Before capturing pane (best-effort) |
| Detect /// |
| / | After killing tmux |
| Terminal state not seen when reached |
Standard Actions After PM Receives Notification see
templates/pm-sentinel-response.md
:
- Exit 0 = done: read RESULT/PATCH_SUMMARY, run verify, review, merge
- Exit 2 = failed/blocked/stopped: read STATUS.issues to decide restart/block/defer
- Exit 124 = timeout: check worker tmux + STATUS status, correct or restart
- Exit 64 = usage error: check consistency of / with spawn-worker
Downgrade Path: If sentinel fails to start (auto mode rejection/SIGKILL/parameter error), PM returns to §7.1
behavior: use
for single worker, use
for multiple workers.
Downgrade is graceful, not a failure.
Tuning Suggestions:
- : default 5s. Reduce to 1s when worker's single thinking is short, keep 5s when long
- : default 7200s (2h). Split long workers into sub-tasks, each sub-task has its own max-wait
- : do not kill tmux during review phase,便于 PM tmux capture-pane to see worker wrap-up
- : turn off when pane snapshot is not needed, reduce 1 tmux capture-pane call
Known Uncovered Scenarios:
- Deduplication of multiple sentinels for single worker: guaranteed 1:1 by PM behavior layer
- Codex/OpenCode path: not tested yet, Codex follows
templates/codex-heartbeat-wait.md
- High-frequency polling storm: single worker CPU may be slightly high when worker cluster is large and polling interval <2s, adjust as needed
7.3 cron + sentinel Standard Combination (Fallback Monitoring, Must Hang Two Layers)
sentinel (§7.2) is
main monitoring: event-driven, captures worker terminal state
in seconds, zero idle token. But sentinel alone has 3 blind spots, must hang another
cron fallback (periodic inspection), two-layer combination is standard mode, not either-or:
| Sentinel Blind Spot | Performance | How cron fallback catches it |
|---|
| (a) Worker hard freezes and does not write STATUS | Sentinel polls until timeout (exit 124), maximum wait 2h | cron periodically reads STATUS + pane, finds stale and actively intervenes |
| (b) Worker uses non-standard STATUS file name | Sentinel listens to , worker writes , Sentinel polls empty file until timeout | cron directly / multiple candidate file names, recognizes when hit |
| (c) Sentinel itself is SIGKILL/SIGTERM or harness does not re-invoke | Sentinel silently disappears, PM is never woken up | cron is independent job, does not depend on sentinel survival |
Frequency (Hard Recommendation, by Task Granularity):
- Short Tasks (single worker, expected <1h): ~22 minutes
- Long Pipelines (multiple workers/Wave/expected 1-4h): 10-15 minutes
- Avoid / on the hour: All users crowding on the hour will cause API congestion + trigger rate limits; use off-peak expressions such as (off-peak every 10 minutes) or (off-peak every 22 minutes).
- Do not be less than 10 minutes: cron re-invokes PM every time it fires (reads STATUS + git + pane), too frequent will offset token efficiency of multi-agent.
Dual-Signal Freeze Detection (Avoid Misjudging Long Thinking):
To judge worker freeze, both conditions must be met, neither is dispensable:
- STATUS Signal: Both and file mtime have not changed for > threshold (20min for long pipelines, 15min for short tasks).
- Pane Signal: tail shows evidence of infinite loop (continuous repeated lines / "Levitating… Nmin" keeps rising but no new tool calls / error stack does not exit).
Only meet (1) but not (2): Worker may be in long thinking, send a
heartbeat probe ("update STATUS heartbeat"), wait for next cron round to judge, do not restart immediately.
Use Template for cron Prompt:
templates/cron-monitor-prompt.md
. Template includes: worker session + STATUS path + git branch + sentinel id + stale threshold + wrap-up self-delete (
after all workers merged) + one-sentence report when no action (does not expand context).
Relationship with §7.1/§7.2:
- §7.1 /: Read-only inspection tools actively called by PM (one-time or low-frequency log).
- §7.2 sentinel: Event-driven wake-up when worker reaches terminal state (captures done in seconds), main monitoring.
- §7.3 cron: Time-driven fallback (captures sentinel blind spots + freeze dual signals + sentinel failure).
- The three superimpose, not replace. After PM assigns workers, must hang two layers (sentinel + cron); sentinel is main, cron is fallback, if cron triggers and finds worker still advancing, only return one sentence, no big actions.
8. Wrap-Up
8.0 PM Continuous Synchronization After Worker Raises PR
Worker raising PR is not a signal that PM wrap-up is completed. Between raising PR and merging, PM must do two things to avoid external preemption:
-
Immediately run mergeable check after raising PR:
bash
gh pr view <N> --json state,mergeable,mergeStateStatus,baseRefName,headRefName
- // is behind: base has been preempted by doc-curator or other PRs. Immediately handle according to 's "base behind/conflict handling" decision table (update branch vs rebase vs close-and-reopen).
- and base is latest: enter review process.
-
PM local main push immediately:
- After PM commits docs/DEC in main directory, immediately , avoid drift between local and origin/main.
- After drift, push reports non-fast-forward, "same content but different history" introduced by squash merge will make git misjudge conflict, high recovery cost.
- When seeing origin/main is ahead of local, first +
git switch -C main origin/main
(not , squash commit will not automatically ff), then continue PM work.
Worker backend selection (subagent/tmux/Agent Teams) see §2.1.
8.1 Standard Wrap-Up Steps
After worker completes:
- Check ,
git diff --check main...HEAD
, PR diff scope.
- When review is needed, cross-review, branch author does not review their own PR. Select review tool according to project type, do not default to code-review: use code-review subagent for code projects; use (or project-specific review skill) for manuscripts/docs/writing projects; use corresponding content review for research/configuration PRs. Projects should specify which review skill to use in their ; if not written, PM judges according to project nature, do not assume code-review.
- Merge, push, write PR number into commit, close Issue, etc., follow .
- If PM review finds problems, prioritize sending review correction to original worker via tmux/agent view/inbox; worker should add fix commit, re-run verification, and update PR, do not default to PM writing instead.
- After PM reviews correction commit, verification results, and PR diff, decide whether to enter merge.
- After merging, clean up worktree/session, dry-run first then execute explicitly:
bash
bash scripts/clean-worktree.sh --project /path/to/repo --branch docs/ch01-agent-intro --session legal-ch01
bash scripts/clean-worktree.sh --project /path/to/repo --branch docs/ch01-agent-intro --session legal-ch01 --execute
9. Dependencies
Dependencies are layered by mode; read-only documents do not require any tool installation. Before starting workers on a new machine for the first time, run:
bash
bash scripts/check-dependencies.sh
bash scripts/check-dependencies.sh --backend claude-code --backend codex --check-gh
Minimum Local Execution Dependencies
| Dependency | Installation Method |
|---|
| Usually provided with development environment |
| Regular scripts require bash; requires bash 4+ |
| macOS: <br>Linux: |
| macOS: <br>Linux: sudo apt-get install tmux
|
Common Unix tools such as
,
,
,
,
,
,
are usually provided by the system; date parsing is compatible with macOS/Linux.
Dependencies Enabled by Mode
| Mode | Dependency |
|---|
| PR/mergeability inspection | , and requires login |
| Claude Code worker | ; third-party providers require local settings files |
| Codex worker | |
| OpenCode worker | |
| Codex heartbeat | Codex App automation capability; must use to create/modify automation |
| Claude official agent view/ | , may also need if necessary |
Optional Terminal Dependencies
scripts/terminal-split.sh
requires additional tools only in corresponding terminal scenarios: Kitty requires
, WezTerm requires
, macOS GUI terminal automation depends on
, split screen or new tab capabilities of Warp/Ghostty/Zed/Terminal.app depend on local applications and accessibility authorization.
Complete dependency matrix see
references/02-runtime-dependencies.md
. Dependency check script only reports status, does not install software, start workers, or modify configurations.
10. References
Read only when details are needed:
Core Orchestration References (Mechanism/Dependency/Wrap-Up):
references/01-model-selection-matrix.md
: Model and execution mode selection.
references/02-runtime-dependencies.md
: Local dependency matrix split by mode and installation suggestions.
references/03-checkpoint-files.md
: Fields and templates of , , .
references/04-sentinel-design.md
: Design and signals of PM inspection (sentinel) bash mode.
references/05-legal-domain-patterns.md
: Legal project decomposition examples (litigation/non-litigation phase models, task fields, Agent routing).
config/claude-provider-registry.example.json
: Claude Code third-party API provider/model registry template.
config/claude-provider-settings.example.json
: Claude Code third-party API provider settings compatibility template.
Agent CLI Worker Backend (Read Overview First, Then Check Specific Tools):
references/06-agent-cli-reference.md
: Complete reference manual for all local Agent CLIs (Claude Code/Codex/OpenCode/Hermes/Kimi/Gemini/QoderWork), including parameter quick reference, tmux worker template, cross-CLI comparison matrix, and selection suggestions.
references/07-qoderwork-cli-worker.md
: Feasibility study of QoderWork CLI () as worker backend, including CLI parameters, model list, SDK environment conflicts, tmux startup examples, and applicable scenarios.
references/08-workbuddy-cli-worker.md
: Feasibility study of WorkBuddy/CodeBuddy CLI () as worker backend, including Kimi K2.6 manuscript worker actual test, permission mode, checkpoint/path deviation, and wrap-up rules.
Practical Experience and Troubleshooting:
references/09-parallel-lessons.md
: Practical pitfalls of tmux/Agent Teams.
references/10-agent-teams-troubleshooting.md
: Troubleshooting for Agent Teams/agent view/Claude native backend.
Official Documentation:
- Claude Code agent view:
https://code.claude.com/docs/en/agent-view
- Claude Code worktrees:
https://code.claude.com/docs/en/worktrees
- Claude Code CLI usage:
https://code.claude.com/docs/en/cli-usage
- Claude Code checkpointing:
https://code.claude.com/docs/en/checkpointing
Scripts:
scripts/check-dependencies.sh
: Checks core dependencies, backend CLI, GitHub CLI, and terminal split tools.
scripts/claude-provider-env.sh
: Constructs isolated env for this worker from Claude provider registry or settings JSON, shields user-level provider/model pollution.
scripts/render-runtime-profile.sh
: Generates worker command, prompt context, and spawn metadata according to backend/profile.
- : Creates isolated worktree, Session Context, and tmux session, and outputs startup gate.
- : Automatic PM inspection script, retains checkpoint files, Agent Teams inbox, tasks, Git SHA, PR status, tmux session, Wave, and multi-signal progress monitoring.
- : Single worker waiter, can connect to Claude Code background Bash or Codex heartbeat automation.
scripts/worktree-status.sh
: Single worker read-only overview, displays metadata, checkpoint, tmux, and git status.
scripts/clean-worktree.sh
: Safe cleanup of worker session/worktree, default dry-run, displays metadata summary before cleanup.
scripts/smoke-tmux-worker.sh
: Temporary repo end-to-end smoke test; only run after modifying Skill scripts.
scripts/smoke-provider-settings.sh
: Verifies one by one that can start Claude Code and return response; run after adding or modifying providers.
scripts/lint-wait-script.sh
: Lint for wait/monitor/custom wait scripts; only run after modifying wait/monitor scripts.
scripts/terminal-split.sh
: Optional visualization aid, retains support for iTerm2, Kitty, WezTerm, Warp, Ghostty, Zed, Terminal.app; default orchestration does not depend on it.
Templates:
templates/worker-prompt.md
: Worker bootstrap and complete assignment prompt template.
templates/orchestration-goal.md
: PM-level continuous multi-Wave Goal Contract template.
templates/project-config.json
: Optional project-level orchestration configuration template, declares trunk, task source, verification commands, provider slot, non-sensitive configuration copy, and hook boundaries.
templates/codex-heartbeat-wait.md
: Codex App heartbeat inspection prompt.
templates/wave-summary.md
: Template for each Wave wrap-up and provider/model evaluation.
templates/checkpoint-status.json
: template.
templates/checkpoint-result.md
: Completion/failure result summary template.
templates/checkpoint-patch-summary.md
: Diff summary template for PR review.
11. Evaluation and Acceptance
Evaluation Scope
Evaluation object of this skill = collaborative behavior of spawn-worker + sentinel + pm-monitor + render-runtime-profile + clean-worktree; does not evaluate capabilities of specific worker backends (claude/codex/opencode) themselves.
Hard Fail(Fail Immediately If Occurs)
- Anti-escape gate not passed (§2.1), PM directly writes business code.
- After spawn-worker.sh starts, pane cwd ≠ worktree or branch ≠ target branch (gate failure).
- Worker writes STATUS synonyms (completed/finished) instead of literal , sentinel does not exit.
- Worker modifies files without committing, PM verifies empty diff when wrapping up.
- Real settings (config/*.settings.json) enter git tracking or package.
Benchmark Case
- : Temporary repo e2e (spawn 1 worker to complete, STATUS=done, diff non-empty, clean no residue).
- It is recommended to add : spawn 2 workers to modify non-overlapping files in parallel, sentinel waits for terminal state, verify that two PR diff scopes are independent, STATUS are all done, clean no residue.
Static Check vs Dynamic Evaluation
- Static: (lint for wait/monitor scripts) + (preflight dependency check).
- Dynamic: (e2e end-to-end) +
smoke-provider-settings.sh
(provider verification, requires real key, optional).