opencode-parallel-executor
v0.1.0
Published
An orchestration plugin for OpenCode that enables parallel, dependency-aware task execution using isolated Git worktrees, automated verification, and resilient state management. This exists **with** your agent orchestrator (such as [oh-my-opencode](https:
Downloads
160
Readme
OpenCode Parallel Executor
An orchestration plugin for OpenCode that enables parallel, dependency-aware task execution using isolated Git worktrees, automated verification, and resilient state management. This exists with your agent orchestrator (such as oh-my-opencode, oh-my-opencode-slim)
Getting Started
Installation
Add the plugin to your opencode.json configuration file:
{
"plugin": [
"opencode-parallel-executor"
]
}Basic Usage
Then after you have your plan, in Opencode, run
/parallel-planto convert your plan to a parallel-plan
Once you're happy with the plan, in Opencode, run
/parallel-buildwhich will run your DAG-based plan in parallel
Note
The plugin automatically registers the required parallel-plan, parallel-orchestrator, and parallel-worker agents, slash commands (/parallel-plan, /parallel-build, /parallel-status, /parallel-cancel, /parallel-resume), and workflow tools on startup.
These agents are namespaced and do not replace your existing plan / build agents:
parallel-planandparallel-orchestratorusemode: "primary"so they work withopencode run --agent …and slash commands.parallel-workerusesmode: "subagent"for task implementation only.- Orchestrator defaults to
permission.edit: denyso it cannot rewrite source mid-run. - This means that this is compatible with oh-my-opencode, oh-my-opencode-slim, or whatever agent orchestrator plugin you use
Table of Contents
- Getting Started
- Overview
- Usage & Policy
- Commands Reference
- Configuration & Schema Reference
- Technical Architecture & Under the Hood
- 1. DAG Validation & Ownership Enforcement
- 2. Git Worktree Orchestration
- 3. Polyglot Toolchain Symlinking
- 4. Pre-Check File Boundary Enforcement
- 5. Feedback-Driven Retry Loop
- 6. Sequential Merging & Automated Conflict Resolution
- 7. Post-Merge Semantic Verification & Rollback
- 8. Event-Sourced SQLite State Machine
Overview
Complex software features often consist of multiple independent subtasks, such as updating database schemas, adding API utilities, building UI components, and writing tests. Running an AI assistant sequentially on these tasks can be slow and error-prone.
The OpenCode Parallel Executor solves this by breaking feature requests into a Directed Acyclic Graph (DAG) of non-overlapping subtasks. It dispatches worker subagents to execute those subtasks concurrently in isolated Git worktrees, runs acceptance checks, and automatically integrates verified changes back into your working branch.
Key Benefits
- Speed: Executes independent tasks simultaneously, reducing overall build time by 3x to 5x.
- Working Directory Safety: Work happens inside temporary, isolated Git worktrees. Your main workspace remains untouched until all changes are fully verified and integrated.
- High Quality Gates: Every task must pass CLI acceptance checks (such as typecheckers, linters, and unit test suites) before its code is merged.
- Polyglot Support: Works out of the box with TypeScript/Node.js, Python, Go, Rust, and other language toolchains.
- Fault Tolerance: Automatically captures compiler errors and feeds them back into retry attempts, handles merge conflicts, detects semantic drift, and supports resuming failed runs without re-running completed tasks.
Fault Tolerance & Plan Repair
The orchestrator includes robust recovery mechanisms for both coding errors and structural plan defects:
- Implementation Retries: If a worker fails its acceptance checks, the scheduler captures the error and retries the task up to 3 times in the same worktree.
- Failure Forensics: When a worker times out (wall-clock limit), the system automatically analyzes the session history to identify the last tool and command in flight (e.g., a wedged
catorgrep). This context is provided to the next attempt to prevent the model from repeating the same hang. - Final Acceptance Recovery: If the full integrated suite fails, the scheduler automatically parses error paths, blames the responsible tasks, resets them to pending with the failure feedback, and continues orchestration for up to 2 recovery rounds.
- Plan Defect Escalation: If a worker determines that the assigned task is impossible under the current plan, it can call the
report_plan_defecttool. - Automated Quiesce: Upon a reported plan defect, the orchestrator immediately pauses the run and cancels other active workers to prevent further desync.
- Repair Cycle: A specialized
parallel-repairagent can then analyze the defect and apply a validated patch to the plan using theplan_repair_applytool. Once repaired, the failed task is reset and execution resumes from the point of failure.
Usage & Policy
When to use Parallel Executor
Parallel builds are designed for large features with independent subtasks.
- Eligibility: A plan must have at least 3 worker tasks and a DAG width of at least 2 to be eligible.
- Small Tasks: For features affecting only 1-2 files or small changes, direct implementation in a single agent session is recommended.
Acceptance Scoping & Category Coverage
To avoid deadlocks, task acceptance checks must be scoped to the files owned by that task (e.g., npx vitest run src/my-feature.test.ts).
- Mirror Final Categories: If
finalAcceptanceincludes a check category (liketype,unit, orlint), every worker task that owns relevant code files must include a scoped acceptance check for that category. - Global Checks: Commands like bare
npm testortsc --noEmitare banned at the task level. - Final Verification: Use
plan.finalAcceptancefor full-repo suite runs after all tasks are merged.
Operational Requirements
- Session Persistence: The orchestrator runs in the background of the session that calls
/parallel-build. Ensure you use a persistent session (OpenCode TUI oropencode serve). - Toolchain Preflight: The project root must have dependencies installed (e.g.,
node_modules) before starting a parallel build to enable worktree symlinking.
Basic Workflow
Generate a Plan: Type
/parallel-plan "Describe the feature you want to build"in OpenCode. Theparallel-planagent analyzes your request, creates a DAG plan with file boundaries and test checks, and saves it.Execute the Plan: Type
/parallel-buildto launch execution. The orchestrator stashes your changes and starts the background scheduler. Workers are spawned and managed by the scheduler, providing live TUI spinners in your session.Monitor Progress: Type
/parallel-statusat any time to inspect real-time progress and task statuses.Resume or Cancel if Needed: If a task encounters an unrecoverable error, use
/parallel-resumeto pick up where it left off after fixing the issue, or/parallel-cancelto stop execution and clean up worktrees.
Commands Reference
The plugin registers five primary slash commands:
/parallel-plan [request]
Analyzes the codebase and the user request, decomposes the work into a structured DAG of tasks, validates file ownership constraints, and calls plan_save to persist the plan.
/parallel-build [planId]
Triggers execution for the specified plan (or the most recently saved plan if planId is omitted). Stashes uncommitted local workspace changes if necessary, creates an integration worktree, and begins dispatching parallel workers.
/parallel-status [runId]
Displays the current execution status, task states, attempt counts, and error messages for a running or completed build job. If runId is omitted, it defaults to the most recent run.
/parallel-cancel [runId]
Immediately cancels a running parallel build run. Aborts active worker sessions, cleans up worker and integration worktrees from disk, and restores stashed changes if any were created. If runId is omitted, it automatically cancels the currently active run.
/parallel-resume [runId]
Resumes a failed or cancelled build run. It inspects the SQLite state database, resets failed tasks back to pending, skips all previously succeeded tasks, and continues orchestration from the last checkpoint.
/parallel-repair [runId]
Repairs a flawed parallel execution plan that is currently PAUSED_FOR_REPAIR. It invokes the parallel-repair agent to analyze reported defects and apply a validated patch to the plan before resuming.
Configuration & Schema Reference
Plan Schema (Version 1)
Plans are represented as JSON objects. Each task defines its dependencies, file ownership boundaries, and acceptance commands:
{
"version": 1,
"planId": "ado-3279-video-controls",
"title": "Add Video Controls and Insights Sidebar",
"goal": "Implement sidebar controls and update video player component",
"createdAt": "2026-07-22T21:00:00.000Z",
"tasks": [
{
"id": "task-player-controls",
"kind": "worker",
"title": "Add media control helpers",
"description": "Implement play, pause, and seek helper functions in player.ts",
"dependsOn": [],
"owns": [
"src/components/player/controls.ts"
],
"acceptance": [
{
"id": "check-player-tests",
"command": "pnpm test src/components/player/controls.test.ts"
}
]
},
{
"id": "task-sidebar-ui",
"kind": "worker",
"title": "Build Insights Sidebar UI",
"description": "Implement sidebar container component",
"dependsOn": [],
"owns": [
"src/components/sidebar/*"
],
"acceptance": [
{
"id": "check-sidebar-typecheck",
"command": "npx tsc --noEmit"
}
]
},
{
"id": "task-integration",
"kind": "worker",
"title": "Integrate sidebar and player controls",
"description": "Connect player controls to sidebar layout in main view",
"dependsOn": [
"task-player-controls",
"task-sidebar-ui"
],
"owns": [
"src/views/MainView.tsx"
],
"acceptance": [
{
"id": "check-full-build",
"command": "pnpm build"
}
]
}
]
}Registered Tools
The plugin registers five custom tools available to OpenCode agents:
plan_save: Validates plan JSON (checking schema, DAG cycles, and file ownership overlaps) and persistsplan.jsonandplan.mdto.opencode/parallel-builds/plans/<planId>/. Supports overwrite on subsequent runs.execute_plan: TakesplanId, stashes dirty workspace changes, initializes a run in SQLite, and launchesDagScheduler. The scheduler handles all worker dispatches.run_status: Returns formatted Markdown describing run state and per-task statuses.cancel_run: Cancels an active run, aborts subagent sessions, and force-removes physical worktree directories.resume_run: Resets failed/cancelled tasks in an existing run to pending and re-launches the scheduler without re-executing succeeded tasks.dispatch_parallel_tasks: Starts or resumes the background scheduler for a run and returns ready task IDs. Unlikeexecute_plan, it can be called repeatedly to monitor and ensure orchestration is active.report_plan_defect: Called by workers to escalate structural plan flaws to the orchestrator.plan_repair_apply: Applies a validated patch to a run's plan, resets defect tasks, and resumes execution.plan_repair_abandon: Abandons a repair attempt and marks the parallel build as failed.plan_repair_request_human: Requests human intervention for complex plan repairs.
Technical Architecture & Under the Hood
For experienced engineers and contributors, this section details the internal mechanics, state machine, and safety systems of the orchestrator.
1. DAG Validation & Ownership Enforcement
Before any plan is saved, validateExecutionPlan runs a strict multi-pass check:
- Schema Parsing: Validates required fields using Zod.
- Duplicate Check: Ensures all task IDs are unique.
- Unknown Dependency Check: Ensures every ID listed in
dependsOnexists in the task list. - Cycle Detection: Executes a 3-color Depth-First Search (DFS) algorithm to guarantee that task dependencies form a valid Directed Acyclic Graph with no circular loops.
- Overlap Prevention: Verifies that non-integration tasks have completely disjoint
ownsfile paths or glob patterns.
2. Git Worktree Orchestration
To enable concurrent writes without workspace corruption:
- Integration Worktree: Created at
.opencode-parallel-builds/<runId>/integrationfrom the base commit (HEAD). Serves as the single source of truth for merged code during the run. - Worker Worktrees: Created at
.opencode-parallel-builds/<runId>/<taskId>branching offintegration.branch. - Child Sessions: Worker child sessions are spawned via the OpenCode SDK (
client.session.create) scoped directly to the worker worktree directory.
3. Polyglot Toolchain Symlinking
Running dependency installation (npm install, cargo build, pip install) inside every worker worktree creates unacceptable latency and disk usage. When a worktree is created, GitWorktreeManager automatically inspects the source project root and creates symbolic links for pre-existing toolchain directories:
- Node.js:
node_modules - Python:
.venv,venv - Rust:
target - Go:
vendor
This allows tools like npx tsc, go test, cargo check, and pytest to execute inside worker worktrees in milliseconds.
4. Pre-Check File Boundary Enforcement
LLM agents can accidentally write to unowned files despite system prompt instructions. Before executing acceptance checks or staging changes, GitWorktreeManager runs enforceFileBoundaries:
- Executes
git status --porcelain=v1 -uallinside the worker worktree. - Compares modified and untracked files against the task's
ownsarray using path prefix and regex glob matching. - Automatically reverts unowned tracked modifications (
git checkout HEAD -- <file>) and cleans unowned untracked files (git clean -f -- <file>). - Ensures acceptance checks run strictly on the sanitized, boundary-compliant codebase.
5. Feedback-Driven Retry Loop
If a worker fails worker execution or acceptance checks:
DagSchedulercaptures the output (stdout,stderr, or exit codes) from the failed check (e.g., a specific TypeScript compiler error line or test failure trace).- If the task has remaining attempts (default: 3 attempts), the scheduler cleans the worktree and re-dispatches the task.
- The previous compiler/test error log is injected directly into
WorkerInput.lastErrorand appended to the worker prompt (### Previous Attempt Failure). - The subagent uses this feedback to correct its code on the subsequent attempt.
6. Sequential Merging & Automated Conflict Resolution
When a worker completes successfully:
MergeCoordinatoruses an async mutex lock to serialize merges intointegration.branchusinggit merge --no-ff.- If Git reports a textual merge conflict,
MergeCoordinatoridentifies conflicting files viagit diff --name-only --diff-filter=U. - If a
ConflictResolverhook is configured, it passes the conflict markers and file contents to the resolver to clean up conflict markers. - Upon successful resolution, changes are staged and committed with
chore(merge): resolve conflicts in <taskId>. - If conflict resolution fails or no resolver is present, the merge is aborted (
git merge --abort) and the task is marked as failed.
7. Post-Merge Semantic Verification & Rollback
Textual Git merges can succeed even when code is semantically broken (for example, if Task A renames a function in module 1, and Task B calls the old function name in module 2).
After a worker branch is merged into integration.branch:
DagSchedulerexecutes the task's acceptance checks directly onintegration.path.- If the integration check fails due to semantic drift, the scheduler rolls back the integration branch via
git reset --hard HEAD~1. - The task is marked as failed for that attempt, and the compiler's semantic integration error is passed back into the worker retry loop.
8. Event-Sourced SQLite State Machine
All run state is managed by RunStore backed by better-sqlite3 at .opencode/parallel-builds/runs.db.
- Append-Only Event Log: Events (
run.created,worker.started,checks.passed,branch.merged,task.succeeded,task.failed,run.cancelled,run.resumed) are appended torun_events. - Derived State: Run and task states are deterministically updated inside SQLite transactions.
- Resiliency: If OpenCode or the host process restarts,
DagSchedulerreads the database state, skips completed tasks, and resumes orchestration seamlessly.
