Orchestrate Skill
Required Context
Before beginning work, read these files for project-specific guidelines:
.claude/memory-bank/best-practices/subagent-design.md
Pre-Flight Challenge
Before beginning work, address these operational feasibility questions:
- Are there cross-workstream conflicts in shared resources (env vars, ports, DB schemas)?
- Is there shared resource contention (file locks, build artifacts, test databases)?
- Are workstream sequencing risks identified (circular deps, missing prerequisites)?
- Are coordination gaps visible (unowned integration boundaries, unclear contracts)?
If any question cannot be answered from available context, surface it as a finding -- do not skip.
Purpose
Orchestrate large multi-workstream projects (orchestrator workflow) using git worktrees for true parallel development. This skill coordinates the facilitator agent to manage worktree allocation, dependency ordering, subagent execution, and auto-merge after convergence gates pass.
When to Use
Use this skill when:
- MasterSpec has been approved (3+ workstreams)
- Multiple workstreams need to execute in parallel
- Workstreams have dependencies that require ordered execution
- Git worktrees will enable isolated, parallel development
Trigger: After MasterSpec approval in orchestrator workflow
Orchestration Flow
Step 0: Check for Existing Session State
Before initializing, check for an interrupted orchestration session:
node .claude/scripts/session-checkpoint.mjs get-status
If active_work exists with workflow "orchestrator":
-
Display resume prompt to user:
Found interrupted orchestration session: - Task: <objective from active_work> - Phase: <current_phase> - Workstreams: X/Y complete Resume this session? (yes/no) -
If resuming:
- Load session.json
worktree_allocationandworkstream_execution - Verify worktrees still exist:
git worktree list - Determine which workstreams are complete vs in-progress
- Resume from last checkpoint (see Recovery Protocol below)
- Load session.json
-
If not resuming:
- Archive current session state
- Clean up orphaned worktrees if any
- Start fresh with Step 1
If no active orchestration work, proceed to Step 1.
1. Load MasterSpec and Spec Group
# Load approved MasterSpec spec group
cat .claude/specs/groups/<master-spec-group-id>/manifest.json
cat .claude/specs/groups/<master-spec-group-id>/spec.md
# List workstream spec groups
ls .claude/specs/groups/<master-spec-group-id>/workstreams/
Extract:
- Workstream Overview (IDs, titles, dependencies)
- Contract Registry
- Dependency Graph
- Worktree Allocation Strategy (if present)
- Atomic specs for each workstream
2. Invoke Facilitator for Worktree Allocation
If MasterSpec doesn't have worktree allocation strategy, dispatch facilitator to analyze and allocate:
Task({
description: 'Allocate worktrees for MasterSpec',
prompt: `
Analyze the MasterSpec spec group at .claude/specs/groups/<master-spec-group-id>/ and determine worktree allocation.
**Workstreams** (each has its own spec group with atomic specs):
- ws-1: <title> (dependencies: <deps>) - spec group at workstreams/ws-1/
- ws-2: <title> (dependencies: <deps>) - spec group at workstreams/ws-2/
- ws-3: <title> (dependencies: <deps>) - spec group at workstreams/ws-3/
**Your task**:
1. Analyze dependency graph
2. Identify independent workstreams (separate worktrees)
3. Identify tightly coupled workstreams (shared worktrees)
4. Apply allocation heuristics (see facilitator agent guidelines)
5. Document allocation strategy in MasterSpec manifest.json
6. Initialize session.json with worktree_allocation
`,
subagent_type: 'facilitator',
});
3. Create Worktrees
For each worktree in allocation strategy:
# Get repository name
REPO_NAME=$(basename $(pwd))
# Create worktree-1
git worktree add ../${REPO_NAME}-ws-1 -b feature/ws-1-<slug>
# Create worktree-2
git worktree add ../${REPO_NAME}-ws-2 -b feature/ws-2-<slug>
# Verify creation
git worktree list
Create Session State File
After allocating worktrees, persist state to session.json:
# Initialize session with orchestrator workflow
node .claude/scripts/session-checkpoint.mjs start-work <master-spec-id> orchestrator "Orchestrating: <objective>"
# Transition to implementing phase
node .claude/scripts/session-checkpoint.mjs transition-phase implementing
Also create the full worktree state in session.json:
{
"worktree_allocation": {
"strategy": "ws-1 and ws-4 share worktree (tight coupling), ws-2 and ws-3 isolated",
"worktrees": [
{
"id": "worktree-1",
"path": "/Users/matthewlin/Desktop/Personal Projects/engineering-assistant-ws-1",
"branch": "feature/ws-1-backend-api",
"workstreams": ["ws-1", "ws-4"],
"status": "active",
"created_at": "2026-01-02T15:35:00Z"
}
]
}
}
This state enables cross-session recovery if the orchestration is interrupted.
4. Evaluate Initial Workstream Readiness
For each workstream, determine if ready to start:
Ready (no dependencies):
- ws-1: No dependencies → Ready to start
- ws-3: No dependencies → Ready to start
Blocked (has dependencies):
- ws-2: Depends on ws-1 → Blocked
- ws-4: Depends on ws-1 → Blocked (but shares worktree with ws-1)
Update session.json:
{
"workstream_execution": {
"workstreams": [
{
"id": "ws-1",
"title": "Backend API",
"worktree_id": "worktree-1",
"dependencies": [],
"status": "ready"
},
{
"id": "ws-2",
"title": "Frontend UI",
"worktree_id": "worktree-2",
"dependencies": ["ws-1"],
"status": "blocked",
"blocking_reason": "Waiting for ws-1 to merge (dependency)"
}
]
}
}
5. Atomize and Enforce Each Workstream (CRITICAL)
Before dispatching implementers, each workstream spec must be atomized and validated. This step ensures the unified vision traceability chain (REQ → atomic spec → impl → test).
For each workstream (can run in parallel for independent workstreams):
// Step 5a: Atomize workstream spec
Task({
description: 'Atomize ws-1 spec',
prompt: `
Run /atomize for workstream ws-1.
**Spec Group**: .claude/specs/groups/<master-spec-group-id>/workstreams/ws-1/
**Input**: spec.md (WorkstreamSpec)
**Output**: atomic/as-001-*.md, atomic/as-002-*.md, etc.
Decompose the workstream spec into atomic specs following atomicity criteria:
- Each atomic spec is independently testable
- Each atomic spec is independently deployable
- Each atomic spec is independently reviewable
- Each atomic spec is independently reversible
Update manifest.json with atomic_specs.count and atomic_specs.coverage.
`,
subagent_type: 'atomizer',
});
// Step 5b: Enforce atomicity validation
Task({
description: 'Enforce atomicity for ws-1',
prompt: `
Run /enforce for workstream ws-1.
**Spec Group**: .claude/specs/groups/<master-spec-group-id>/workstreams/ws-1/
**Atomic Specs**: .claude/specs/groups/<master-spec-group-id>/workstreams/ws-1/atomic/
Validate each atomic spec against atomicity criteria:
- NOT TOO_COARSE: Single behavior, single test suite, independent rollback
- NOT TOO_GRANULAR: Can test alone, can deploy alone, is a behavior not a code fragment
Also validate:
- Every REQ-XXX is covered by at least one atomic spec
- Requirements coverage >= 100%
Update manifest.json with enforcement_status: PASSING or FAILING.
`,
subagent_type: 'atomicity-enforcer',
});
Gate Implementation on Enforcement:
// Check enforcement status before proceeding
const manifest = JSON.parse(
fs.readFileSync('.claude/specs/groups/<id>/workstreams/ws-1/manifest.json'),
);
if (manifest.enforcement_status !== 'PASSING') {
// Do NOT dispatch implementers
// Either iterate with /atomize --refine or escalate to user
throw new Error(
`ws-1 atomicity enforcement failed: ${manifest.enforcement_issues}`,
);
}
// Only proceed to implementation if enforcement passes
Update session.json:
{
"workstream_execution": {
"workstreams": [
{
"id": "ws-1",
"status": "atomized",
"atomic_specs_count": 4,
"enforcement_status": "PASSING",
"ready_for_implementation": true
}
]
}
}
6. Dispatch Implementers and Test-Writers
For each ready workstream, dispatch implementer and test-writer in parallel:
// ws-1 is ready
const ws1Impl = Task({
description: 'Implement ws-1 in worktree-1',
prompt: `
You are implementing workstream ws-1.
## EXECUTION CONTEXT
**Worktree**: worktree-1
**Path**: /Users/matthewlin/Desktop/Personal Projects/engineering-assistant-ws-1
**Branch**: feature/ws-1-backend-api
**Workstream**: ws-1 (Backend API)
## CRITICAL INSTRUCTIONS
1. **Working Directory**: All operations MUST occur in the worktree path above
2. **Isolation**: Do NOT modify files in the main worktree
3. **Spec Group Location**: .claude/specs/groups/<master-spec-group-id>/workstreams/ws-1/
4. **Atomic Specs**: Execute atomic specs in order (as-001, as-002, etc.)
${
ws1.sharedWorktree
? `
## SHARED WORKTREE NOTICE
This worktree is shared with: ws-4 (Integration Tests)
Coordinate with test-writer: you implement, they test (parallel execution)
`
: ''
}
## YOUR TASK
Implement all atomic specs in ws-1 spec group following standard implementation process.
Fill Implementation Evidence in each atomic spec as you complete them.
`,
subagent_type: 'implementer',
run_in_background: true,
});
const ws1Tests = Task({
description: 'Write tests for ws-1 in worktree-1',
prompt: `
You are writing tests for workstream ws-1.
## EXECUTION CONTEXT
**Worktree**: worktree-1
**Path**: /Users/matthewlin/Desktop/Personal Projects/engineering-assistant-ws-1
**Branch**: feature/ws-1-backend-api
**Workstream**: ws-1 (Backend API)
## YOUR TASK
Write tests for all acceptance criteria in ws-1 atomic specs.
Fill Test Evidence in each atomic spec as you complete them.
Test names should reference atomic spec ID and AC (e.g., "should X (as-001 AC1)").
**Spec Group**: .claude/specs/groups/<master-spec-group-id>/workstreams/ws-1/
**Atomic Specs**: .claude/specs/groups/<master-spec-group-id>/workstreams/ws-1/atomic/
`,
subagent_type: 'test-writer',
run_in_background: true,
});
Update session state:
{
"workstream_execution": {
"workstreams": [
{
"id": "ws-1",
"status": "in_progress"
}
]
}
}
7. Monitor Subagent Completion
Poll background tasks for completion:
// Wait for both implementer and test-writer
const ws1ImplResult = TaskOutput({ task_id: ws1Impl.task_id, block: true });
const ws1TestsResult = TaskOutput({ task_id: ws1Tests.task_id, block: true });
// Both complete → Ready for convergence validation
8. Run Convergence Validation
Dispatch unifier to validate workstream:
Task({
description: 'Validate ws-1 convergence in worktree-1',
prompt: `
Validate convergence for workstream ws-1.
## EXECUTION CONTEXT
**Worktree**: worktree-1
**Path**: /Users/matthewlin/Desktop/Personal Projects/engineering-assistant-ws-1
**Spec Group**: .claude/specs/groups/<master-spec-group-id>/workstreams/ws-1/
## VALIDATION REQUIREMENTS
- All atomic specs have status: implemented
- All atomic spec ACs have Implementation Evidence
- All atomic spec ACs have Test Evidence
- All tests passing
- Traceability chain complete (REQ → atomic spec → impl → test)
- Contract registry validated (if ws-1 owns contracts)
Produce convergence report with CONVERGED or NOT_CONVERGED status.
Update manifest.json convergence gates.
`,
subagent_type: 'unifier',
});
If CONVERGED:
- Update workstream status: "converged"
- Proceed to security review
If NOT_CONVERGED:
- Iteration count < 3 → Fix issues, re-run unifier
- Iteration count >= 3 → Escalate to user
9. Run Security Review
Task({
description: 'Security review for ws-1 in worktree-1',
prompt: `
Review workstream ws-1 for security vulnerabilities.
**Worktree**: worktree-1
**Path**: /Users/matthewlin/Desktop/Personal Projects/engineering-assistant-ws-1
Check: OWASP Top 10, input validation, auth/authz, secrets handling.
`,
subagent_type: 'security-reviewer',
});
If PASSED:
- Update convergence.security_review_passed: true
- Check if workstream has UI components → Run browser test (step 9a)
- If no UI → Add to merge queue
If FAILED (Critical/High severity):
- Block merge
- Escalate to user with findings
9a. Run Browser Test (UI Workstreams Only)
For workstreams that include UI components (frontend, components, user-facing features):
// Check if workstream has UI changes
const hasUIChanges =
workstream.tags?.includes('ui') ||
workstream.title.toLowerCase().includes('frontend') ||
workstream.title.toLowerCase().includes('ui') ||
workstream.title.toLowerCase().includes('component');
if (hasUIChanges) {
Task({
description: 'Browser test for ws-2 in worktree-2',
prompt: `
Run browser-based UI testing for workstream ws-2.
**Worktree**: worktree-2
**Path**: /Users/matthewlin/Desktop/Personal Projects/engineering-assistant-ws-2
## TEST REQUIREMENTS
1. Navigate to relevant pages where UI changes were made
2. Verify visual appearance matches acceptance criteria
3. Test user interactions (clicks, form inputs, navigation)
4. Capture screenshots as evidence
5. Verify error states and edge cases
## ACCEPTANCE CRITERIA TO VERIFY
Reference the atomic specs for ws-2 and verify each UI-related AC:
- Visual elements render correctly
- Interactions work as specified
- Error messages display appropriately
- Responsive behavior (if applicable)
Report PASS or FAIL with evidence (screenshots, interaction logs).
`,
subagent_type: 'browser-tester',
});
}
If PASSED:
- Update convergence.browser_tests_passed: true
- Add to merge queue
If FAILED:
- Block merge
- Report UI issues to user with screenshots
- Wait for fixes, then re-validate
If NO UI CHANGES:
- Skip browser test
- Add directly to merge queue after security review
10. Process Merge Queue
For each workstream in merge queue (FIFO, respecting dependencies):
Pre-Merge Checks:
# Switch to worktree
cd /Users/matthewlin/Desktop/Personal\ Projects/engineering-assistant-ws-1
# Re-run tests (ensure still passing)
npm test
# Check for conflicts with main
git fetch origin main
git merge --no-commit --no-ff origin/main
if [ $? -ne 0 ]; then
git merge --abort
# Handle conflict (see facilitator error handling)
else
git merge --abort # Dry run successful
fi
Execute Merge:
# Commit any uncommitted changes in worktree
git add .
git commit -m "feat(ws-1): implement Backend API
Implements workstream ws-1 from <master-spec-group-id>
Atomic Specs:
- as-001: <title> ✅
- as-002: <title> ✅
- as-003: <title> ✅
Tests: 15 passing
Coverage: 92%
Convergence: PASSED (all atomic specs complete)
Security: PASSED
🤖 Generated with Claude Code
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>"
# Switch to main worktree
cd /Users/matthewlin/Desktop/Personal\ Projects/engineering-assistant
# Merge with --no-ff
git merge --no-ff feature/ws-1-backend-api -m "Merge ws-1: Backend API
Implements workstream ws-1 spec group
Atomic Specs: 3 complete
Contracts Provided:
- contract-backend-api: src/api/server.ts
Dependencies: none
Next: ws-2 can now proceed (dependency satisfied)"
# Push to remote
git push origin main
Update session state:
{
"workstream_execution": {
"workstreams": [
{
"id": "ws-1",
"status": "merged",
"merge_timestamp": "2026-01-02T16:20:00Z"
}
]
}
}
11. Unblock Dependent Workstreams
After ws-1 merges, evaluate dependent workstreams:
// Find workstreams that depend on ws-1
const dependents = workstreams.filter((ws) => ws.dependencies.includes('ws-1'));
for (const ws of dependents) {
// Check if all dependencies now satisfied
const allDepsMerged = ws.dependencies.every(
(dep) => getWorkstream(dep).status === 'merged',
);
if (allDepsMerged) {
// Unblock and dispatch
updateWorkstreamStatus(ws.id, 'ready', null);
dispatchImplementer(ws.id, ws.worktree_id);
}
}
Example:
ws-1: merged ✅
ws-2: ready (dependency satisfied) → Dispatch implementer to worktree-2
ws-4: ready (dependency satisfied, shares worktree-1 with ws-1) → Dispatch test-writer to worktree-1
12. Repeat for All Workstreams
Continue cycle for each workstream:
- Atomize and enforce (step 5)
- Dispatch implementers/test-writers (step 6)
- Monitor completion (step 7)
- Run convergence validation (step 8)
- Run security review (step 9)
- Run browser test if UI workstream (step 9a)
- Add to merge queue (step 10)
- Merge to main
- Unblock dependents (step 11)
Until all workstreams merged.
12a. Mandatory Post-Merge Quality Gates
After all workstreams are merged and before final validation, the following mandatory gates MUST be executed. Each gate uses the session checkpoint for enforcement tracking.
Challenge Dispatches (MANDATORY at 4 stages)
Challenge dispatches are tracked per-stage. The orchestration layer emits --stage when dispatching challenger subagents (DEC-008).
# Stage 1: Pre-orchestration (before dispatching implementers, after spec approval)
node .claude/scripts/session-checkpoint.mjs dispatch-subagent challenge-pre-orch challenger "Pre-orchestration feasibility check" --stage pre-orchestration
node .claude/scripts/session-checkpoint.mjs transition-phase challenging
# Dispatch challenger subagent with stage: pre-orchestration
# After challenger completes:
node .claude/scripts/session-checkpoint.mjs complete-subagent challenge-pre-orch "Pre-orchestration challenge passed"
# Stage 2: Pre-test (after implementation, before test verification)
node .claude/scripts/session-checkpoint.mjs dispatch-subagent challenge-pre-test challenger "Pre-test feasibility check" --stage pre-test
node .claude/scripts/session-checkpoint.mjs transition-phase challenging
# After challenger completes:
node .claude/scripts/session-checkpoint.mjs complete-subagent challenge-pre-test "Pre-test challenge passed"
# Stage 3: Pre-review (after unify, before code review)
node .claude/scripts/session-checkpoint.mjs dispatch-subagent challenge-pre-review challenger "Pre-review feasibility check" --stage pre-review
node .claude/scripts/session-checkpoint.mjs transition-phase challenging
# After challenger completes:
node .claude/scripts/session-checkpoint.mjs complete-subagent challenge-pre-review "Pre-review challenge passed"
Code Review (MANDATORY)
Task({
description: 'Code review for all workstreams',
prompt: `Review all workstream implementations for code quality...`,
subagent_type: 'code-reviewer',
});
Completion Verification (MANDATORY)
Task({
description: 'Completion verification for all workstreams',
prompt: `Verify all post-completion gates: docs, assumptions, registry, memory bank...`,
subagent_type: 'completion-verifier',
});
Documentation Generation (MANDATORY)
Task({
description: 'Generate documentation from implementation',
prompt: `Generate documentation from the completed implementation...`,
subagent_type: 'documenter',
});
PRD Amendment (when PRD exists)
If the implementation was driven by a PRD, push implementation discoveries back:
Task({
description: 'Push implementation discoveries to PRD',
prompt: `Review implementation decisions and push amendments to the source PRD...`,
subagent_type: 'prd-amender',
});
13. Cleanup Worktrees
After all workstreams merged:
# Remove all worktrees
git worktree remove ../engineering-assistant-ws-1
git worktree remove ../engineering-assistant-ws-2
git worktree remove ../engineering-assistant-ws-3
# Delete branches
git branch -d feature/ws-1-backend-api
git branch -d feature/ws-2-frontend-ui
git branch -d feature/ws-3-database-schema
# Verify cleanup
git worktree list # Should only show main worktree
Update session state:
{
"worktree_allocation": {
"worktrees": []
}
}
14. Final Integration Validation
After all workstreams merged, run final validation:
# Full test suite on main
npm test
# Integration tests
npm run test:integration
# Build verification
npm run build
If all pass → Mark orchestrator task complete.
Error Handling
Merge Conflicts
If merge conflict detected:
- Check if contract-based (favor contract owner)
- Otherwise, escalate to user with conflict details
- Preserve both worktrees for manual resolution
Failed Convergence (3+ iterations)
If workstream fails convergence after 3 iterations:
- Update workstream status: "blocked"
- Preserve worktree for debugging
- Escalate to user with validation results
Security Failures (Critical/High)
If security review finds critical/high severity issues:
- Block merge
- Report findings to user
- Wait for fixes, then re-validate
State Management and Recovery
Session Persistence
The orchestrator maintains state in two locations:
.claude/context/session.json- Global session state with phase, active work, worktree allocation- Per-workstream state in manifest.json - Each workstream spec group tracks its own implementation progress
Cross-Session Recovery
On session start, the orchestrator checks for incomplete work (see Step 0):
- Check session.json for active orchestrator workflow
- Verify worktrees exist - Each allocated worktree should still be present
- Check workstream status - Determine which workstreams are complete vs in-progress
- Resume or restart - Continue from where we left off or restart failed workstreams
Recovery Decision Matrix:
| Worktree Status | Workstream Status | Action | | --------------- | ----------------- | ------------------------------------- | | Exists | merged | Skip (already done) | | Exists | converged | Resume at security review | | Exists | in_progress | Resume implementation | | Exists | ready | Resume dispatch | | Missing | any non-merged | Recreate worktree, restart workstream |
Checkpoint Triggers
Session state is updated on these events:
- Worktree allocation (new worktree created)
- Workstream dispatch (subagent started)
- Workstream completion (subagent finished)
- Convergence validation (unifier result)
- Merge operation (workstream merged to main)
- Phase transition (all workstreams done, moving to review)
# After each workstream completion
node .claude/scripts/session-checkpoint.mjs complete-subagent <task_id> "<summary>"
# After merge
node .claude/scripts/session-checkpoint.mjs transition-phase verifying
State Fields
Throughout orchestration, maintain session.json with:
worktree_allocation: All active worktrees with paths, branches, workstreamsworkstream_execution: Status of each workstream (ready, blocked, in_progress, converged, merged)merge_queue: Workstreams ready to merge (FIFO order)active_work.workflow: "orchestrator"current_phase: Current orchestration phase
Success Criteria
Orchestrator task complete when:
- All workstream spec groups converged (all atomic specs implemented + tested)
- All UI workstreams browser tested
- All workstreams merged to main
- All worktrees cleaned up
- Integration tests passing
- No merge conflicts remain
- MasterSpec manifest.json shows all convergence gates passed
- Full traceability chain validated for each workstream
Finalize Session
After all success criteria met, complete the orchestration work:
# Complete orchestration work and clear active session
node .claude/scripts/session-checkpoint.mjs complete-work
This clears the active_work from session.json, archiving the completed orchestration. The next session start will not prompt for resume.
Example Session
User Request: "Add real-time notifications"
MasterSpec: 3 workstreams
- ws-1: WebSocket Server (no deps)
- ws-2: Frontend Client (depends on ws-1)
- ws-3: Notification Service (depends on ws-1)
Orchestration:
- Load MasterSpec ✅
- Allocate worktrees (3 separate) ✅
- Create worktrees ✅
- Evaluate readiness (ws-1 ready, ws-2/ws-3 blocked) ✅
- Atomize + enforce ws-1 ✅
- Dispatch ws-1 implementer/test-writer ✅
- ws-1 converges → Security review ✅ → Merge ✅
- Unblock ws-2, ws-3 ✅
- Atomize + enforce ws-2, ws-3 (parallel) ✅
- Dispatch ws-2, ws-3 (parallel) ✅
- ws-2 converges → Security review ✅ → Browser test (UI workstream) ✅ → Merge ✅
- ws-3 converges → Security review ✅ → Merge ✅ (no browser test - backend only)
- Cleanup worktrees ✅
- Final validation ✅
- Complete ✅