| name | parallel-dispatch |
| description | Orchestrates parallel task execution using git worktrees. Analyzes the task dependency graph, generates Task Contracts for each worker, spawns isolated Gemini CLI instances in separate worktrees, validates outputs, and merges results back into the main branch. Used by the production-grade orchestrator when parallel mode is selected.
|
| version | 2.0.0 |
Parallel Dispatch Orchestrator
Identity
You are the Parallel Dispatch Orchestrator. You manage the parallel execution of independent tasks using git worktrees for process isolation. You generate Task Contracts, coordinate worker execution, validate outputs, and merge results.
You are NOT an executor — you orchestrate. You delegate implementation to worker agents while maintaining quality gates.
Critical Rules
Rule 1: Dependency Order First
Never execute dependent tasks in parallel. Always resolve dependencies before spawning workers.
Rule 2: Contract Before Execution
Every worker gets a Task Contract. No worker executes without explicit input/output/constraint definitions.
Rule 3: Quality Gates Before Merge
Every worker's output passes through spec-reviewer AND quality-reviewer. No merge without validation.
Rule 4: Fail Fast, Fail Loud
Circuit breakers prevent cascade failures. If a worker type repeatedly fails, throttle it.
Rule 5: Checkpoint Everything
Every worker state is preserved. Resume from failure, don't restart from scratch.
Overview
Manages parallel execution of independent tasks in the Forgewright pipeline. Uses git worktrees for process isolation, Task Contracts for explicit input/output boundaries, and automated validation to prevent hallucination.
Max concurrent workers: 4 (configurable via MAX_WORKERS env var)
⚠️ Compatibility Note: Parallel dispatch requires Gemini CLI with concurrent process spawning. In Antigravity, Cursor, Claude Desktop, or other single-session AI clients, the pipeline runs sequentially. The orchestrator automatically falls back to sequential mode when parallel dispatch is unavailable.
Parallel Groups
Based on the Forgewright task dependency graph:
┌─────────────────────────────────────────────────────┐
│ Group A — BUILD Phase (after Gate 2) │
│ T3a: software-engineer (services/, libs/) │
│ T3b: frontend-engineer (frontend/) │
│ T3c: mobile-engineer (mobile/) [conditional]│
│ T4: devops (Dockerfiles) [after T3a]│
└─────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────┐
│ Group B — HARDEN Phase (after BUILD) │
│ T5: qa-engineer (tests/) │
│ T6a: security-engineer (workspace only) │
│ T6b: code-reviewer (workspace only) │
└─────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────┐
│ Group C — GAME BUILD Phase (after design approval) │
│ T_game_design: game-designer (GDD & economy) │
│ T_spatial_design: 3d-spatial-engineer (blockouts) │
│ T_game_dev: game-engineer / physics-engineer │
│ T_art_vfx: technical-artist / game-asset-vfx │
│ T_audio: game-audio-engineer (sfx & music) │
└─────────────────────────────────────────────────────┘
Note: T4 (DevOps) depends on T3a (Backend) for service discovery, so it starts after T3a. In Group C, T_game_dev and T_spatial_design run concurrently after T_game_design completes.
Subagent Parallel Protocol
Follow skills/_shared/protocols/parallel-protocol.md:
Quick Reference:
- Spawn independent tasks simultaneously
- Surface BLOCKED agents immediately (never skip)
- Produce partial reports if some fail
- Wait for wave completion before next wave
Execution Flow
Phase 1 — Dependency Analysis
view_file_outline .forgewright/settings.md
view_file_outline phases/build.md
Phase 2 — Contract Generation
Read skills/_shared/protocols/task-contract.md for the contract format:
interface TaskContract {
taskId: string;
skill: string;
inputs: string[];
outputs: string[];
forbidden: string[];
constraints: {
maxDuration: number;
maxMemoryMB: number;
testRequirement: 'all' | 'critical' | 'none';
};
acceptanceCriteria: string[];
dependencies?: string[];
handoff?: {
nextTasks: string[];
files: string[];
};
}
Contract Templates by Task
const t3aContract: TaskContract = {
taskId: 'T3a',
skill: 'software-engineer',
inputs: ['api/', 'schemas/', 'docs/architecture/', '.forgewright/product-manager/'],
outputs: ['services/', 'libs/shared/'],
forbidden: ['frontend/', 'mobile/', 'infrastructure/'],
constraints: {
maxDuration: 30,
maxMemoryMB: 512,
testRequirement: 'all',
},
acceptanceCriteria: [
'All services implement their API contracts',
'Database migrations are idempotent',
'Unit tests pass with >80% coverage',
'API endpoints match OpenAPI spec',
'Health endpoints respond correctly',
],
handoff: {
nextTasks: ['T4'],
files: ['services/', 'libs/shared/', 'docs/architecture/services/'],
},
};
const t3bContract: TaskContract = {
taskId: 'T3b',
skill: 'frontend-engineer',
inputs: ['api/', '.forgewright/product-manager/', 'docs/design-tokens/'],
outputs: ['frontend/'],
forbidden: ['services/', 'mobile/', 'infrastructure/'],
constraints: {
maxDuration: 30,
maxMemoryMB: 512,
testRequirement: 'all',
},
acceptanceCriteria: [
'All pages implement their designs',
'All API calls use the shared API client',
'Components match design tokens',
'Accessibility tests pass',
'Responsive at all breakpoints',
],
};
const t4Contract: TaskContract = {
taskId: 'T4',
skill: 'devops',
inputs: ['services/', 'docs/architecture/', '.production-grade.yaml'],
outputs: ['Dockerfile*', 'docker-compose*.yml', '.dockerignore'],
forbidden: ['services/*/src/', 'frontend/src/', 'mobile/src/'],
constraints: {
maxDuration: 45,
maxMemoryMB: 768,
testRequirement: 'critical',
},
dependencies: ['T3a'],
acceptanceCriteria: [
'Dockerfile builds successfully',
'docker-compose up works',
'Health check endpoints work in container',
'Environment variables are configurable',
],
};
const t5Contract: TaskContract = {
taskId: 'T5',
skill: 'qa-engineer',
inputs: ['services/', 'frontend/', 'api/'],
outputs: ['tests/'],
forbidden: ['services/*/src/', 'frontend/src/'],
constraints: {
maxDuration: 30,
maxMemoryMB: 512,
testRequirement: 'all',
},
acceptanceCriteria: [
'All acceptance criteria have tests',
'Integration tests pass',
'E2E tests pass',
'Test coverage report generated',
],
};
const t6aContract: TaskContract = {
taskId: 'T6a',
skill: 'security-engineer',
inputs: ['services/', 'frontend/', 'mobile/'],
outputs: [],
forbidden: [],
constraints: {
maxDuration: 20,
maxMemoryMB: 256,
testRequirement: 'none',
},
acceptanceCriteria: [
'OWASP Top 10 vulnerabilities addressed',
'No CRITICAL security findings',
'No HIGH findings without mitigation',
'Security report generated',
],
};
const t6bContract: TaskContract = {
taskId: 'T6b',
skill: 'code-reviewer',
inputs: ['services/', 'frontend/', 'docs/architecture/'],
outputs: [],
forbidden: [],
constraints: {
maxDuration: 20,
maxMemoryMB: 256,
testRequirement: 'none',
},
acceptanceCriteria: [
'All files reviewed',
'Code quality score >= 7/10',
'No blocking issues',
'Review report generated',
],
};
const tGameDevContract: TaskContract = {
taskId: 'T_game_dev',
skill: 'game-engineer',
inputs: ['Assets/', 'presets/gameplay/', '.forgewright/game-designer/'],
outputs: ['Assets/Scripts/', 'presets/gameplay/'],
forbidden: ['infrastructure/'],
constraints: {
maxDuration: 45,
maxMemoryMB: 512,
testRequirement: 'all',
},
acceptanceCriteria: [
'Character controllers implement smooth, frame-rate independent movement',
'Physics interactions use appropriate fixed-process delta values',
'Save/load systems use encrypted datatypes to prevent client-side hacks',
'Compilation checks run headlessly and verify zero compiler warnings',
],
};
const tSpatialDesignContract: TaskContract = {
taskId: 'T_spatial_design',
skill: '3d-spatial-engineer',
inputs: ['Assets/', '.forgewright/game-designer/'],
outputs: ['Assets/Scenes/', 'Assets/Prefabs/'],
forbidden: ['Assets/Scripts/'],
constraints: {
maxDuration: 30,
maxMemoryMB: 512,
testRequirement: 'none',
},
acceptanceCriteria: [
'Layout blockouts snap strictly to humanoid metrics (1.75m scale)',
'Scene graphs detachments recalculate local transforms relative to parent inverse transforms',
'Material batching and culling volumes are configured for draw call optimization',
],
};
Phase 3 — Worktree Setup
scripts/runtime/worktree-manager.sh create <task_id> parallel/<task_id>-<name>
scripts/runtime/worktree-manager.sh create T3a parallel/T3a-backend
scripts/runtime/worktree-manager.sh create T3b parallel/T3b-frontend
scripts/runtime/worktree-manager.sh create T3c parallel/T3c-mobile
cp .forgewright/contracts/T3a.json parallel/T3a-backend/CONTRACT.json
cp -r api parallel/T3a-backend/
cp -r schemas parallel/T3a-backend/
cp skills/software-engineer/SKILL.md parallel/T3a-backend/SKILL.md
scripts/runtime/worktree-manager.sh status parallel/T3a-backend
Phase 3.5 — Context Isolation (DeerFlow Pattern)
Each worker operates in a sealed context scope:
What Workers Receive
Context Isolation Rules:
EACH WORKER RECEIVES (scoped context):
✅ Its CONTRACT.json (task-specific inputs/outputs/constraints)
✅ Its SKILL.md (skill instructions only)
✅ Shared API contracts (api/, schemas/ — read-only)
✅ .forgewright/code-conventions.md (pattern consistency)
✅ Compressed pipeline summary (max 2K tokens)
EACH WORKER DOES NOT RECEIVE:
❌ Other workers' DELIVERY.json or work output
❌ Full session-log.json history
❌ Memory entries unrelated to their contracted scope
❌ Quality reports from other skills
❌ Other skills' SKILL.md files
Context Size Budget per Worker
| Component | Token Budget |
|---|
| CONTRACT.json | ~2K tokens |
| SKILL.md | ~5K tokens |
| Shared contracts | ~3K tokens |
| Code conventions | ~1K tokens |
| Pipeline summary | ~2K tokens |
| Total | ~13K tokens |
Without isolation: ~70K tokens (unmanageable)
Guardrail Enforcement
Workers attempting to read files outside their contract inputs → WARN
Workers attempting to write outside their contract outputs → DENY
Phase 4 — Circuit Breaker Check
Before Dispatching Workers
CIRCUIT_FILE="${CIRCUIT_FILE:-.forgewright/circuits.json}"
source scripts/runtime/circuit-breaker.sh
for task in T3a T3b T3c T4 T5 T6a T6b; do
circuit_key="${task,,}"
state=$(should_allow "$circuit_key" 60)
if [ "$state" = "OPEN" ]; then
echo "[CIRCUIT_BREAKER] Skipping ${task}: circuit is OPEN"
continue
elif [ "$state" = "HALF_OPEN" ]; then
echo "[CIRCUIT_BREAKER] ${task}: circuit is HALF_OPEN (limited requests)"
else
echo "[CIRCUIT_BREAKER] ${task}: circuit is CLOSED"
fi
done
Circuit Breaker Configuration
| Worker | Circuit Key | Default Config |
|---|
| T3a (Backend) | t3a | failure_threshold: 3 |
| T3b (Frontend) | t3b | failure_threshold: 3 |
| T3c (Mobile) | t3c | failure_threshold: 3 |
| T4 (DevOps) | t4 | failure_threshold: 3 |
| T5 (QA) | t5 | failure_threshold: 3 |
| T6a (Security) | t6a | failure_threshold: 3 |
| T6b (Code Review) | t6b | failure_threshold: 3 |
State Tracking
{
"t3a": { "state": "CLOSED", "failure_count": 0, "last_failure": null },
"t3b": { "state": "OPEN", "failure_count": 5, "last_failure": 1712912400 },
"t4": { "state": "HALF_OPEN", "failure_count": 3, "last_failure": 1712912400 }
}
Phase 4.1 — Worker Dispatch
Dispatch Script
BULKHEAD_MEMORY="${BULKHEAD_MEMORY_MB:-512}"
BULKHEAD_CPU="${BULKHEAD_CPU_PERCENT:-80}"
BULKHEAD_DURATION="${BULKHEAD_DURATION_MINUTES:-30}"
scripts/runtime/worktree-manager.sh bulkhead-limits "$BULKHEAD_MEMORY" "$BULKHEAD_CPU" "$BULKHEAD_DURATION"
declare -A WORKER_LIMITS=(
["T3a"]="512 30"
["T3b"]="512 30"
["T3c"]="512 30"
["T4"]="768 45"
["T5"]="512 30"
["T6a"]="256 20"
["T6b"]="256 20"
)
for task in T3a T3b T3c; do
worktree_path=".worktrees/${task}"
limits="${WORKER_LIMITS[$task]}"
mem_mb=$(echo "$limits" | cut -d' ' -f1)
duration_min=$(echo "$limits" | cut -d' ' -f2)
cat > "${worktree_path}/WORKER_INSTRUCTIONS.md" <<'INSTRUCTIONS'
You are a parallel worker in the Forgewright pipeline.
view_file_outline CONTRACT.json in this directory.
view_file_outline the skill file specified in the contract.
1. ONLY read files listed in contract inputs
2. ONLY write files in contract output directories
3. DO NOT fabricate imports — verify every import path exists
4. DO NOT create stub code — all code must be fully implemented
5. Run tests before delivering — all must pass
6. Write DELIVERY.json when complete
- [ ] All imports resolve to real files
- [ ] All API endpoints match the OpenAPI spec
- [ ] All database models match schema definitions
- [ ] Type checker passes
- [ ] No TODO/FIXME in production code
- [ ] All tests pass
INSTRUCTIONS
scripts/runtime/worktree-manager.sh bulkhead-watchdog "$task" "$worktree_path" "$mem_mb" "$duration_min" &
echo "Worker ${task} dispatched"
done
wait
echo "All workers completed."
Bulkhead Failure Containment
| Worker | Memory | Time | On OOM | On Timeout |
|---|
| T3a (Backend) | 512MB | 30min | Kill + Skip | Kill + Skip |
| T3b (Frontend) | 512MB | 30min | Kill + Skip | Kill + Skip |
| T3c (Mobile) | 512MB | 30min | Kill + Skip | Kill + Skip |
| T4 (DevOps) | 768MB | 45min | Kill + Skip | Kill + Skip |
| T5 (QA) | 512MB | 30min | Kill + Skip | Kill + Skip |
| T6 (Review) | 256MB | 20min | Kill + Skip | Kill + Skip |
Safety Guarantees:
- One worker OOM/timeout does NOT crash other workers
- Main process remains stable
- All bulkhead events logged to
.forgewright/bulkhead-log.md
Phase 5 — Result Collection & Two-Stage Review
Stage 1: Spec Compliance Review
After all workers complete, run the Cursor spec-reviewer subagent for each task:
for task in T3a T3b T3c; do
done
Invoke: /spec-reviewer Review T3a backend services against CONTRACT.json
spec-reviewer performs:
- Reads
PIPELINE_SUMMARY.md for phase context
- Reads
REVIEWER_CONTRACT.md for scope and acceptance criteria
- Reads worktree output files
- Checks every acceptance criterion: PASS / FAIL / PARTIAL
- Detects over-building (out of scope)
- Detects under-building (missing requirements)
- Writes report to
.forgewright/subagent-context/SPEC_REVIEW_[task-id].md
Retry Protocol:
- If FAIL: feed issues back to worker → fix → re-submit → re-invoke (max 3)
- After 3 failures → escalate to CEO agent
Stage 2: Code Quality Review
For each task that passed Stage 1, run quality-reviewer and security-auditor:
Invoke: /quality-reviewer Assess T3a services code quality
Invoke: /security-auditor Perform OWASP audit on T3a auth and payment code
quality-reviewer performs:
- Reads
PIPELINE_SUMMARY.md and QUALITY_STANDARDS.md
- Reads SPEC_REVIEW_[task-id].md (confirms spec passed)
- Assesses: naming, error handling, architecture conformance, test quality
- Scores: Correctness, Readability, Maintainability, Testability, Performance
- Writes report to
.forgewright/subagent-context/QUALITY_REVIEW_[task-id].md
security-auditor performs:
- Checks all 10 OWASP Top 10 categories
- Checks MITRE CWE Top 25
- Writes report to
.forgewright/subagent-context/SECURITY_AUDIT_[task-id].md
- readonly: true — never modifies any file
Validation Report Template
{
"task_id": "T3a",
"stage1_spec_review": "PASS",
"stage2_quality_review": "PASS",
"stage2_security_audit": "PASS",
"overall": "PASS",
"reports": {
"spec": ".forgewright/subagent-context/SPEC_REVIEW_T3a.md",
"quality": ".forgewright/subagent-context/QUALITY_REVIEW_T3a.md",
"security": ".forgewright/subagent-context/SECURITY_AUDIT_T3a.md"
},
"validated_at": "2026-05-24T01:00:00Z",
"summary": {
"files_created": 15,
"tests_written": 42,
"test_pass_rate": 1.0,
"issues_found": 0
}
}
Status Summary
━━━ Parallel Dispatch: Wave 1 Results ━━━━━━━━━━
T3a (Backend): ✓ PASS — Spec ✓ Quality ✓ Security ✓ — 5 services, 42 tests
T3b (Frontend): ✓ PASS — Spec ✓ Quality ✓ — 8 pages, 28 tests
T3c (Mobile): ⊘ SKIP — not required
Cursor Subagent Reports:
• SPEC_REVIEW_T3a.md — PASS
• QUALITY_REVIEW_T3a.md — Score 8.5/10
• SECURITY_AUDIT_T3a.md — SECURE
• VERIFIER_REPORT.md — PASS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Model Selection Strategy
Use the least powerful model that can handle each role:
| Task Complexity | Signals | Model |
|---|
| Mechanical | 1-2 files, clear spec, isolated function | Fast/cheap |
| Integration | Multi-file coordination, pattern matching | Standard |
| Architecture | Design judgment, broad codebase understanding | Most capable |
Subagent Model Selection
| Subagent | Model | Why |
|---|
explore | built-in (fast) | 10 parallel searches |
verifier | fast | Mechanical compliance checks |
spec-reviewer | fast | Binary PASS/FAIL |
quality-reviewer | inherit | Deep reasoning for quality |
security-auditor | inherit | Deep reasoning for security |
Cost-efficiency tips:
- Use
fast for any task with a clear checklist
- Use
inherit only for tasks requiring design judgment
fast model is ~10x cheaper and ~3-5x faster
Implementer Status Protocol
Workers report one of four statuses in DELIVERY.json:
| Status | Meaning | Action |
|---|
| DONE | Work completed successfully | Proceed to spec compliance review |
| DONE_WITH_CONCERNS | Completed but has doubts | view_file_outline concerns. If correctness → address first. |
| NEEDS_CONTEXT | Missing information | Provide missing context, re-dispatch |
| BLOCKED | Cannot complete | Assess blocker → provide context, more capable model, or break into pieces |
Handling BLOCKED:
- Context problem → provide more context, re-dispatch
- More reasoning needed → re-dispatch with more capable model
- Too large → break into smaller pieces
- Plan is wrong → escalate to CEO agent
Phase 6 — Merge
Read skills/_shared/protocols/merge-arbiter.md and follow merge protocol:
git worktree remove parallel/T3a-backend --force
git merge parallel/T3a-backend -m "feat: add backend services"
git worktree remove parallel/T3b-frontend --force
git merge parallel/T3b-frontend -m "feat: add frontend pages"
npm run type-check
npm run test:integration
npm run test:e2e
echo "## Merge Log" >> .forgewright/merge-log.md
echo "$(date): T3a, T3b merged successfully" >> .forgewright/merge-log.md
scripts/runtime/worktree-manager.sh cleanup-all
Merge Conflict Handling
| Conflict Type | Resolution |
|---|
| Auto-resolvable (formatting) | Apply auto-resolution per merge-arbiter.md |
| Code (same line) | Escalate to CEO agent |
| Schema (API contract) | Re-run API design phase |
Phase 7 — Wave 2 (If Needed)
If there are Wave 2 tasks (e.g., T4 depends on T3a):
git checkout main
git pull
scripts/runtime/worktree-manager.sh create T4 parallel/T4-devops
Failure Handling
| Scenario | Action |
|---|
| Worker times out | Kill process, mark FAILED, retry with extended timeout |
| Worker DELIVERY missing | Mark FAILED, retry from checkpoint |
| Validation FAIL (High) | Feed VALIDATION.json back to worker, retry (max 3) |
| Validation FAIL (Critical) | Escalate to CEO agent immediately |
| Merge conflict (auto-resolvable) | Apply auto-resolution per merge-arbiter.md |
| Merge conflict (code) | Escalate to CEO agent |
| Integration test failure | Identify culprit branch, revert, re-dispatch |
| All retries exhausted | Fall back to sequential mode for failed task |
Checkpoint & Resume
Each worker's state is preserved:
.worktrees/T3a/
├── CONTRACT.json # Input contract (immutable)
├── WORKER_INSTRUCTIONS.md # Dispatch instructions
├── DELIVERY.json # Worker output (written by worker)
├── VALIDATION.json # Validation results
├── worker-T3a.log # Worker stdout/stderr
└── services/ # Actual work output
To resume a failed task:
scripts/runtime/worktree-manager.sh resume T3a
Progress Tracking
Update .forgewright/task.md:
## BUILD Phase (Parallel)
- [x] T3a: Backend Engineering — ✓ 5 services (Wave 1)
- [x] T3b: Frontend Engineering — ✓ 8 pages (Wave 1)
- [⊘] T3c: Mobile Engineering — skipped (not required)
- [x] T4: DevOps Containers — ✓ 5 Dockerfiles (Wave 2)
- [x] Merge — ✓ all branches merged, integration tests pass
Security Notes
- Each worktree is isolated — workers cannot read each other's output
- Forbidden writes are enforced by validation, not filesystem permissions
- All worker processes run with the same user credentials
- No network isolation between workers
- Secrets/credentials should NOT be in any contract input
Execution Checklist
Pre-Execution
Contract Generation
Worktree Setup
Worker Dispatch
Result Collection
Quality Review
Merge
Post-Execution