简体中文 | English
opencode-flow-engine provides two complementary workflow modes:
- IFlow — Iterative workflow: GSD
- SFlow — Linear workflow: SDD+TDD
- Quick Start
- Workflow Selection
- sFlow Workflow
- iFlow Workflow
- Agents
- Frontend UI Design System
- Tools
- Execution Modes
- Execution Discipline
- Features
- Configuration
- Project Structure
- Acknowledgments
npm install -g opencode-flow-engineAdd to opencode.json:
{
"plugin": ["opencode-flow-engine"]
}Then start a conversation:
"start a workflow" → sFlow (linear, documentation-first)
"start an iteration" → iFlow (cyclic, rapid iteration)
Or use slash commands for cross-workflow actions:
/flow-test → Run comprehensive testing (5-tier)
/flow-review → Run comprehensive review (3-round)
/flow-afk → Activate AFK unattended mode
/flow-intel → Entry scan, generate CONTEXT.md
/flow-architect → Create or refactor ARCHITECTURE.md
/flow-evolve → Sync architecture decisions
/flow-health → Codebase health check
/flow-restyle → One-click visual restyle (frontend only)
# Install all Track 2 skills (18 skills) to global directory
flow-engine install-skills
# Install specific skills with filter
flow-engine install-skills --filter gsap-
# Show help
flow-engine --helpNote: install-skills supports top-level SKILL.md overwrite for skills like frontend-design-pro while preserving subdirectories.
| Workflow | Use Case | Shape | Agent Color |
|---|---|---|---|
| sFlow | Complex features, strict gates, documentation-first | Linear (9 states) | #f8cd93 |
| iFlow | Quick iterations, research-driven, continuous delivery | Cyclic (6 states) | #FFB6C1 |
Guidance: Complex features (3+ files, cross-module, DB schema) → sFlow. Quick fixes, small features → iFlow. Uncertain → start with sFlow.
9 states executed sequentially:
| # | State | Subagent | Artifact | Gate |
|---|---|---|---|---|
| 1 | exploring | need-explorer | Clarified requirements | User confirmation |
| 2 | specifying | spec-writer | proposal.md, specs/, design.md, tasks.md | Artifact validation |
| 3 | ui-design* | ui-director | ui-design.md | UI tokens validated |
| 4 | bridging | contract-builder | execution-contract.md | Contract validated |
| 5 | approved-for-build | — | Approved contract | User approval |
| 6 | executing | build-executor | Implemented code | Tests pass, review passed |
| 7 | debugging | bug-investigator | Bug report, fix | Issue resolved |
| 8 | closing | release-archivist | Verification report | All checks passed |
| 9 | abandoned | — | — | Terminal state |
* The ui-design state is automatically inserted for frontend projects. It uses the ui-director subagent (not spec-writer) to guide a 7-step aesthetic decision process, with 71 brand design references and 9 merged frontend skills.
On context restoration, sFlow detects artifact/state mismatches and auto-repairs:
| State says | Artifacts show | Auto-repair |
|---|---|---|
exploring |
proposal.md exists | → specifying |
specifying |
design.md + tasks.md exist | → bridging |
bridging |
execution-contract.md approved | → approved-for-build |
executing |
All tasks checked | → closing |
6 states in a continuous cycle:
| # | State | Subagent | Artifact | Gate |
|---|---|---|---|---|
| 1 | discussing | iflow-discuss-planner | Clarified requirements, user decisions | User confirmation |
| 2 | researching | iflow-researcher | CONTEXT.md (goals, constraints, findings) | Research complete |
| 3 | planning | iflow-discuss-planner | PLAN.md (XML tasks, wave dependencies) | Plan validated |
| 4 | executing | iflow-plan-executor | Implemented code | Tests pass, deviations handled |
| 5 | verifying | iflow-verifier | VERIFICATION.md (BLOCKER/WARNING) | All checks pass |
| 6 | shipping | iflow-shipper | UAT.md, PR/branch | Shipped, return to discuss |
| Dimension | sFlow | iFlow |
|---|---|---|
| Flow shape | Linear (terminates at closed/abandoned) | Cyclic (returns to discuss) |
| Artifacts | proposal, specs, design, tasks, contract | CONTEXT, PLAN, SUMMARY, VERIFICATION, UAT |
| State dir | .flow-engine/sflow/ |
.flow-engine/iflow/ |
| Methodology | OpenSpec + Superpowers | GSD (Get Stuff Done) |
| Verification | Contract-based validation | Adversarial verification |
| Scope reduction | Guard hook enforced | Agent prompt declaration |
| Agent | Mode | Description |
|---|---|---|
| sFlow | Primary orchestrator | State detection → subagent routing, never writes code |
| need-explorer | Subagent | Requirements clarification via structured questioning |
| spec-writer | Subagent | Generates proposal, specs, design, tasks |
| ui-director | Subagent | Frontend projects: 7-step aesthetic decision process, 71 brand references, produces ui-design.md |
| contract-builder | Subagent | Creates execution contract with boundary control, test plan |
| build-executor | Subagent | TDD/SDD executor: 3 execution modes (inline, batch-inline, SDD) |
| bug-investigator | Subagent | Systematic debugging, root cause analysis, fix verification |
| code-reviewer | Subagent | Spec compliance + code quality review. Enforces Minimality Discipline (5 gates) |
| release-archivist | Subagent | Verify, archive, close changes |
| spec-merger | Subagent | Incremental spec change merging |
| ui-implementer | Subagent | Frontend UI implementation specialist |
| Agent | Mode | Description |
|---|---|---|
| iFlow | Primary orchestrator | Cyclic workflow controller, 6-state orchestration |
| iflow-discuss-planner | Subagent | Discuss + plan: requirements clarification, PLAN.md generation |
| iflow-plan-executor | Subagent | Executor with 4 deviation rules. Can delegate frontend tasks to ui-implementer |
| iflow-verifier | Subagent | Adversarial verification: goal-backward, BLOCKER/WARNING classification |
| iflow-researcher | Subagent | Technical research: discovery levels, tool priority chain, confidence markers |
| iflow-shipper | Subagent | PR creation, UAT.md generation, branch lifecycle management |
| Agent | Mode | Description |
|---|---|---|
| test-engineer | Subagent | Independent comprehensive testing: 5-tier test pyramid (functional, performance, security, compatibility, observability). Triggered by /flow-test or "全面test" / "comprehensive test". Not bound to any workflow state. |
| review-engineer | Subagent | Independent comprehensive review: 5 rounds (R1 spec compliance, R2 code quality + test quality, R3 engineering correctness / Web Interface Guidelines, R4 tech debt, R5 cross-model Spot-Check). Triggered by /flow-review; also consumed by the fix-loop's REVIEWING phase. Not bound to any workflow state. |
| flow-intel | Subagent | Entry scan: Scans codebase to generate project-level CONTEXT.md (architecture, conventions, abstractions). Triggered by /flow-intel. |
| flow-architect | Subagent | Architecture documentation: Creates or refactors ARCHITECTURE.md (module map, dependency rules, ADR). Triggered by /flow-architect. |
| flow-evolve | Subagent | Architecture evolution: Syncs architecture decisions from archived changes into CONTEXT.md. Triggered by /flow-evolve. |
| flow-health | Subagent | Codebase health check: 6+6 dimension risk assessment, redundancy scan, health report generation. Triggered by /flow-health. |
| flow-restyle | Subagent | One-click visual restyle: Preserves functionality, changes only visual style. Frontend projects only. Triggered by /flow-restyle. |
| ui-reviewer | Subagent (sFlow-only) | Design-consistency review: token consistency against ui-design.md + 8-dimension anti-slop + accessibility. Report-only. Dispatched after code-reviewer passes when the diff contains UI files (.css/.tsx/.vue/.html/.svelte) and ui-design.md exists. |
Trigger phrases: "审查并修复" / "fix-loop" (and similar "review and fix" requests).
When triggered, sFlow orchestrates a closed review-fix cycle: review-engineer reviews → gate decision (continue/stop) → sFlow applies fixes → repeat, for a maximum of 10 rounds. Each round is a fresh, stateless review to avoid bias from prior fixes.
- NEVER implement code yourself — always delegate to subagents
- NEVER skip states — must pass through pipeline in order
- NEVER approve your own contract — user must approve
- NEVER close without verification — release-archivist must verify first
opencode-flow-engine has a comprehensive frontend UI design system built into the sFlow workflow, spanning from aesthetic direction to production code delivery.
For frontend projects, the ui-director subagent is automatically inserted between specifying and bridging. It guides a 7-step aesthetic decision process:
Step 1: Tone Confirmation → Pick from 71 brand references or 9 abstract tone cards
Step 2: 4-Question Framework → Purpose, Tone, Constraints, Differentiation
Step 3: Brownfield Alignment → Extract existing visual vocabulary (7 dimensions)
Step 4: 5-Dimension Matrix → Typography, Color (OKLCH), Motion, Space, Texture
Step 5: v0 Draft Review → User confirms before full document
Step 6: Write ui-design.md → Structured output with frontmatter tokens
Step 7: Anti-AI-Slop Check → 8 categories, 42 rules
71 Brand Design References: Built-in library of design systems from Apple, Stripe, Linear, Notion, Claude, Ferrari, and 65+ other brands. Each includes complete color palettes, typography scales, and interaction patterns. Users select a reference brand to inherit design tokens, then fine-tune in Step 4.
The ui-implementer subagent loads 10 frontend specialized skills at runtime, each providing domain-specific rules and patterns. Skill distribution source: Project root skills/ directory (Track 2, 18 skills).
| Phase | Skills Loaded | Purpose |
|---|---|---|
| Design Intake | taste-skill |
Aesthetic direction, anti-slop, design reading |
| Design System | shadcn-ui + ui-ux-pro-max |
Component library theming, 95+ color palettes, 56 font pairings |
| Component Implementation | frontend-design-pro + svg-architect |
Component layout, SVG icon design |
| Motion & Animation | GSAP skill group (gsap-core, gsap-scrolltrigger, gsap-timeline, etc. - 8 skills) | Complex animation scenarios: loading, entrance, scroll-triggered, Banner/Hero animations |
| Quality Pass | polish + frontend-code-review + impeccable + frontend-performance-optimization |
Spacing/alignment, code review, production standards, Core Web Vitals |
GSAP Skills Installation: Run flow-engine install-skills to automatically install 8 GSAP animation skills to the global directory ~/.agents/skills/.
Delivery Checklist: 10-item pre-commit verification (console.log cleanup, interactive states, hardcoded colors, responsive adaptation, accessibility, and more).
The validate_ui_design tool checks ui-design.md for 7 quality gates:
| Check | Rule | Severity |
|---|---|---|
| V1 | Color format (OKLCH required, not plain HEX) | ERROR |
| V2 | Font compliance (no AI-default fonts) | WARNING |
| V3 | Tone declaration (frontmatter must specify tone) | ERROR |
| V4 | Component coverage (≥5 component types) | WARNING |
| V5 | Placeholder strategy section exists | ERROR |
| V6 | Anti-AI-slop coverage (≥6/8 categories) | WARNING |
| V7 | WCAG AA accessibility guidelines | ERROR |
| Tool | Description |
|---|---|
workflow_router / iflow_router |
State detection and subagent routing |
call_flow_agent |
Core: delegates tasks to subagents (sync/async). Supports output_mode (last_message | structured) for JSON extraction, agent_id for resume from subagent store, and optional model_type (lite/quick/standard/deep/ultra/review) for per-call dynamic model tier routing |
flowagent_output / flowagent_cancel |
Async task management |
contract_validator / artifact_inspector |
Artifact validation |
record_decision_point |
Decision point recording (DP-0 to DP-5) |
record_execution_plan |
Wave-based execution plan creation |
record_review_receipt |
Wave review result persistence |
validate_ui_design |
UI design quality validation (7 checks) |
validate_spec, validate_proposal, validate_delta_spec, validate_tasks, validate_contract, validate_design, validate_implementation, detect_sync_conflicts
build-executor automatically selects one of three modes based on task count and dependency analysis:
| Mode | Trigger | Behavior |
|---|---|---|
| Inline | ≤3 tasks, no cross-module deps | Current agent implements directly (TDD applies) |
| Batch Inline | 3-5 tasks, same module, no API changes | Whole batch in one pass, each step TDD |
| SDD | 6+ tasks, cross-module, or dependency chains | Per-task subagent + review receipts + final review |
During execution, sFlow continuously monitors scope. If thresholds are exceeded, it auto-upgrades:
| Preset | Downgrade Condition | Upgrade Trigger |
|---|---|---|
| hotfix | ≤2 files, no architecture changes | 3+ files, DB schema → auto-upgrade to full |
| tweak | ≤4 config files, no code changes | 5+ files, cross-module → auto-upgrade to full |
| full | — | Standard process |
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
| Phase | Action | Evidence |
|---|---|---|
| RED | Write failing test | Run, confirm failure for expected reason |
| GREEN | Write minimal production code | Tests pass (all others still pass) |
| REFACTOR | Clean up while tests stay green | Full suite still passes |
Each task declares read_files (reference boundary) and write_files (modification boundary) in the execution contract. git diff --name-only runs before commit to prevent scope creep.
.flow-engine/sflow/lessons.md — Auto-written on debug exit, auto-scanned before each task
.flow-engine/sflow/subagent-progress.md — Node state (implementing/review/done)
.flow-engine/sflow/checkpoints/ — Structured checkpoints with commit evidence
.flow-engine/sflow/handoffs/ — Cross-session handoff contracts
.flow-engine/sflow/progress.md — Batch completion progress
.flow-engine/sflow/notifications/ — Subagent completion notifications (P0)
.flow-engine/sflow/subagent-store/ — Persisted subagent contexts for resume (P1)
SDD-mode execution is orchestrated via .flow-engine/sflow/execution-plan.json:
- Wave scheduling: Tasks grouped into waves with
serial/parallelstrategy anddepends_ondependencies - Wave dependency validation: Guard hooks detect circular dependencies before execution
- Review receipts: Persisted to
.flow-engine/sflow/reviews/<wave-id>.jsonwith commit range evidence - Triple hash validation: content_hash + artifacts_hash + contract_hash integrity check
- Closing gate: All wave reviews must pass before entering closing state
- 9-state sFlow + 6-state iFlow, automatic state detection and routing
- Guard conditions preventing invalid state transitions
- Automatic state repair (artifact ↔ state inconsistency)
- Frontend/backend project adaptation (auto-inserts ui-design state for frontend)
- Tracks ADDED/MODIFIED/REMOVED/RENAMED specs per change
- Auto-detects spec sync conflicts across changes
- spec-merger merges delta specs on close
- Auto-executed after DP-7 confirmation: When workflow enters
closingstate and user confirms, archive cleanup is automatically executed - Move active artifacts: proposal.md, design.md, tasks.md, execution-contract.md, specs/ are moved to
.flow-engine/sflow/archive/<change-name>/ - Preserve cross-change assets: lessons.md, subagent-store/, notifications/, verification-report.md, archive-metadata.json remain in root directory
- Reset state: state.json is reset to initial state (state: "exploring"), ensuring next workflow can start normally
- Audit trail: Archive is moved, not deleted, preserving historical traceability
| Hook | Trigger | Description |
|---|---|---|
state_transition |
On state transition | Logs transition |
artifact_validation |
After tool execution | Validates artifact completeness |
guard |
Before tool execution | Prevents illegal operations |
pre_process |
Before message processing | Injects context |
post_process |
After tool execution | Detects state transition signals |
continuation |
After context compression | Decides auto-continue |
Subagent completion notifications via file system, eliminating 10+ second polling delay:
- Write: subagent completes →
.flow-engine/sflow/notifications/<task-id>.json(type, subagent, task_id, session_id, completed_at, summary) - Consume: orchestrator auto-scans pending notifications on startup → injects into system prompt → moves to
consumed/ - Deduplication:
consumed/directory with file-level dedup - Reliability: write failure never blocks agent result return (try-catch, warn only)
Full context persistence for long-running subagents, enabling interrupted task recovery:
- Store:
.flow-engine/sflow/subagent-store/<agent_id>/{meta.json, prompt.md, output.md, events.log}+index.json - Resume:
call_flow_agentwithagent_idparameter → reconstructs prompt from original + previous output → creates new session - Index:
index.jsonmaintains searchable agent registry by status
Structured output extraction from subagent responses, reducing orchestrator's dependency on LLM free-text parsing:
- Mode:
output_modeparameter (last_message|structured), default preserves existing behavior - Extraction: JSON block extraction from code fences or bare JSON objects; fails gracefully with
structured_output: null - Schema Hints: Agent-specific hints injected into prompt (build-executor →
{files_changed, tests_passed, blockers}, verifier →{blockers, warnings, score})
Detects incomplete subagent turns and automatically retries:
- Detection: Checks for completion signals (
[TASK_COMPLETE], JSON code fence, bare JSON object); empty output treated as incomplete - Reminder: Injects
<system-reminder>message into session when completion signal is missing - Retry: Synchronous mode only; max 2 retries (1s → 2s backoff); async mode logs completion status without retrying
AFK (Away From Keyboard) mode enables automated workflow execution without user intervention:
- Activation: Triggered by natural language ("afk" / "AFK" / "无人值守") or
/flow-afkcommand - Tier 1 (default): Auto-replies to need-explorer questions using its recommended options + auto-approves contracts
- Tier 2/3: Upgrade via "afk tier2/3" for expanded automation (ui-director decisions, full automation)
- Lifecycle: Activated at workflow start, automatically deactivates on
closing/abandoned— no manual exit needed - Safety: Falls back to user input when subagent output lacks structured recommendations; ignores non-AFK messages during automation
Subagent completion detection uses a hybrid event-driven + polling fallback mechanism:
- Event-driven mode (default):
- Global event bus: Lightweight in-process event bus (Map<sessionID, listener> pattern)
- No message queue dependencies (no Redis, no RabbitMQ)
- No EventEmitter/RxJS dependencies
- Global singleton accessible from both
pollSessionCompletionand plugin hooks
- Plugin Hooks.event integration:
- Plugin registers
Hooks.eventhook to listen forsession.idleevents from OpenCode runtime - On
session.idleevent, hook dispatches event to global event bus viaeventBus.dispatch(sessionID, event) - Event bus invokes registered listener (wakeUp callback) for the session
- Instant completion detection (< 50ms after subagent finishes)
- Plugin registers
- pollSessionCompletion registration:
- At start, registers
sessionID → wakeUpcallback to event bus viaeventBus.register(sessionID, callback) - When event received, immediately reads last message and returns (no status confirmation needed)
- On completion, unregisters listener via
eventBus.unregister(sessionID)to prevent memory leaks
- At start, registers
- Global event bus: Lightweight in-process event bus (Map<sessionID, listener> pattern)
- Polling fallback:
- If no event received within
fallbackThreshold(default 25s), unregisters from event bus and switches to pure polling - Pure polling uses
status()andmessages()APIs to detect completion (200ms interval) - Handles status/messages API failures gracefully with consecutive failure tracking
- If no event received within
- Diagnostic logging: All polling events logged to
.flow-engine/sflow/polling.log:- Event bus operations:
event-bus register,event-bus dispatch,event-bus unregister - Polling lifecycle:
start polling,event received,fallback to polling,completed - Structured format:
[ISO-timestamp] [INFO] [sessionID] message | metadata
- Event bus operations:
- Safety caps: Max 120 polls for new sessions (24s), max wait 120s for async mode
7-step model resolution chain (user configuration only — no built-in default models):
override → model → model_type → config → profile → fallback → unconfigured
Models are resolved only from user configuration (modelProfiles.<tier> and per-agent agents.<name>). There is no built-in default model or default fallback list: when nothing is configured, resolution returns unconfigured and no model field is injected, so OpenCode uses its own default model.
| Tier | Purpose | Typical Agents |
|---|---|---|
lite |
Single-line fixes / trivial edits (dynamic routing target) | — |
quick |
Mechanical execution (archive/format), explore | release-archivist |
standard |
General orchestration / exploration | sFlow, need-explorer, ui-director, spec-merger, ui-implementer, flow-intel, flow-evolve |
deep |
Strongest code capability | spec-writer, contract-builder, build-executor, bug-investigator, ui-implementer, flow-architect, flow-restyle |
ultra |
Complex wave tasks / long context 512K-1M (dynamic routing target) | — |
review |
Review-specialized (role tier) | code-reviewer, test-engineer, review-engineer, flow-health |
lite and ultra have no static agent binding — they are dynamic routing targets selected via the optional model_type parameter of call_flow_agent. Primary agents (sFlow/iFlow) bypass tier resolution and use per-agent agents config only.
{
"plugin": ["opencode-flow-engine"]
}# Project-level (recommended)
sflow init
# User-level global
sflow init --user{
"version": "0.1.0",
"mode": "full",
"agents": {
"sFlow": { "model": "your-provider/glm-5.2", "temperature": 0.6 },
"iFlow": { "model": "your-provider/deepseek-v4-flash", "temperature": 0.6 },
"need-explorer": { "model": "your-provider/step-3.7-flash", "temperature": 0.6 },
"spec-writer": { "model": "your-provider/glm-5.1", "temperature": 0.6 },
"ui-director": { "model": "your-provider/glm-5.1", "temperature": 0.7 },
"contract-builder": { "model": "your-provider/glm-5.1", "temperature": 0.6 },
"build-executor": { "model": "your-provider/glm-5.1", "temperature": 0.7 },
"bug-investigator": { "model": "your-provider/minimax-m2.7", "temperature": 0.6 },
"code-reviewer": { "model": "your-provider/glm-5.1", "temperature": 0.6 },
"release-archivist": { "model": "your-provider/glm-5.1", "temperature": 0.7 },
"spec-merger": { "model": "your-provider/glm-5.1", "temperature": 0.7 },
"ui-implementer": { "model": "your-provider/glm-5.1", "temperature": 0.6 },
"iflow-discuss-planner": { "model": "your-provider/kimi-k2.6", "temperature": 0.6 },
"iflow-plan-executor": { "model": "your-provider/glm-5.1", "temperature": 0.6 },
"iflow-verifier": { "model": "your-provider/minimax-m2.7", "temperature": 0.6 },
"iflow-researcher": { "model": "your-provider/glm-5.1", "temperature": 0.7 },
"iflow-shipper": { "model": "your-provider/glm-5.1", "temperature": 0.6 }
},
"modelProfiles": {
"lite": { "model": "your-provider/step-3.7-flash", "fallback_models": [] },
"quick": { "model": "your-provider/deepseek-v4-flash", "fallback_models": [] },
"standard": { "model": "your-provider/glm-5.1", "fallback_models": [] },
"deep": { "model": "your-provider/glm-5.1", "fallback_models": [] },
"ultra": { "model": "your-provider/long-context-model", "fallback_models": [] },
"review": { "model": "your-provider/glm-5.1", "fallback_models": [] }
}
}Configuration loading priority: project-level .flow-engine/sflow/config.json → user-level ~/.config/opencode/opencode-flow-engine.json
opencode-flow-engine/
├── packages/
│ ├── core/ # Schema, validation, parsing engine
│ ├── plugin-infra/ # Plugin infrastructure
│ │ └── src/
│ │ ├── agents/ # Builders, types, config loading
│ │ ├── hooks/ # 6 lifecycle hook types + guards
│ │ ├── tools/ # Tool definitions and implementations
│ │ ├── features/ # Workflow manager, state manager, MCP,
│ │ │ │ # notification-manager, subagent-store
│ │ └── helpers/ # Utility functions, output-extractor,
│ │ # completion-detector, polling
│ └── shared/ # Shared utilities
├── skills/ # Track 2 frontend skill distribution source (18 skills)
├── workflows/
│ ├── sflow/ # SFlow workflow
│ │ ├── agents/ # 11 agent factories
│ │ ├── skills/ # 11 Track 1 agent-same-name skills (skill-loader injection source)
│ │ └── templates/ # Artifact templates (incl. UI-DESIGN.md)
│ └── iflow/ # IFlow workflow
│ ├── agents/ # 6 agent factories
│ ├── skills/ # Skill definitions
│ └── templates/ # Artifact templates
├── design-reference/ # (Moved into skills/design-reference/data/)
├── sflow-plugin.ts # SFlow-only PluginModule
├── iflow-plugin.ts # IFlow-only PluginModule
├── shared-plugin.ts # Combined PluginModule (default export)
├── docs/ # Technical documentation
└── config.example.json # Example configuration
- OpenCode — Runtime platform, plugin mechanism
- OpenSpec — Planning engine
- Superpowers — Execution discipline
- GSD — iFlow iterative methodology source
- spec-superflow — Validation engine port source
- flow-kit — Test pyramid, review framework, lateral command system, UI design methodology reference (2a-ui-design, anti-AI-slop, brownfield alignment)
- grill-me — Requirements clarification methodology
- getdesign.md — 71 brand design system references