# Advanced Workflows
Source: https://docs.codemachine.co/build-workflows/advanced-workflows
Master workflow definitions with tracks, conditions, modules, and controllers.
This guide covers advanced workflow features: step types, configuration options, tracks, conditions, modules, and controllers.
***
## Workflow Definition
The workflow definition file (`.workflow.js`) is the core of your package. It defines what happens when someone runs your workflow.
### Minimum Workflow
A workflow only needs steps to run:
```javascript example.workflow.js theme={null}
export default {
steps: [
resolveStep('analyst-agent'),
resolveStep('developer-agent'),
resolveStep('reviewer-agent'),
],
};
```
### Full Structure
```javascript example.workflow.js theme={null}
export default {
name: 'My Workflow',
autonomousMode: 'never',
specification: false,
controller: controller('my-controller', {}),
tracks: { /* ... */ },
conditionGroups: [ /* ... */ ],
steps: [ /* ... */ ],
subAgentIds: [ /* ... */ ],
};
```
***
## Step Functions
Three functions are available globally in workflow files:
### resolveStep
Resolves a main agent from `config/main.agents.js`:
```javascript theme={null}
resolveStep('agent-id')
resolveStep('agent-id', { engine: 'claude', interactive: false })
```
### resolveModule
Resolves a module from `config/modules.js` with loop behavior:
```javascript theme={null}
resolveModule('review-module', { loopSteps: 2, loopMaxIterations: 5 })
```
### separator
Creates a visual phase separator in the workflow timeline:
```javascript theme={null}
separator("Planning Phase")
separator("⟲ Development Cycle ⟲")
```
### controller
Defines a controller agent for autonomous execution:
```javascript theme={null}
controller('controller-agent-id', { engine: 'claude' })
```
***
## Step Options
Configure how each step behaves:
| Option | Type | Description |
| ---------------------- | ----------------------------- | ----------------------------------------- |
| `engine` | `string` | AI engine to use |
| `model` | `string` | Specific model override |
| `modelReasoningEffort` | `'low' \| 'medium' \| 'high'` | Reasoning effort level |
| `interactive` | `boolean` | Wait for user input between prompts |
| `executeOnce` | `boolean` | Run only once (skip on re-runs) |
| `tracks` | `string[]` | Only run for specified tracks |
| `conditions` | `string[]` | Only run when ALL conditions are selected |
| `conditionsAny` | `string[]` | Run when ANY condition is selected |
| `agentName` | `string` | Override display name |
| `promptPath` | `string \| string[]` | Override default prompt path |
### Engines
| Engine | Description |
| ------------ | -------------------------- |
| `'claude'` | Anthropic Claude (default) |
| `'codex'` | OpenAI Codex |
| `'cursor'` | Cursor AI |
| `'ccr'` | Claude Code Runner |
| `'opencode'` | OpenCode |
### Examples
```javascript theme={null}
// Basic step
resolveStep('analyst')
// With engine override
resolveStep('developer', { engine: 'codex' })
// Non-interactive step (auto-continues)
resolveStep('code-gen', { interactive: false })
// Conditional step
resolveStep('ui-designer', { conditions: ['has-ui'] })
// Track-specific step
resolveStep('mobile-dev', { tracks: ['mobile-app'] })
// Execute once (skip on workflow resume)
resolveStep('init', { executeOnce: true })
```
***
## Module Options
Modules extend step options with loop behavior:
| Option | Type | Description |
| ------------------- | ---------- | -------------------------------------- |
| `loopSteps` | `number` | How many steps to go back when looping |
| `loopMaxIterations` | `number` | Maximum loop iterations |
| `loopSkip` | `string[]` | Agent IDs to skip when looping back |
```javascript theme={null}
// Loop back 2 steps, max 5 iterations
resolveModule('review-agent', {
loopSteps: 2,
loopMaxIterations: 5
})
// Loop back 6 steps, skip certain agents
resolveModule('task-checker', {
loopSteps: 6,
loopMaxIterations: 20,
loopSkip: ['runtime-prep', 'init']
})
```
Modules are agents that can loop back to earlier steps. Use them for review cycles or iterative refinement until a condition is met.
***
## Tracks
Tracks let users choose different workflow paths. Only one track can be selected at runtime.
```javascript theme={null}
tracks: {
question: 'Choose your project type:',
options: {
'landing-page': {
label: 'Landing Page',
description: 'Single page website'
},
'full-app': {
label: 'Full Application',
description: 'Complete web application'
},
'api-only': {
label: 'API Only',
description: 'Backend API without frontend'
},
},
},
```
Use tracks when you have mutually exclusive paths that significantly change the workflow.
### Track-Filtered Steps
```javascript theme={null}
steps: [
resolveStep('planner'),
resolveStep('frontend-dev', { tracks: ['landing-page', 'full-app'] }),
resolveStep('backend-dev', { tracks: ['full-app', 'api-only'] }),
resolveStep('deployer'),
]
```
***
## Condition Groups
Conditions are feature toggles that enable or disable specific steps. Unlike tracks, multiple conditions can be selected.
```javascript theme={null}
conditionGroups: [
{
id: 'features',
question: 'What features do you need?',
multiSelect: true,
conditions: {
'has-api': { label: 'API', description: 'REST or GraphQL API' },
'has-auth': { label: 'Auth', description: 'User authentication' },
'has-db': { label: 'Database', description: 'Database integration' },
},
},
],
```
### Nested Conditions
Conditions can have children that appear based on parent selection:
```javascript theme={null}
conditionGroups: [
{
id: 'deployment',
question: 'Where will you deploy?',
multiSelect: false,
conditions: {
'cloud': { label: 'Cloud', description: 'AWS, GCP, or Azure' },
'self-hosted': { label: 'Self-hosted', description: 'Your own servers' },
},
children: {
'cloud': {
question: 'Which cloud provider?',
multiSelect: false,
conditions: {
'aws': { label: 'AWS', description: 'Amazon Web Services' },
'gcp': { label: 'GCP', description: 'Google Cloud Platform' },
'azure': { label: 'Azure', description: 'Microsoft Azure' },
},
},
},
},
],
```
### Track-Specific Conditions
Condition groups can be limited to specific tracks:
```javascript theme={null}
conditionGroups: [
{
id: 'advanced-features',
question: 'Select advanced features:',
multiSelect: true,
tracks: ['full-app'], // Only shown when 'full-app' track is selected
conditions: {
'microservices': { label: 'Microservices', description: 'Service-based architecture' },
'caching': { label: 'Caching', description: 'Redis or Memcached' },
},
},
],
```
### Condition-Filtered Steps
```javascript theme={null}
steps: [
resolveStep('planner'),
resolveStep('api-architect', { conditions: ['has-api'] }),
resolveStep('auth-setup', { conditions: ['has-auth'] }),
resolveStep('db-designer', { conditionsAny: ['has-db', 'has-api'] }),
]
```
Use `conditions` when ALL listed conditions must be selected. Use `conditionsAny` when ANY of the listed conditions enables the step.
***
## Controllers
Controllers are special agents that drive workflows autonomously. They can approve step transitions without user input.
```javascript theme={null}
export default {
name: 'My Workflow',
controller: controller('my-controller-agent', { engine: 'claude' }),
autonomousMode: 'always',
// ...
};
```
Controllers are in beta. The workflow can still run without a controller in manual mode.
### Workflow Signals MCP
Controllers and step agents communicate through the `workflow-signals` MCP. **Both must be configured** for autonomous mode to work.
The controller approves or rejects step transitions.
```javascript main.agents.js theme={null}
{
id: 'my-controller-agent',
name: 'Project Controller',
role: 'controller',
promptPath: path.join(promptsDir, 'controller', 'main.md'),
mcp: [
{
server: 'workflow-signals',
only: ['approve_step_transition', 'get_pending_proposal'],
},
],
}
```
Step agents propose when they're done.
```javascript main.agents.js theme={null}
{
id: 'developer',
name: 'Developer',
promptPath: path.join(promptsDir, 'developer', 'main.md'),
mcp: [
{
server: 'workflow-signals',
only: ['propose_step_completion'],
},
],
}
```
| Agent Type | MCP Tools |
| ----------- | ------------------------------------------------- |
| Controller | `approve_step_transition`, `get_pending_proposal` |
| Step Agents | `propose_step_completion` |
View a complete autonomous workflow with controller and step agents
***
## Autonomous Mode
Control how the workflow runs:
| Value | Behavior | Toggle |
| ---------- | ------------------------------------------------ | ------------------------------------------ |
| `'never'` | Always manual - user controls each step | Locked - can't switch to auto |
| `'always'` | Always autonomous - controller drives everything | Locked - can't switch to manual |
| `true` | Defaults to autonomous mode | User can toggle to manual with `Shift+Tab` |
| `false` | Defaults to manual mode | User can toggle to auto with `Shift+Tab` |
```javascript theme={null}
export default {
name: 'My Workflow',
autonomousMode: true, // Defaults to auto, user can toggle
// ...
};
```
Use `true` or `false` for most workflows - this gives users flexibility to switch modes. Use `'always'` or `'never'` only when you want to lock the mode.
***
## Sub-Agents
Sub-agents are helper agents that main agents can invoke for specialized tasks. **Both the workflow and main agent must be configured.**
### Workflow Configuration
Declare available sub-agents in your workflow file:
```javascript example.workflow.js theme={null}
export default {
name: 'My Workflow',
steps: [
resolveStep('orchestrator', { interactive: false }),
],
subAgentIds: [
'code-generator',
'test-runner',
'doc-writer',
],
};
```
### Agent Coordination MCP
The main agent that orchestrates sub-agents needs the `agent-coordination` MCP:
```javascript main.agents.js theme={null}
{
id: 'orchestrator',
name: 'Orchestrator',
description: 'Coordinates sub-agents for specialized tasks',
promptPath: path.join(promptsDir, 'orchestrator', 'main.md'),
mcp: [
{
server: 'agent-coordination',
only: ['run_agents', 'get_agent_status', 'list_available_agents'],
targets: ['code-generator', 'test-runner', 'doc-writer'],
},
],
}
```
| Field | Description |
| --------- | ---------------------------------------- |
| `server` | Must be `'agent-coordination'` |
| `only` | Limit which MCP tools the agent can use |
| `targets` | Restrict which sub-agents can be invoked |
Both `subAgentIds` in the workflow and `agent-coordination` MCP on the main agent must be configured for sub-agent orchestration to work.
Sub-agents are defined in `config/sub.agents.js`.
View a complete workflow using sub-agents
***
## Specification Mode
Enable specification mode to require a spec file before running:
```javascript theme={null}
export default {
name: 'My Workflow',
specification: true,
// ...
};
```
When `specification: true`, CodeMachine prompts for a specification file path at workflow start.
***
## Next Steps
See complete real-world workflow examples
# Build Agents
Source: https://docs.codemachine.co/build-workflows/build-agents
Configure main agents, sub-agents, modules, and controllers for your workflow.
This is the first step to create a workflow: defining **who**. Agents are the actors that execute each step of your workflow.
Agents are configured in JavaScript files inside the `config/` folder. Each agent type has its own configuration file.
| File | Agent Type | Purpose |
| ---------------- | ----------- | -------------------------------------- |
| `main.agents.js` | Main agents | Core workflow steps |
| `modules.js` | Modules | Agents with loop behavior |
| `sub.agents.js` | Sub-agents | Delegated tasks spawned by main agents |
Controllers are defined in `main.agents.js` with `role: 'controller'`. They're main agents with special orchestration capabilities.
***
## Main Agents
Main agents are the core building blocks of your workflow. Each main agent runs as a step in the workflow sequence.
### Basic Structure
```javascript config/main.agents.js theme={null}
const path = require('node:path');
const promptsDir = path.join(__dirname, '..', 'prompts', 'templates');
module.exports = [
{
id: 'planner',
name: 'Project Planner',
description: 'Analyzes requirements and creates implementation plan',
promptPath: path.join(promptsDir, 'planner', 'main.md'),
},
];
```
### Agent Fields
| Field | Required | Description |
| -------------------- | -------- | --------------------------------------------------- |
| `id` | Yes | Unique identifier (lowercase, hyphens) |
| `name` | Yes | Display name shown in UI |
| `description` | Yes | Brief description of what the agent does |
| `promptPath` | Yes | Path or array of paths to prompt files |
| `chainedPromptsPath` | No | Array of chained prompt paths (multi-step agents) |
| `role` | No | Set to `'controller'` for controller agents only |
| `engine` | No | AI engine to use (defaults to workflow default) |
| `model` | No | AI model to use (defaults to engine default) |
| `tracks` | No | Array of track IDs this agent runs for |
| `conditions` | No | Array of condition IDs (runs when ALL are selected) |
| `conditionsAny` | No | Array of condition IDs (runs when ANY is selected) |
***
## Prompt Path: String vs Array
The `promptPath` field accepts either a single path or an array of paths.
One prompt file loaded as the agent's instructions.
```javascript theme={null}
{
id: 'planner',
promptPath: path.join(promptsDir, 'planner', 'main.md'),
}
```
Multiple prompt files **merged into one** and shown to the agent as a single prompt. Use this to split large prompts into organized files.
```javascript theme={null}
{
id: 'planner',
promptPath: [
path.join(promptsDir, 'planner', 'persona.md'),
path.join(promptsDir, 'planner', 'instructions.md'),
path.join(promptsDir, 'planner', 'examples.md'),
],
}
```
**promptPath array** = Files merged into one prompt, shown at once.
**chainedPromptsPath** = Separate prompts injected sequentially, one after another with user interaction between each.
### When to Use Array promptPath
| Use Case | Example |
| ------------------------- | ------------------------------------------------------------- |
| Organizing large prompts | Split persona, instructions, and examples into separate files |
| Reusing prompt components | Share common instructions across agents |
| Maintaining readability | Keep individual files focused and manageable |
```javascript theme={null}
// Complex agent with organized prompt structure
{
id: 'architect',
name: 'System Architect',
description: 'Designs system architecture',
promptPath: [
path.join(promptsDir, 'shared', 'coding-standards.md'),
path.join(promptsDir, 'architect', 'persona.md'),
path.join(promptsDir, 'architect', 'workflow.md'),
path.join(promptsDir, 'architect', 'output-format.md'),
],
}
```
***
## Single-Step vs Multi-Step
Agents can be single-step or multi-step based on whether they have chained prompts.
One prompt file, injected once. Best for focused tasks.
```javascript theme={null}
{
id: 'code-reviewer',
name: 'Code Reviewer',
description: 'Reviews code for issues and improvements',
promptPath: path.join(promptsDir, 'reviewer', 'main.md'),
}
```
Multiple prompts injected sequentially into the same session. Best for complex workflows with progressive context.
```javascript theme={null}
{
id: 'onboarding-guide',
name: 'Onboarding Guide',
description: 'Guides users through project setup',
promptPath: path.join(promptsDir, 'onboarding', 'main.md'),
chainedPromptsPath: [
path.join(promptsDir, 'onboarding', 'chained', 'step-01-intro.md'),
path.join(promptsDir, 'onboarding', 'chained', 'step-02-setup.md'),
path.join(promptsDir, 'onboarding', 'chained', 'step-03-config.md'),
],
}
```
Learn how to write chained step files
### When to Use Each
| Type | Use When |
| --------------- | --------------------------------------------------------------- |
| **Single-step** | Focused tasks, smaller prompts, minimal context needed |
| **Multi-step** | Q\&A flows, progressive context building, conversational agents |
Multi-step agents maintain the same session throughout all steps. The agent remembers everything from previous steps.
***
## Modules
Modules are main agents with loop behavior. They can send the workflow back to earlier steps, creating validation gates and iteration cycles.
### Module Structure
```javascript config/modules.js theme={null}
const path = require('node:path');
const promptsDir = path.join(__dirname, '..', 'prompts', 'modules');
module.exports = [
{
id: 'quality-gate',
name: 'Quality Gate',
description: 'Validates work and loops back if issues found',
promptPath: path.join(promptsDir, 'quality-gate', 'main.md'),
behavior: {
type: 'loop',
action: 'stepBack',
},
},
];
```
### Module Fields
In addition to standard agent fields, modules have:
| Field | Required | Description |
| ----------------- | -------- | -------------------- |
| `behavior.type` | Yes | Must be `'loop'` |
| `behavior.action` | Yes | Must be `'stepBack'` |
### How Modules Control Flow
Modules communicate with the workflow by writing to a directive file when validation **fails**:
```
.codemachine/memory/directive.json
```
```json theme={null}
{
"action": "loop",
"reason": "Validation failed: 3 tests failing, missing error handling",
"target": "developer"
}
```
If validation **passes**, no action is needed. The workflow continues to the next step by default.
Your module's prompt **must** include instructions on how to validate and how to write the directive file. Without these instructions, the agent won't know how to trigger the loop.
Learn how to write prompts that instruct modules to validate and write directives
Configure MCP for directive-based workflow control
### Common Module Patterns
Check work quality, fix issues, re-check until passing.
```javascript theme={null}
{
id: 'validator',
name: 'Code Validator',
description: 'Validates code quality and loops if issues found',
promptPath: path.join(promptsDir, 'validator', 'main.md'),
behavior: { type: 'loop', action: 'stepBack' },
}
```
Review output, request changes, iterate until approved.
```javascript theme={null}
{
id: 'reviewer',
name: 'Review Module',
description: 'Reviews and requests revisions until approved',
promptPath: path.join(promptsDir, 'reviewer', 'main.md'),
behavior: { type: 'loop', action: 'stepBack' },
}
```
Block progression until quality threshold is met.
```javascript theme={null}
{
id: 'quality-gate',
name: 'Quality Gate',
description: 'Ensures quality standards before proceeding',
promptPath: path.join(promptsDir, 'quality-gate', 'main.md'),
behavior: { type: 'loop', action: 'stepBack' },
}
```
### Workflow File Options
When using modules in your workflow file, you can configure loop behavior:
```javascript theme={null}
resolveModule('quality-gate', {
loopSteps: 2, // How many steps to go back
loopMaxIterations: 3, // Maximum loop attempts
loopSkip: ['logger'], // Agents to skip on re-loop
})
```
***
## Sub-Agents
Sub-agents are helper agents that main agents can spawn during execution. They run as separate sessions and return results to the calling agent.
### When to Use Sub-Agents
* Delegating specialized subtasks
* Parallel task execution
* Context isolation for specific work
* Reusable agent capabilities
### Sub-Agent Types
Pre-defined prompt file. You define the prompt at build time.
```javascript config/sub.agents.js theme={null}
{
id: 'test-writer',
name: 'Test Writer',
description: 'Writes unit tests for given code',
mirrorPath: path.join(promptsDir, 'sub-agents', 'test-writer.md'),
}
```
No prompt file. The main agent generates the prompt at runtime.
```javascript config/sub.agents.js theme={null}
{
id: 'specialist',
name: 'Dynamic Specialist',
description: 'Specialized agent generated at runtime',
// No mirrorPath - empty .md file created in .codemachine/agents/
}
```
### Why Sub-Agent Prompts Live in `.codemachine/`
Unlike main agents whose prompts are in the `prompts/` folder, sub-agent prompts live in the runtime `.codemachine/agents/` folder. This design enables:
* **Dynamic prompt generation** - A main agent (like an `agent-builder`) can write prompts for sub-agents at runtime
* **Cross-agent access** - Other agents can read and modify sub-agent prompts during workflow execution
* **Flexibility** - Use static prompts via `mirrorPath`, or leave it empty for fully dynamic sub-agents that receive instructions when invoked
Sub-agents are also accessible via the `codemachine run` command for direct execution.
### Sub-Agent Fields
| Field | Required | Description |
| ------------- | ----------- | ------------------------------- |
| `id` | Yes | Unique identifier |
| `name` | Yes | Display name |
| `description` | Yes | What the sub-agent does |
| `mirrorPath` | Static only | Path to pre-defined prompt file |
### Invoking Sub-Agents
Sub-agents must be invoked via MCP tools or CLI commands.
**Example orchestrator with agent-coordination MCP:**
```javascript main.agents.js theme={null}
{
id: 'blueprint-orchestrator',
name: 'Blueprint Orchestrator',
description: 'Coordinates architecture sub-agents',
promptPath: path.join(promptsDir, 'orchestrator', 'main.md'),
mcp: [
{
server: 'agent-coordination',
only: ['run_agents', 'get_agent_status', 'list_available_agents'],
targets: ['data-architect', 'api-architect', 'ui-architect'],
},
],
}
```
Include MCP tools documentation in your main agent's prompt if it needs to call sub-agents.
Learn how to write prompts for agents that orchestrate sub-agents
Configure MCP for sub-agents
Run sub-agents via CLI
See complete workflow
***
## Controllers
Controllers are special agents that orchestrate autonomous workflows. They respond on behalf of the user, driving the entire workflow.
Controllers require `role: 'controller'` and must be configured with the `workflow-signals` MCP to approve step transitions.
**Example controller and step agent with workflow-signals MCP:**
```javascript main.agents.js theme={null}
module.exports = [
// Controller - Approves/rejects step transitions
{
id: 'project-controller',
name: 'Project Controller',
role: 'controller',
promptPath: path.join(promptsDir, 'controller', 'main.md'),
mcp: [
{
server: 'workflow-signals',
only: ['approve_step_transition', 'get_pending_proposal'],
},
],
},
// Step agents - Propose completion
{
id: 'pm',
name: 'Product Manager',
promptPath: path.join(promptsDir, 'pm', 'main.md'),
mcp: [
{
server: 'workflow-signals',
only: ['propose_step_completion'],
},
],
},
// ... other step agents with same MCP config
];
```
Both controller and all step agents must have `workflow-signals` MCP configured for autonomous mode to work.
Configure MCP for autonomous mode
See complete autonomous workflow
***
## Built-in MCP Servers
CodeMachine provides built-in MCP servers for agent coordination and workflow control. Configure these on your agents using the `mcp` field.
### MCP Configuration Fields
| Field | Description |
| --------- | -------------------------------------------------------------------- |
| `server` | The MCP server name (`'workflow-signals'` or `'agent-coordination'`) |
| `only` | Array of tool names to expose (limits available tools) |
| `targets` | Array of sub-agent IDs that can be invoked (agent-coordination only) |
***
### Workflow Signals
Controllers and step agents communicate through the `workflow-signals` MCP. Step agents propose completion, and the controller approves or rejects.
Both controller and all step agents must have `workflow-signals` MCP configured for autonomous mode to work.
The controller approves or rejects step transitions.
```javascript theme={null}
{
id: 'project-controller',
name: 'Project Controller',
description: 'Orchestrates workflow and approves transitions',
role: 'controller',
promptPath: path.join(promptsDir, 'controller', 'main.md'),
mcp: [
{
server: 'workflow-signals',
only: ['approve_step_transition', 'get_pending_proposal'],
},
],
}
```
| Tool | Description |
| ------------------------- | --------------------------------------------- |
| `approve_step_transition` | Accept or reject a step's completion proposal |
| `get_pending_proposal` | Read the current pending proposal from a step |
Step agents propose when they're done.
```javascript theme={null}
{
id: 'pm',
name: 'Product Manager',
description: 'Creates product requirements',
promptPath: path.join(promptsDir, 'pm', 'main.md'),
mcp: [
{
server: 'workflow-signals',
only: ['propose_step_completion'],
},
],
}
```
| Tool | Description |
| ------------------------- | ---------------------------------------- |
| `propose_step_completion` | Signal that the step is ready for review |
View a complete autonomous workflow with controller and step agents
***
### Agent Coordination
Main agents or controllers that orchestrate sub-agents need the `agent-coordination` MCP configured.
```javascript theme={null}
{
id: 'orchestrator',
name: 'Orchestrator',
description: 'Coordinates sub-agents for specialized tasks',
promptPath: path.join(promptsDir, 'orchestrator', 'main.md'),
mcp: [
{
server: 'agent-coordination',
only: ['run_agents', 'get_agent_status'],
targets: ['code-generator', 'test-runner', 'doc-writer'],
},
],
}
```
| Tool | Description |
| ----------------------- | ----------------------------- |
| `list_available_agents` | Discover available sub-agents |
| `run_agents` | Execute sub-agent scripts |
| `get_agent_status` | Check execution status |
| `list_active_agents` | See currently running agents |
View a complete workflow using sub-agents with agent-coordination MCP
***
## Agent Characters
Agent characters give your agents visual personality in the CLI. Each agent can have custom ASCII faces and phrases.
### Character Configuration
```json config/agent-characters.json theme={null}
{
"personas": {
"swagger": {
"baseFace": "(⌐■_■)",
"expressions": {
"thinking": "(╭ರ_•́)",
"tool": "<(•_•<)",
"error": "(╥﹏╥)",
"idle": "(⌐■_■)"
},
"phrases": {
"thinking": ["Processing...", "Working on it..."],
"tool": ["Got what I needed", "Perfect, moving on"],
"error": ["Hmm, that didn't work", "Trying another way"],
"idle": ["Ready when you are", "Your turn"]
}
}
},
"agents": {
"planner": "swagger",
"reviewer": "analytical"
},
"defaultPersona": "friendly"
}
```
### Pre-built Styles
| Style | Base Face | Best For |
| ------------ | ----------- | ------------------------ |
| `swagger` | `(⌐■_■)` | Cool, confident agents |
| `friendly` | `(˶ᵔ ᵕ ᵔ˶)` | Warm, helpful agents |
| `analytical` | `[•_•]` | Logical, precise agents |
| `cheerful` | `◕‿◕` | Upbeat, positive agents |
| `technical` | `{•_•}` | Developer-focused agents |
| `precise` | `<•_•>` | Validation, QA agents |
### Custom Characters
Create custom characters by defining all expressions and phrases:
```json theme={null}
{
"personas": {
"my-custom-style": {
"baseFace": "[◉_◉]",
"expressions": {
"thinking": "[◉~◉]",
"tool": "[◉!◉]",
"error": "[x_x]",
"idle": "[◉_◉]"
},
"phrases": {
"thinking": ["Analyzing...", "Computing..."],
"tool": ["Data received", "Processing result..."],
"error": ["Error encountered", "Retrying..."],
"idle": ["Standing by", "Awaiting input"]
}
}
}
}
```
If no character is defined for an agent, it falls back to the `swagger` character.
***
## Engine & Model
Each agent can use a different AI engine and model. Configure `engine` and `model` fields to optimize for your use case.
See available engines, model options, reasoning effort, and fallback system
***
## Track & Condition Filtering
Filter when agents run based on user-selected tracks and conditions.
### Agent-Level Filtering
Control when an entire agent runs:
```javascript theme={null}
{
id: 'frontend-specialist',
name: 'Frontend Specialist',
description: 'Handles frontend implementation',
promptPath: path.join(promptsDir, 'frontend', 'main.md'),
tracks: ['frontend', 'fullstack'], // Only runs for these tracks
conditions: ['has_ui'], // AND only if has_ui is selected
}
```
### Step-Level Filtering
For multi-step agents, filter individual steps:
```javascript theme={null}
{
id: 'developer',
name: 'Full Stack Developer',
description: 'Implements features',
promptPath: path.join(promptsDir, 'developer', 'main.md'),
chainedPromptsPath: [
// Always loads
path.join(promptsDir, 'developer', 'chained', 'step-01-setup.md'),
// Only for frontend track
{
path: path.join(promptsDir, 'developer', 'chained', 'step-02-react.md'),
tracks: ['frontend'],
},
// Only if mobile condition selected
{
path: path.join(promptsDir, 'developer', 'chained', 'step-03-mobile.md'),
conditions: ['has_mobile'],
},
],
}
```
### Filtering Rules
* **Both track AND conditions must match** if both are specified
* **Empty arrays = always runs/loads**
* Agent-level filtering is checked first, then step-level
***
## Complete Example
Here's a complete `main.agents.js` with multiple agent types:
```javascript config/main.agents.js theme={null}
const path = require('node:path');
const promptsDir = path.join(__dirname, '..', 'prompts', 'templates');
module.exports = [
// Single-step main agent
{
id: 'planner',
name: 'Project Planner',
description: 'Analyzes requirements and creates implementation plan',
promptPath: path.join(promptsDir, 'planner', 'main.md'),
engine: 'claude',
model: 'opus',
},
// Multi-step main agent with filtering
{
id: 'developer',
name: 'Developer',
description: 'Implements the planned features',
promptPath: path.join(promptsDir, 'developer', 'main.md'),
chainedPromptsPath: [
path.join(promptsDir, 'developer', 'chained', 'step-01-setup.md'),
{
path: path.join(promptsDir, 'developer', 'chained', 'step-02-frontend.md'),
tracks: ['frontend', 'fullstack'],
},
{
path: path.join(promptsDir, 'developer', 'chained', 'step-03-backend.md'),
tracks: ['backend', 'fullstack'],
},
],
engine: 'codex',
modelReasoningEffort: 'medium',
},
// Controller agent
{
id: 'project-controller',
name: 'Project Owner',
description: 'Orchestrates the workflow autonomously',
role: 'controller',
promptPath: path.join(promptsDir, 'controller', 'project-owner.md'),
engine: 'claude',
model: 'opus',
},
];
```
***
## Next Steps
Create prompts for your agents
Put it all together in a workflow
# Import Workflows
Source: https://docs.codemachine.co/build-workflows/import-workflows
Install workflows from local directories, GitHub, and other git repositories.
Import workflow packages from local directories, GitHub repositories, or any git URL.
***
## Quick Start
```bash theme={null}
codemachine import ./my-workflow
codemachine import user/repo
codemachine import https://github.com/user/repo
```
```
/import ./my-workflow
/import user/repo
/import https://github.com/user/repo
```
After importing, your workflow appears in the selection menu when you run `codemachine`.
***
## Source Formats
CodeMachine supports multiple import source formats:
| Format | Example | Resolution |
| --------------------- | ------------------------------ | ------------- |
| Local path (absolute) | `/path/to/folder` | local-path |
| Local path (relative) | `./my-package` or `../other` | local-path |
| Local path (home) | `~/projects/my-workflow` | local-path |
| Short name | `package-name` | github-search |
| Owner/repo | `user/repo` | github-repo |
| Full URL | `https://github.com/user/repo` | github-repo |
| Git SSH | `git@github.com:user/repo.git` | git-url |
### Resolution Priority
When you run an import, CodeMachine checks sources in this order:
1. **Local path** — if it's absolute, starts with `./`, `../`, or `~`
2. **HTTPS URLs** — full GitHub or git URLs
3. **Git SSH URLs** — `git@` format
4. **Owner/repo format** — checks if local path exists first
5. **Short name** — searches GitHub for matching packages
***
## Local Imports
Import workflows from your local filesystem for development and testing.
### Path Formats
```bash theme={null}
# Absolute path
codemachine import /home/user/my-workflows
# Relative path
codemachine import ./my-local-package
codemachine import ../shared-workflows
# Home directory
codemachine import ~/projects/codemachine-prompts
```
Local imports require a valid manifest file (`codemachine.json` or `.codemachine.json`) in the source directory.
### Local Path Resolution
For a path to be recognized as local, it must:
* Be an absolute path (starts with `/`)
* Start with `./` or `../` (relative)
* Start with `~` (home directory)
* Contain a valid manifest file
***
## GitHub Imports
Import workflows directly from GitHub repositories.
### By Owner/Repo
```bash theme={null}
codemachine import username/my-workflow-codemachine
```
### By Full URL
```bash theme={null}
codemachine import https://github.com/username/my-workflow-codemachine
```
### By Short Name
Search GitHub for packages by name:
```bash theme={null}
codemachine import my-workflow
```
Short name search looks for repositories with the `-codemachine` suffix on GitHub.
### Git SSH
```bash theme={null}
codemachine import git@github.com:user/repo.git
```
***
## Manifest Files
Every importable package needs a manifest file (`codemachine.json` or `.codemachine.json`) at the root with `name` and `version` fields.
For details on creating and configuring manifest files, see [Publish Workflow](/build-workflows/publish-workflow#create-the-manifest).
***
## Validation Requirements
Both local and remote imports must pass validation:
Must have `codemachine.json` or `.codemachine.json` with `name` and `version` fields.
Must have `config/main.agents.js` with agent definitions.
Must have at least one `.workflow.js` file in the workflows directory.
If missing, you'll see a warning but import will proceed.
***
## Import Location
Imported packages are stored in:
```
~/.codemachine/imports/{name}-codemachine/
```
For example, importing a package named `codemachine-one` creates:
```
~/.codemachine/imports/codemachine-one-codemachine/
├── codemachine.json
├── config/
│ ├── main.agents.js
│ └── ...
├── templates/
│ └── workflows/
│ └── codemachine-one.workflow.js
└── prompts/
└── ...
```
***
## Examples
### Import Local Development Package
```bash theme={null}
# Create a local package
mkdir -p ~/my-workflow/config ~/my-workflow/templates/workflows
# Add manifest
echo '{"name": "my-workflow", "version": "1.0.0"}' > ~/my-workflow/codemachine.json
# Add required files...
# Import it
codemachine import ~/my-workflow
```
### Import from GitHub
```bash theme={null}
# By owner/repo
codemachine import username/my-workflow-codemachine
# By short name (searches GitHub)
codemachine import my-workflow
# By full URL
codemachine import https://github.com/username/my-workflow-codemachine
```
### Import Using TUI
Within CodeMachine, use the `/import` command:
```
/import ./my-local-package
/import username/my-workflow-codemachine
```
***
## Troubleshooting
Ensure your package has either `codemachine.json` or `.codemachine.json` at the root level with valid `name` and `version` fields.
Create `config/main.agents.js` with at least one agent definition:
```javascript theme={null}
module.exports = [
{
id: 'my-agent',
name: 'My Agent',
description: 'Agent description',
promptPath: './prompts/my-agent.md'
}
];
```
Create at least one `.workflow.js` file in `templates/workflows/`:
```javascript theme={null}
export default {
steps: [
resolveStep('my-agent'),
],
};
```
Make sure your path:
* Starts with `/` (absolute), `./`, `../` (relative), or `~` (home)
* Points to an existing directory
* Contains a valid manifest file
***
## Next Steps
Share your workflow with others on GitHub
# Model Configuration
Source: https://docs.codemachine.co/build-workflows/model-configuration
Configure and override AI models in your workflows.
CodeMachine uses a hierarchical configuration system for engine and model selection. Each layer can override the previous, giving you fine-grained control.
[Default engines and models](#default-engine-&-model)
Override in `main.agents.js`
Override in `workflow.js`
Final resolution with [auth fallback](#engine-fallback-system)
## Available Engines
| Engine ID | Name | Default Model | Reasoning Effort |
| ---------- | ------------------ | --------------------- | ---------------- |
| `claude` | Claude Code | `opus` | No |
| `ccr` | Claude Code Router | `sonnet` | No |
| `codex` | Codex | `gpt-5.2-codex` | Yes (`medium`) |
| `opencode` | OpenCode | `opencode/big-pickle` | No |
| `cursor` | Cursor | `auto` | No |
| `mistral` | Mistral Vibe | `devstral-2` | No |
| `auggie` | Auggie CLI | `auto` | No |
Engines other than `claude`, `codex`, and `opencode` are experimental and might not be stable.
## Agent Configuration
Configure engine and model in `config/main.agents.js` for individual agents.
### Agent Schema
```javascript theme={null}
{
id: string, // Unique agent identifier (required)
name: string, // Display name shown in UI (required)
description: string, // Brief description (required)
promptPath: string | string[], // Path to prompt file(s) (required)
promptPath: string[], // Chained prompt paths (optional)
engine: string, // Engine to use (optional)
model: string, // Model to use (optional)
modelReasoningEffort: string, // 'low' | 'medium' | 'high' (optional)
}
```
### Examples
**Engine + Model:**
```javascript theme={null}
// config/main.agents.js
export const mainAgents = {
'my-code-generator': {
id: 'my-code-generator',
promptPath: 'agents/code-generator/main.prompt.md',
engine: 'claude',
model: 'opus',
},
};
```
**With Reasoning Effort (Codex only):**
```javascript theme={null}
'my-analyzer': {
id: 'my-analyzer',
promptPath: 'agents/analyzer/main.prompt.md',
engine: 'codex',
model: 'gpt-5.2-codex',
modelReasoningEffort: 'high',
},
```
**Engine Only (uses engine's default model):**
```javascript theme={null}
'my-agent': {
id: 'my-agent',
promptPath: 'agents/my-agent/main.prompt.md',
engine: 'claude', // Uses 'opus' (Claude's default)
}
```
## Workflow Step Overrides
Override engine and model per step in your `workflow.js` files.
### Override Schema
```javascript theme={null}
{
engine: string, // Override engine
model: string, // Override model
modelReasoningEffort: string, // 'low' | 'medium' | 'high'
}
```
### Using `resolveStep()`
```javascript theme={null}
// templates/workflows/my.workflow.js
import { resolveStep } from '#src/workflows/utils/resolvers/index.js';
export default {
id: 'my-workflow',
name: 'My Custom Workflow',
steps: [
// No overrides - uses agent's config
resolveStep('my-agent'),
// Engine override
resolveStep('code-generator', {
engine: 'claude',
}),
// Engine + model + reasoning
resolveStep('complex-analysis', {
engine: 'codex',
model: 'gpt-5.2-codex',
modelReasoningEffort: 'high',
}),
],
};
```
### Using `resolveFolder()`
Apply overrides to all steps from a folder:
```javascript theme={null}
import { resolveFolder } from '#src/workflows/utils/resolvers/index.js';
export default {
id: 'spec-workflow',
steps: [
// All steps in 'spec-kit' folder use these settings
...resolveFolder('spec-kit', {
engine: 'codex',
model: 'gpt-5',
modelReasoningEffort: 'medium',
}),
],
};
```
### Using `resolveModule()`
```javascript theme={null}
import { resolveModule } from '#src/workflows/utils/resolvers/index.js';
export default {
id: 'module-workflow',
steps: [
resolveModule('spec-module', {
engine: 'claude',
model: 'opus',
}),
],
};
```
## Model Reasoning Effort
Only supported by certain engines (currently Codex).
| Value | Description |
| -------- | ----------------------------------------- |
| `low` | Minimal reasoning, fastest response |
| `medium` | Balanced reasoning (default for Codex) |
| `high` | Maximum reasoning, best for complex tasks |
```javascript theme={null}
resolveStep('complex-analysis', {
engine: 'codex',
modelReasoningEffort: 'high',
});
```
## Practical Examples
### Fast Prototyping
Use faster, cheaper models:
```javascript theme={null}
export default {
id: 'prototype',
name: 'Fast Prototyping',
steps: [
resolveStep('scaffold-generator', {
engine: 'ccr',
model: 'sonnet',
}),
resolveStep('quick-test', {
engine: 'ccr',
model: 'haiku',
}),
],
};
```
### Production Quality
Use powerful models:
```javascript theme={null}
export default {
id: 'production',
name: 'Production Quality',
steps: [
resolveStep('architecture-design', {
engine: 'claude',
model: 'opus',
}),
resolveStep('code-generation', {
engine: 'codex',
model: 'gpt-5.2-codex',
modelReasoningEffort: 'high',
}),
resolveStep('security-review', {
engine: 'claude',
model: 'opus',
}),
],
};
```
### Mixed Engine Workflow
Leverage different engines for their strengths:
```javascript theme={null}
export default {
id: 'mixed',
name: 'Mixed Engine Workflow',
steps: [
// Claude for creative tasks
resolveStep('brainstorm', {
engine: 'claude',
model: 'opus',
}),
// Codex for complex reasoning
resolveStep('algorithm-design', {
engine: 'codex',
modelReasoningEffort: 'high',
}),
// Fast model for simple tasks
resolveStep('format-code', {
engine: 'ccr',
model: 'haiku',
}),
],
};
```
## Engine Fallback System
When running a workflow, CodeMachine resolves the engine and model through a fallback system.
### How It Works
* Use step/CLI override if specified
* Else use agent config (`engine` field)
* Else find first authenticated engine by order
* If selected engine is not authenticated → try next authenticated engine
* If none authenticated → use registry default (first by order)
* If engine fell back, agent's model is ignored (uses engine's default)
* Otherwise: step override → agent config → engine default
### Default Engine & Model
**Default engine:** `opencode` (order: 1)
**Default model:** `opencode/big-pickle`
### Engine Fallback Order
Engines are tried in this order when falling back:
| Order | Engine | Default Model |
| ----- | ---------- | --------------------- |
| 1 | `opencode` | `opencode/big-pickle` |
| 2 | `claude` | `opus` |
| 3 | `codex` | `gpt-5.2-codex` |
| 4 | `cursor` | `auto` |
| 7 | `ccr` | `sonnet` |
If no engine is specified and `opencode` is authenticated, it's used. If `opencode` isn't authenticated, it tries `claude`, then `codex`, and so on.
## Validation
The workflow validator checks:
* `model` must be a string (if provided)
* `modelReasoningEffort` must be `'low'`, `'medium'`, or `'high'`
* `engine` must be a valid engine ID from the registry
Invalid configurations produce descriptive error messages during workflow loading.
# Package Structure
Source: https://docs.codemachine.co/build-workflows/package-structure
Understand the folder structure and manifest file of a workflow package.
A workflow package is a folder containing everything CodeMachine needs to run your workflow: configuration, prompts, and workflow definitions.
New to building workflows? Use the built-in [Ali workflow](/resources/workflow-library#ali-workflow-builder) for step-by-step guidance.
***
## Folder Structure
Every workflow package follows this structure:
A minimum workflow requires only three files: `codemachine.json`, `main.agents.js`, and a `.workflow.js` file. Everything else is optional.
***
## Required Files
| File | Location | Purpose |
| ------------------ | ---------------------- | -------------------------------------- |
| `codemachine.json` | Root | Package manifest with name and version |
| `main.agents.js` | `config/` | Main agent definitions |
| `*.workflow.js` | `templates/workflows/` | Workflow step definitions |
## Optional Files
| File | Location | Purpose |
| ----------------------- | --------- | --------------------------------------------- |
| `sub.agents.js` | `config/` | Sub-agent definitions for orchestrated agents |
| `modules.js` | `config/` | Module definitions for looping agents |
| `placeholders.js` | `config/` | Dynamic content placeholders |
| `agent-characters.json` | `config/` | Agent personalities and display styles |
| `prompts/` | Root | Prompt templates for agents |
***
## Manifest File
Every workflow package must have a `codemachine.json` manifest at its root:
```json codemachine.json theme={null}
{
"name": "my-workflow",
"version": "1.0.0",
"description": "Optional description of your workflow"
}
```
| Field | Required | Description |
| ------------- | -------- | ------------------------------------- |
| `name` | Yes | Package identifier (used for imports) |
| `version` | Yes | Semantic version (e.g., `1.0.0`) |
| `description` | No | Brief description of your workflow |
The `name` field must be unique. When importing, CodeMachine uses this to identify the package.
### Real Examples
```json BMAD theme={null}
{
"name": "bmad",
"version": "1.0.0",
"description": "BMAD Method - Business-driven Modular Agile Development workflow for greenfield projects"
}
```
```json CodeMachine-One theme={null}
{
"name": "codemachine-one",
"version": "1.0.0",
"description": "CodeMachine-One autonomous development workflow - from specification to implementation"
}
```
***
## Importing Packages
Once your package has a valid manifest, you can import it using the CLI or TUI:
```bash theme={null}
codemachine import ./path/to/workflow
```
Or from within CodeMachine:
```
/import ./path/to/workflow
```
Learn about all import sources: local paths, GitHub repos, and more
***
## Next Steps
Learn how to configure agents in `main.agents.js`
# Publish Workflow
Source: https://docs.codemachine.co/build-workflows/publish-workflow
Share your workflow with others via the import system.
Share your workflow package by publishing it to a public GitHub repository. Others can then import it using the `codemachine import` command.
***
## Prerequisites
Before publishing, ensure your workflow package has:
* A valid manifest file (`codemachine.json`)
* At least one agent definition in `config/main.agents.js`
* At least one workflow file in your workflows directory
***
## Create the Manifest
Every publishable package needs a `codemachine.json` file at the repository root.
### Minimal Manifest
For packages using the default directory structure:
```json codemachine.json theme={null}
{
"name": "my-workflow",
"version": "1.0.0"
}
```
### Full Manifest
For packages with custom directory layouts or additional metadata:
```json codemachine.json theme={null}
{
"name": "my-workflow",
"version": "1.0.0",
"description": "A workflow for building React applications",
"paths": {
"config": "config",
"workflows": "templates/workflows",
"prompts": "prompts",
"characters": "config/agent-characters.json"
}
}
```
### Required Fields
| Field | Description |
| --------- | ----------------------------------- |
| `name` | Package identifier (must be unique) |
| `version` | Semantic version (e.g., `1.0.0`) |
### Optional Fields
| Field | Description |
| ------------- | ---------------------------------- |
| `description` | Brief description of the workflow |
| `paths` | Custom paths for package resources |
***
## Custom Paths
If your repository has an existing structure that doesn't match the defaults, use the `paths` field to map your directories.
### Default Paths
When `paths` is omitted, CodeMachine uses these defaults:
| Resource | Default Path |
| ---------- | ------------------------------ |
| Config | `config/` |
| Workflows | `templates/workflows/` |
| Prompts | `prompts/` |
| Characters | `config/agent-characters.json` |
### When to Use Custom Paths
If you're creating a new repository for your workflow, use the default structure—no `paths` configuration needed.
```
my-workflow/
├── codemachine.json
├── config/
│ └── main.agents.js
├── templates/
│ └── workflows/
│ └── my-workflow.workflow.js
└── prompts/
└── ...
```
If you're adding a workflow to an existing repository with its own structure, define custom paths:
```json codemachine.json theme={null}
{
"name": "my-workflow",
"version": "1.0.0",
"paths": {
"config": "src/codemachine/config",
"workflows": "src/codemachine/workflows",
"prompts": "src/codemachine/prompts"
}
}
```
***
## Publish to GitHub
Create a new GitHub repository or use an existing one.
```bash theme={null}
# New repository
mkdir my-workflow-codemachine
cd my-workflow-codemachine
git init
```
Create your `codemachine.json` at the repository root.
```bash theme={null}
echo '{
"name": "my-workflow",
"version": "1.0.0"
}' > codemachine.json
```
Ensure you have the required configuration and workflow files.
```bash theme={null}
mkdir -p config templates/workflows prompts
# Add your main.agents.js, workflow files, and prompts
```
Commit and push to a public repository.
```bash theme={null}
git add .
git commit -m "Initial workflow package"
git remote add origin https://github.com/username/my-workflow-codemachine.git
git push -u origin main
```
Your repository **must be public** for others to import it. GitHub private repositories cannot be fetched by the import system.
***
## After Publishing
Once published, users can import your workflow using any of these formats:
```bash theme={null}
# By owner/repo
codemachine import username/my-workflow-codemachine
# By full URL
codemachine import https://github.com/username/my-workflow-codemachine
# By short name (if using -codemachine suffix)
codemachine import my-workflow
```
```
/import username/my-workflow-codemachine
/import https://github.com/username/my-workflow-codemachine
/import my-workflow
```
The imported workflow will be available in the workflow selection menu when running `codemachine`.
***
## Private Workflows
If you prefer to keep your workflow private, you can share it via local import instead of publishing to a public repository.
For private workflows, share the package directory directly and have users import it locally. See [Import Workflows - Local Imports](/build-workflows/import-workflows#local-imports) for details.
***
## Naming Conventions
For discoverability, consider using the `-codemachine` suffix in your repository name:
* `my-workflow-codemachine`
* `react-builder-codemachine`
* `api-generator-codemachine`
This allows users to import by short name:
```bash theme={null}
codemachine import my-workflow
```
CodeMachine searches GitHub for repositories matching `{name}-codemachine` when using short name imports.
# Runtime State
Source: https://docs.codemachine.co/build-workflows/runtime-state
How CodeMachine tracks your workflow progress and enables recovery.
When you run a workflow, CodeMachine creates a `.codemachine` folder in your project. This folder tracks everything about your workflow session—what's running, what's finished, and how to pick up where you left off.
## The .codemachine Folder
***
| Path | Description |
| -------------------------- | ------------------------------------------------------------------------------------ |
| `agents/agent-config.json` | Subagents registered for this workflow |
| `inputs/specification.md` | User specifications (if workflow requires them) |
| `artifacts/` | Optional folder for planning files (must be defined in prompts) |
| `prompts/` | Optional folder for cached prompts (must be defined in prompts) |
| `memory/directive.json` | Action that determines what the workflow does next |
| `logs/` | Database of agent history and running states |
| `template.json` | Single source of truth for runtime data. Deleting this resets the workflow from zero |
***
## How Progress is Tracked
The `template.json` file is the heart of workflow tracking. It remembers:
Which step is running and which steps are done
IDs needed to resume interrupted steps
Selected track and conditions from onboarding
Everything needed to continue after a crash
***
## template.json Schema
```typescript theme={null}
interface TemplateTracking {
// === Required ===
activeTemplate: string; // Running template filename (e.g., "bug-fixer.workflow.js")
lastUpdated: string; // ISO 8601 timestamp (UTC)
// === Step Tracking ===
completedSteps?: Record; // Map of step index → execution data
notCompletedSteps?: number[]; // Steps started but not finished (for crash recovery)
resumeFromLastStep?: boolean; // Enable resume capability (default: true)
// === Workflow Configuration ===
selectedTrack?: string; // Selected track (e.g., 'quick', 'enterprise')
selectedConditions?: string[]; // Selected condition IDs
projectName?: string; // User-provided project name
autonomousMode?: string; // 'true' | 'false' | 'never' | 'always'
// === Controller Mode ===
controllerConfig?: {
agentId: string;
sessionId: string;
monitoringId: number;
};
controllerView?: boolean; // Recovery opens controller vs workflow view
}
interface StepData {
sessionId: string; // Engine session ID for resume
monitoringId: number; // Database ID in registry.db
completedChains?: number[]; // Completed chained prompt indices
completedAt?: string; // ISO timestamp when step finished
}
```
### State Transitions
| Phase | What Changes in template.json |
| ------------------ | ------------------------------------------------------------------- |
| **Onboarding** | `selectedTrack`, `selectedConditions` set |
| **Workflow Start** | `activeTemplate` set, `completedSteps: {}`, `notCompletedSteps: []` |
| **Step Starts** | `notCompletedSteps: [0]` added |
| **Session Init** | `completedSteps["0"] = { sessionId, monitoringId }` |
| **Chain Complete** | `completedSteps["0"].completedChains = [0, 1, ...]` |
| **Step Complete** | `completedSteps["0"].completedAt` set, `notCompletedSteps` cleaned |
| **Loop Triggered** | `notCompletedSteps` updated to loop-back index |
| **Crash Occurs** | `notCompletedSteps` preserved for recovery |
***
## Manipulating Workflow Progress
You can manually control workflow execution by editing `template.json`. This is useful for:
* Re-running a specific step
* Resetting the workflow to an earlier point
* Skipping steps that already completed
### Revert to a Previous Step
The `completedSteps` object tracks finished steps by index. To go back to a step, remove it (and all steps after it) from `completedSteps`.
**Example:** You have steps 0, 1, 2 completed and want to re-run step 2:
```json theme={null}
// Before - all steps complete
{
"completedSteps": {
"0": { "sessionId": "abc", "monitoringId": 1, "completedAt": "..." },
"1": { "sessionId": "def", "monitoringId": 2, "completedAt": "..." },
"2": { "sessionId": "ghi", "monitoringId": 3, "completedAt": "..." }
}
}
// After - remove step 2 to re-run it
{
"completedSteps": {
"0": { "sessionId": "abc", "monitoringId": 1, "completedAt": "..." },
"1": { "sessionId": "def", "monitoringId": 2, "completedAt": "..." }
}
}
```
### Reset Entire Workflow
To start from the beginning, clear `completedSteps`:
```json theme={null}
{
"completedSteps": {},
"notCompletedSteps": []
}
```
Or simply delete the entire `template.json` file to reset everything.
***
## Workflow Lifecycle
Here's what happens as your workflow runs:
CodeMachine creates the `.codemachine` folder and initializes `template.json` with your selected options.
The current step is marked as "in progress" so CodeMachine knows where you are.
The agent executes with its prompts. Session info is saved for potential recovery.
The step is marked complete with a timestamp, and CodeMachine moves to the next step.
All steps are marked complete. The workflow is finished.
***
## What Happens If Something Goes Wrong?
CodeMachine automatically saves your progress. If your workflow crashes or you close the terminal, you can pick up right where you left off.
When you restart after an interruption:
1. CodeMachine finds the `.codemachine` folder
2. It reads `template.json` to see which step was running
3. It offers to resume from that step (or the last completed one)
***
## Agent Directives
Agents can control what happens next by writing to `directive.json`. This is how agents communicate with the workflow.
```json theme={null}
{ "action": "continue" }
```
Move to the next step normally. This is the default.
```json theme={null}
{ "action": "loop", "reason": "Tests failed, need another pass" }
```
Go back to an earlier step and try again.
```json theme={null}
{ "action": "checkpoint", "reason": "Review changes before continuing" }
```
Pause and wait for user confirmation.
```json theme={null}
{ "action": "trigger", "triggerAgentId": "code-reviewer" }
```
Spawn a sub-agent to help with a specific task.
```json theme={null}
{ "action": "stop", "reason": "Task completed successfully" }
```
End the workflow early.
```json theme={null}
{ "action": "error", "reason": "Something went wrong" }
```
Terminate the workflow with an error.
***
## User Controls
You can control workflow execution with keyboard shortcuts:
| Action | Shortcut | What Happens |
| ------------- | -------- | ----------------------------------------- |
| **Skip Step** | `Ctrl+S` | Mark current step as done and move on |
| **Quit** | `Ctrl+C` | Save progress and exit (can resume later) |
| **Advance** | `Enter` | Complete step and continue to next |
When a workflow pauses at a checkpoint, you'll see a prompt. Choose to continue or quit—your progress is saved either way.
***
## Execution Logs
The `logs/` folder contains detailed records of every agent run:
A SQLite database tracking every agent execution:
* Agent name and engine used
* Start time, end time, and duration
* Status (running, completed, failed, skipped)
* Token usage and cost estimates
* Error messages if something went wrong
Each agent gets its own log file (`agent-*.log`) containing:
* The full prompt sent to the agent
* The agent's complete response
* Any errors or warnings during execution
***
## Cleaning Up
The `.codemachine` folder contains your workflow state. Deleting it will remove your ability to resume an interrupted workflow.
To start fresh, you can safely delete the `.codemachine` folder:
```bash theme={null}
rm -rf .codemachine
```
A new folder will be created the next time you run a workflow.
# Workflow Examples
Source: https://docs.codemachine.co/build-workflows/workflow-examples
Complete workflow examples for each orchestration pattern.
Learn from complete workflow examples. Each example shows the logical flow and technical implementation for a specific [orchestration pattern](/core-concepts/workflow/orchestration-patterns).
***
## Interactive: Technical Design Review
You respond at every step. Each agent asks questions, gathers insights, and produces output for the next agent.
Asks you about requirements, constraints, and tradeoffs.
User Answers + Project context
Deep-dive analysis through Q\&A → User → Complete system architecture design
`architecture.md` = `{architecture}`
Review the architecture analysis. Answer follow-up questions.
Asks you about security concerns and compliance needs.
`{architecture}`
Threat modeling and attack surface analysis → User → Security controls and mitigation strategy
`security-review.md` = `{security_review}`
Review the security assessment. Answer follow-up questions.
Asks you about implementation preferences and team constraints.
`{architecture}` + `{security_review}`
Feasibility analysis → User → Final design incorporating all feedback
`final-design.md`
Review the final design. Confirm everything looks good or request changes.
```javascript technical-design-review.workflow.js theme={null}
export default {
name: 'Technical Design Review',
autonomousMode: 'never',
steps: [
separator('Architecture'),
resolveStep('architect', { interactive: true }),
separator('Security Review'),
resolveStep('security-expert', { interactive: true }),
separator('Final Design'),
resolveStep('senior-engineer', { interactive: true }),
],
};
```
**Key patterns:**
* `autonomousMode: 'never'` - User controls every step, can't toggle to auto
* `interactive: true` - Each agent waits for user input before proceeding
`interactive: true` is the default. If not specified, steps are interactive automatically.
***
## Autonomous: Greenfield Project Build
Controller agent runs agents on your behalf. You brief the controller, then review results instead of managing the process.
Autonomous mode is in beta. Behavior may change as we refine controller-agent coordination.
Brief the controller with your project idea, constraints, goals, and the full workflow structure.
Refines requirements and creates product specification.
Controller's project brief + Constraints
Requirements gathering → Controller → Product specification
`prd.md` = `{prd}`
Reviews PRD. Proceeds or adjusts.
Designs system architecture based on requirements.
`{prd}` + Controller's Instructions
System design → Controller → Architecture decisions
`architecture.md` = `{architecture}`
Reviews architecture. Proceeds or adjusts.
Implements the code based on architecture.
`{prd}` + `{architecture}` + Controller's Instructions
Implementation → Controller → Code review
`src/*`
Reviews implementation. Proceeds or adjusts.
Writes tests for the implementation. Examines codebase using tools.
`{prd}` + `{architecture}`
Test planning → Controller → Test implementation
`tests/*`
```javascript greenfield-project.workflow.js theme={null}
export default {
name: 'Greenfield Project Build',
controller: controller('project-controller'),
autonomousMode: 'always',
steps: [
separator('Requirements'),
resolveStep('pm', { interactive: false }),
separator('Architecture'),
resolveStep('architect', { interactive: false }),
separator('Implementation'),
resolveStep('developer', { interactive: false }),
separator('Testing'),
resolveStep('tester', { interactive: false }),
],
};
```
**Key patterns:**
* `controller()` - Defines the controller agent that orchestrates the workflow
* `autonomousMode: 'always'` - Controller drives everything, user can't toggle to manual
* All steps are `interactive: false` - Controller approves transitions, not user
Both controller and step agents must have MCP configured for `workflow-signals`. Step agents propose completion, controller approves or rejects.
**Agent MCP configuration:**
```javascript main.agents.js theme={null}
module.exports = [
// Controller - Approves/rejects step transitions
{
id: 'project-controller',
name: 'Project Controller',
role: 'controller',
promptPath: path.join(promptsDir, 'controller', 'main.md'),
mcp: [
{
server: 'workflow-signals',
only: ['approve_step_transition', 'get_pending_proposal'],
},
],
},
// Step agents - Propose completion
{
id: 'pm',
name: 'Product Manager',
promptPath: path.join(promptsDir, 'pm', 'main.md'),
mcp: [
{
server: 'workflow-signals',
only: ['propose_step_completion'],
},
],
},
// ... other step agents with same MCP config
];
```
***
## Continuous: Adding APIs
Auto-advance with zero interaction. You provide a specification file upfront, then agents run to completion.
Define the APIs you need: endpoints, methods, schemas, validation rules.
Workflows with `specification: true` won't start until this file is provided.
`specification.md` = `{specification}`
Designs endpoint contracts and schemas from spec.
`{specification}`
Parse spec → Design contracts → Generate schemas
`api-design.md` = `{api_design}`
Implements the API endpoints. Examines codebase using tools.
`{specification}` + `{api_design}`
Implement endpoints → Add validation → Wire routes
`src/api/*`
Writes tests for the API. Examines codebase using tools.
`{specification}` + `{api_design}`
Test planning → Write unit tests → Write integration tests
`tests/api/*`
```javascript api-forge.workflow.js theme={null}
export default {
name: 'API Forge',
specification: true,
autonomousMode: true,
steps: [
separator('Design'),
resolveStep('api-designer', { interactive: false }),
separator('Implementation'),
resolveStep('developer', { interactive: false }),
separator('Testing'),
resolveStep('tester', { interactive: false }),
],
};
```
**Key patterns:**
* `specification: true` - Requires a spec file before starting
* `autonomousMode: true` - Defaults to auto, but user can toggle to manual with `Shift+Tab`
* All steps are `interactive: false` - Auto-advances through all steps
* No controller needed - spec file provides all the context
***
## Hybrid: Bug Fix Pipeline
Mix interactive and auto-advance agents in the same workflow. Key decisions need you, routine steps don't.
Asks you about the bug: What's the issue? Which device? Steps to reproduce?
User Answers
Gather symptoms → User → Reproduction steps → User → Environment details
`bug-report.md` = `{bug_report}`
Review bug report. Confirm details are correct.
Reproduces the bug with gathered insights. Examines codebase using tools.
`{bug_report}`
Set up environment → Reproduce steps → Confirm bug exists
`reproduction.md` = `{reproduction}`
Finds root cause. Examines codebase using tools.
`{bug_report}` + `{reproduction}`
Trace execution → Identify root cause → Document findings
`investigation.md` = `{investigation}`
Discusses findings with you. Plans the fix together.
`{bug_report}` + `{reproduction}` + `{investigation}`
Present findings → User → Discuss options → User → Agree on approach
`fix-plan.md` = `{fix_plan}`
Review the plan. Approve or request changes.
Implements the fix. Examines codebase using tools.
`{investigation}` + `{fix_plan}`
Implement fix → Self-review → Refine
`src/*`
Writes tests for the fix. Examines codebase using tools.
`{bug_report}` + `{fix_plan}`
Write regression test → Write edge case tests → Verify fix
`tests/*`
```javascript bug-fix-pipeline.workflow.js theme={null}
export default {
name: 'Bug Fix Pipeline',
autonomousMode: true,
steps: [
separator('Triage'),
resolveStep('triage'), // Interactive - gathers bug details
separator('Investigation'),
resolveStep('reproducer', { interactive: false }),
resolveStep('investigator', { interactive: false }),
separator('Planning'),
resolveStep('planner'), // Interactive - discuss fix approach
separator('Implementation'),
resolveStep('developer', { interactive: false }),
resolveStep('tester', { interactive: false }),
],
};
```
**Key patterns:**
* `autonomousMode: true` - Defaults to auto, but user can toggle to manual with `Shift+Tab`
* Mix of interactive and non-interactive steps
* Interactive steps: `triage`, `planner` - where decisions matter
* Auto steps: `reproducer`, `investigator`, `developer`, `tester` - routine work
* User can take control anytime by toggling to manual mode
***
## Sub-Agents: Blueprint Orchestration
Main agents can delegate specialized tasks to sub-agents. The orchestrator coordinates multiple sub-agents to build a complete solution.
Analyzes requirements and creates a specification.
User requirements + Project context
`specification.md` = `{specification}`
Coordinates sub-agents to design the architecture. Runs sub-agents in parallel for different domains.
`{specification}`
`data-architect` → Database schema design
`api-architect` → API contract design
`ui-architect` → Component structure design
`blueprint.md` = `{blueprint}` (merged from all sub-agents)
Implements the code based on the blueprint.
`{specification}` + `{blueprint}`
`src/*`
**Workflow file:**
```javascript blueprint-orchestration.workflow.js theme={null}
export default {
name: 'Blueprint Orchestration',
autonomousMode: true,
steps: [
separator('Analysis'),
resolveStep('analyst', { interactive: true }),
separator('Architecture'),
resolveStep('blueprint-orchestrator', { interactive: false }),
separator('Implementation'),
resolveStep('developer', { interactive: false }),
],
subAgentIds: [
'data-architect',
'api-architect',
'ui-architect',
],
};
```
Both `agent-coordination` MCP on the main agent and `subAgentIds` in the workflow must be configured for sub-agent orchestration to work.
**Main agent with agent-coordination MCP:**
```javascript main.agents.js theme={null}
{
id: 'blueprint-orchestrator',
name: 'Blueprint Orchestrator',
description: 'Coordinates architecture sub-agents',
promptPath: path.join(promptsDir, 'orchestrator', 'main.md'),
mcp: [
{
server: 'agent-coordination',
only: ['run_agents', 'get_agent_status', 'list_available_agents'],
targets: ['data-architect', 'api-architect', 'ui-architect'],
},
],
}
```
**Sub-agents definition:**
```javascript sub.agents.js theme={null}
module.exports = [
{
id: 'data-architect',
name: 'Data Architect',
description: 'Designs database schema and data models',
mirrorPath: path.join(promptsDir, 'sub-agents', 'data-architect.md'),
},
{
id: 'api-architect',
name: 'API Architect',
description: 'Designs API contracts and endpoints',
mirrorPath: path.join(promptsDir, 'sub-agents', 'api-architect.md'),
},
{
id: 'ui-architect',
name: 'UI Architect',
description: 'Designs component structure and UI patterns',
mirrorPath: path.join(promptsDir, 'sub-agents', 'ui-architect.md'),
},
];
```
**Key patterns:**
* `subAgentIds` in workflow - Declares which sub-agents are available
* `agent-coordination` MCP - Enables the orchestrator to run sub-agents
* `targets` - Restricts which sub-agents can be invoked (security)
* `only` - Limits MCP tools available to the agent
* Sub-agents run in parallel for faster execution
***
## Choosing a Pattern
| Pattern | User Involvement | Best For |
| --------------- | -------------------------------- | ----------------------------------------- |
| **Interactive** | Every step | Tasks needing judgment, exploration, Q\&A |
| **Autonomous** | Brief controller, review results | Long-running tasks, clear objectives |
| **Continuous** | None (spec upfront) | Repeatable, proven workflows |
| **Hybrid** | Key decisions only | Most real-world workflows |
Most workflows end up being **Hybrid** — you want control where it matters and speed everywhere else.
***
## Next Steps
Start building with the basics
Add tracks, conditions, modules, and controllers
# Write Prompts
Source: https://docs.codemachine.co/build-workflows/write-prompts
Create prompts, chained prompts, and placeholders for your agents.
Prompts are the instructions that tell agents what to do. Each agent needs prompt files that define its goals and behavior.
**Flexible Structure:** You can organize your prompt files however you prefer. The examples in this guide (like separating persona from instructions, or using `chained/` folders) are recommendations—not requirements. What matters is that your agent config points to the correct paths.
***
## Best Practices
Each prompt should have a single, clear purpose. If a prompt is doing too many things, split it into multiple agents or steps.
Always specify:
* What format the output should be in
* Where to write output files
* What the next agent expects to receive
Include clear success and failure indicators so the agent knows when it's done and what to avoid.
Don't hardcode context. Use placeholders to inject:
* Previous agent outputs
* User selections (tracks, conditions)
* Shared content (standards, templates)
Test each prompt individually before combining into a full workflow. Use the TUI to run single agents.
***
## Frontmatter
Every prompt file must begin with YAML frontmatter:
```markdown theme={null}
---
name: "Project Planner"
description: "Analyzes requirements and creates implementation plans"
---
```
| Field | Required | Description |
| ------------- | -------- | ------------------------------------------ |
| `name` | Yes | Display name for the prompt |
| `description` | Yes | Brief description of what this prompt does |
***
## Placeholders
Placeholders inject dynamic content into prompts at runtime. They use triple-brace syntax: `{{placeholder_name}}`.
### Built-in Placeholders
These are always available:
| Placeholder | Description |
| ------------------------- | --------------------------------------- |
| `{{date}}` | Current date |
| `{{project_name}}` | Name of the current project |
| `{{selected_track}}` | User-selected track (if tracks defined) |
| `{{selected_conditions}}` | User-selected conditions (if defined) |
| `{{specification}}` | Contents of the spec file (if enabled) |
### Custom Placeholders
Define custom placeholders in `config/placeholders.js`:
```javascript config/placeholders.js theme={null}
const path = require('node:path');
module.exports = {
// Files in the user's project directory
userDir: {
planner_output: '.codemachine/artifacts/planner-output.md',
architect_output: '.codemachine/artifacts/architect-output.md',
},
// Files in the workflow package directory
packageDir: {
coding_standards: path.join('prompts', 'templates', 'my-workflow', 'shared', 'coding-standards.md'),
},
};
```
**userDir** placeholders resolve to files in the user's project. **packageDir** placeholders resolve to files in your workflow package.
### Using Placeholders
Reference placeholders in your prompts:
```markdown theme={null}
## CONTEXT
Previous analysis:
{{planner_output}}
## CODING STANDARDS
{{coding_standards}}
```
### Chaining Agent Outputs
Pass data between agents using output placeholders:
```mermaid theme={null}
flowchart LR
A[Planner] -->|writes| B[planner-output.md]
B -->|placeholder| C[Architect]
C -->|writes| D[architect-output.md]
D -->|placeholder| E[Developer]
```
1. **Agent 1** writes output to `.codemachine/artifacts/planner-output.md`
2. **Register placeholder** `planner_output` pointing to that file
3. **Agent 2** receives content via `{{planner_output}}`
***
## Module Prompts
Modules are special agents that can loop the workflow back. Their prompts must include **directive writing instructions**.
````md prompts/templates/my-workflow/quality-gate/prompt.md theme={null}
---
name: "Quality Gate"
description: "Validates work and decides whether to loop or continue"
---
# Quality Gate
## CONTEXT
{{developer_output}}
## GOAL
Validate the developer's work against quality standards. Decide whether to:
- **LOOP** - Send back for fixes if issues found
- **CONTINUE** - Proceed forward if validation passes
## VALIDATION CRITERIA
**Pass Conditions:**
- All tests pass
- No linting errors
- Code follows standards
- Documentation is complete
**Fail Conditions:**
- Failing tests
- Missing error handling
- Incomplete implementation
- Security vulnerabilities
## INSTRUCTIONS
1. Review the code changes
2. Run validation checks
3. Make a clear PASS or FAIL decision
4. If validation fails, write the directive file to trigger a loop
## DIRECTIVE WRITING (CRITICAL)
**If validation FAILS**, write to `.codemachine/memory/directive.json`:
```json
{
"action": "loop",
"reason": "Validation failed: 3 tests failing, missing error handling",
"target": "developer"
}
```
**If validation PASSES**, no action is needed. The workflow continues to the next step by default.
````
***
## Sub-Agent Prompts
When writing prompts for agents that orchestrate sub-agents, you must include instructions for using MCP tools to spawn and delegate work.
```md prompts/templates/my-workflow/orchestrator/main.md theme={null}
# Blueprint Orchestrator
## ROLE
You are the blueprint orchestrator. You coordinate specialized sub-agents to design the architecture.
## MCP TOOLS
You have access to the `agent-coordination` MCP server with these tools:
- `list_available_agents` - Discover available sub-agents
- `run_agents` - Execute sub-agent scripts
- `get_agent_status` - Check execution status
## INSTRUCTIONS
1. Use `list_available_agents` to see available sub-agents
2. Delegate tasks using `run_agents` with specific instructions for each sub-agent
3. Monitor progress with `get_agent_status`
4. Merge outputs into a unified blueprint
## AVAILABLE SUB-AGENTS
- `data-architect` - Database schema design
- `api-architect` - API contract design
- `ui-architect` - Component structure design
```
Your prompt must instruct the agent to use the `agent-coordination` MCP tools to spawn sub-agents and delegate specific roles to them.
Learn how to set up the agent-coordination MCP for sub-agent orchestration
***
## Controller Prompts
Controllers orchestrate autonomous workflows. They respond on behalf of the user.
```markdown prompts/templates/my-workflow/controller/prompt.md theme={null}
---
name: "Project Owner"
description: "Autonomous controller for the workflow"
role: "controller"
---
# Project Owner
## ROLE
You are the autonomous controller for the **my-workflow** workflow. You respond on behalf of the user, driving agents through the workflow until completion.
## AGENT INTERACTIONS
### Planner (`planner`)
**Expected Output:** Implementation plan document
**Max Turns:** 3
**Approval Criteria:** Plan covers all requirements, tasks are actionable
### Developer (`developer`)
**Expected Output:** Working code implementation
**Max Turns:** 5
**Approval Criteria:** Code compiles, tests pass, matches plan
## BEHAVIOR RULES
1. **Pacing:** Balanced - review key decisions, spot-check work
2. **Loop Depth:** Standard - 3-5 iterations, aim for quality
3. **Turn Limit:** 20 total turns across all agents
## RESPONSE FORMAT
Keep responses brief. 1-2 sentences with the decision and next action.
## DECISION MAKING
For each agent interaction:
1. Review agent output against success indicators
2. Check for failure indicators
3. If success - approve and continue
4. If failure - request specific changes (up to max turns)
```
***
## Full Example: Single Agent
Here's a complete example of a **planner** agent with all its prompt files. This structure separates persona from instructions, but remember—you can organize files however works best for your workflow.
### File Structure
### persona.md
```markdown prompts/templates/my-workflow/planner/persona.md theme={null}
---
name: "Project Planner"
description: "Senior technical architect persona"
---
# Project Planner
## Role
You are a senior technical architect with 15 years of experience designing scalable systems.
## Identity
- Expert in breaking down complex requirements into actionable plans
- Methodical and thorough in analysis
- Focused on practical, implementable solutions
## Communication Style
- Clear and concise explanations
- Uses diagrams and structured formats
- Asks clarifying questions when requirements are ambiguous
## Principles
- Always validate assumptions before proceeding
- Prefer simple solutions over complex ones
- Consider maintainability and scalability
- Document decisions and rationale
```
### prompt.md
```markdown prompts/templates/my-workflow/planner/prompt.md theme={null}
---
name: "Project Planner Prompt"
description: "Main instructions for planning"
---
# Project Planner
## CONTEXT
{{specification}}
## GOAL
Analyze the project requirements and create a detailed implementation plan.
## INSTRUCTIONS
- Review the specification thoroughly
- Identify core features and dependencies
- Break down into implementable tasks
- Estimate complexity for each task
- Define the recommended order of implementation
## OUTPUT
Create a structured plan in `.codemachine/artifacts/planner-output.md` with:
1. **Executive Summary** - High-level overview
2. **Feature Breakdown** - List of features with descriptions
3. **Task List** - Ordered implementation tasks
4. **Dependencies** - What depends on what
5. **Risks** - Potential blockers or challenges
## SUCCESS CRITERIA
- All requirements from spec are addressed
- Tasks are small enough to implement in one session
- Dependencies are clearly mapped
- No ambiguous or undefined tasks
## AVOID
- Skipping requirements from the specification
- Creating tasks that are too large or vague
- Ignoring edge cases mentioned in the spec
- Making assumptions without documenting them
```
### Agent Configuration
This agent would be configured in `config/agents.js`:
```javascript config/agents.js theme={null}
module.exports = [
{
name: 'planner',
description: 'Analyzes requirements and creates implementation plans',
promptPath: 'prompts/templates/my-workflow/planner/prompt.md',
personaPath: 'prompts/templates/my-workflow/planner/persona.md',
},
];
```
The file names `persona.md` and `prompt.md` are just conventions. You could use `identity.md`, `instructions.md`, or any names you prefer—just update the paths in your agent config to match.
***
## Full Example: Multi-Step Agent with Chained Prompts
Here's a complete example of an **onboarding** agent that guides users through multiple steps. This uses a workflow file for shared context and chained step files for step-specific instructions.
### File Structure
### persona.md
```markdown prompts/templates/my-workflow/onboarding/persona.md theme={null}
---
name: "Onboarding Guide"
description: "Friendly assistant persona for onboarding"
---
# Onboarding Guide
## Role
You are a friendly onboarding assistant helping users set up their projects.
## Communication Style
- Patient and encouraging
- Explains concepts clearly without jargon
- Celebrates progress at each step
## Principles
- Never rush the user
- Validate input before proceeding
- Offer to explain if something is unclear
```
### workflow\.md
```markdown prompts/templates/my-workflow/onboarding/workflow.md theme={null}
---
name: "Onboarding Workflow"
description: "Guides users through project setup"
---
# Onboarding Guide
## CONTEXT
{{project_name}}
## GOAL
Guide the user through setting up their new project, ensuring all configuration is correct.
## INSTRUCTIONS (All Steps)
- Be patient and explain each step clearly
- Validate user input before proceeding
- Offer to explain concepts if user seems confused
- Keep track of decisions made in previous steps
## SUCCESS CRITERIA
- User completes all configuration steps
- All required files are created
- Project is ready to run
```
### chained/step-01-intro.md
```markdown prompts/templates/my-workflow/onboarding/chained/step-01-intro.md theme={null}
---
name: "Step 01 - Introduction"
description: "Welcome and project type selection"
---
# Step 1: Introduction
## STEP GOAL
Welcome the user and determine their project type.
## INSTRUCTIONS
- Greet the user warmly
- Explain what this workflow will accomplish
- Ask about their project type (web app, CLI tool, library, etc.)
- Confirm their selection before proceeding
## COMPLETION CRITERIA
User has selected and confirmed their project type.
{{step_completion}}
```
### chained/step-02-setup.md
```markdown prompts/templates/my-workflow/onboarding/chained/step-02-setup.md theme={null}
---
name: "Step 02 - Environment Setup"
description: "Install dependencies and configure environment"
---
# Step 2: Environment Setup
## STEP GOAL
Set up the development environment based on the selected project type.
## INSTRUCTIONS
- Check for required tools (Node.js, Python, etc.)
- Install missing dependencies
- Create initial project structure
- Verify the environment is working
## COMPLETION CRITERIA
All dependencies installed and environment verified.
{{step_completion}}
```
### chained/step-03-config.md
```markdown prompts/templates/my-workflow/onboarding/chained/step-03-config.md theme={null}
---
name: "Step 03 - Configuration"
description: "Final configuration and validation"
---
# Step 3: Configuration
## STEP GOAL
Complete final configuration and validate the setup.
## INSTRUCTIONS
- Generate configuration files
- Ask for any remaining preferences
- Run validation checks
- Provide a summary of what was configured
## FINAL OUTPUT
Write setup summary to `.codemachine/artifacts/onboarding-output.md`
```
### Agent Configuration
```javascript config/agents.js theme={null}
module.exports = [
{
name: 'onboarding',
description: 'Guides users through project setup',
promptPath: 'prompts/templates/my-workflow/onboarding/workflow.md',
personaPath: 'prompts/templates/my-workflow/onboarding/persona.md',
chainedPromptsPath: 'prompts/templates/my-workflow/onboarding/chained',
chainedPrompts: [
'prompts/templates/my-workflow/onboarding/chained/step-01-intro.md',
'prompts/templates/my-workflow/onboarding/chained/step-02-setup.md',
'prompts/templates/my-workflow/onboarding/chained/step-03-config.md',
],
},
];
```
You can use `chainedPromptsPath` to load all files from a directory (alphabetically), or `chainedPrompts` to explicitly list files in order. Using both gives you explicit control while keeping files organized in a folder.
***
## Next Steps
Put agents and prompts together in a workflow
See complete real-world examples
# Your First Workflow
Source: https://docs.codemachine.co/build-workflows/your-first-workflow
Build your first workflow using the CLI.
A workflow file defines how your agents execute: the order they run and how they interact with users.
Before creating a workflow, make sure you've already [configured your agents](/build-workflows/build-agents) and [written your prompts](/build-workflows/write-prompts).
***
## Workflow File Location
Workflow files live in `templates/workflows/` and use the `.workflow.js` extension:
***
## Basic Structure
Every workflow exports a default object with a name and steps:
```javascript templates/workflows/my-workflow.workflow.js theme={null}
export default {
name: 'My Workflow',
steps: [
resolveStep('planner'),
resolveStep('developer'),
resolveStep('reviewer'),
],
};
```
### Name
Names should be short and descriptive. They define the objective of your workflow and help users understand what it accomplishes.
```javascript theme={null}
name: 'Code Review Pipeline'
```
**Example names:**
* `Code Review Pipeline`
* `API Generator`
* `Documentation Writer`
* `Bug Fixer`
### Steps
Steps are agents set in sequence. The `resolveStep()` function loads an agent from your `config/main.agents.js`.
**Arrangement matters.** Each step receives context from previous steps, so the order determines how information flows through your workflow.
```javascript theme={null}
steps: [
resolveStep('planner'), // Runs first
resolveStep('developer'), // Receives planner's output
resolveStep('reviewer'), // Receives both outputs
],
```
***
## Workflow Modes
Choose how your workflow runs:
| Mode | Description | Best For |
| -------------- | -------------------------------------------- | ------------------------------------ |
| **Manual** | User controls flow, agents wait for input | Interactive workflows, brainstorming |
| **Continuous** | Runs automatically from start to finish | Batch processing, reports |
| **Hybrid** | Mix of interactive and auto-advancing agents | Complex workflows with checkpoints |
Set the mode using `autonomousMode`:
```javascript theme={null}
export default {
name: 'My Workflow',
autonomousMode: 'never', // Manual mode - user controls each step
steps: [
resolveStep('planner'),
resolveStep('developer'),
],
};
```
| Value | Behavior |
| -------------------- | -------------------------------------------- |
| `'never'` or `false` | Manual - waits for user at each step |
| `'always'` or `true` | Continuous - auto-advances through all steps |
***
## Adding Separators
Use `separator()` to add visual dividers between workflow phases:
```javascript templates/workflows/code-review.workflow.js theme={null}
export default {
name: 'Code Review Workflow',
steps: [
separator('Analysis Phase'),
resolveStep('analyzer'),
separator('Review Phase'),
resolveStep('structure-reviewer'),
resolveStep('quality-reviewer'),
separator('Final Report'),
resolveStep('report-generator'),
],
};
```
Separators appear in the TUI timeline to help users understand workflow progress.
***
## Interactive vs Non-Interactive Steps
By default, steps are interactive - the workflow waits for user input. Set `interactive: false` to auto-advance:
```javascript theme={null}
export default {
name: 'Hybrid Pipeline',
steps: [
// First step is interactive - gather requirements from user
resolveStep('requirements-gatherer'),
// Remaining steps run automatically
resolveStep('planner', { interactive: false }),
resolveStep('developer', { interactive: false }),
resolveStep('tester', { interactive: false }),
],
};
```
A common pattern is making the first step interactive for gathering requirements, then running subsequent steps non-interactively.
***
## Complete Simple Example
Here's a complete workflow for a basic code generation pipeline:
```javascript templates/workflows/code-generator.workflow.js theme={null}
export default {
name: 'Code Generator',
autonomousMode: 'never',
steps: [
separator('Requirements'),
resolveStep('requirements-analyst'),
separator('Planning'),
resolveStep('architect', { interactive: false }),
separator('Implementation'),
resolveStep('developer', { interactive: false }),
separator('Quality Check'),
resolveStep('reviewer', { interactive: false }),
],
};
```
***
## Running Your Workflow
Once your workflow is complete, run it with:
```bash theme={null}
codemachine workflow my-workflow
```
Or select it from the TUI workflow picker.
### Keyboard Shortcuts
| Key | Action |
| ----------------- | ---------------------------- |
| **Shift+Tab** | Toggle Autonomous Mode |
| **Tab** | Toggle Timeline Panel |
| **P** | Pause Workflow |
| **Ctrl+S** | Skip current prompt or agent |
| **Escape** | Stop Confirmation |
| **H** | History View |
| **Enter** | Toggle Expand / Open Log |
| **Arrow Up/Down** | Navigate |
| **Arrow Right** | Focus Prompt Box |
***
## Validation Checklist
Before running your workflow, verify:
Every agent ID in `resolveStep()` exists in `config/main.agents.js`
All `promptPath` references in agent configs point to existing files
All placeholders used in prompts are registered in `config/placeholders.js`
***
## Next Steps
Ready for more? Learn about tracks, conditions, modules, controllers, and sub-agents.
Tracks, conditions, modules, and controllers
Complete real-world examples
# Agent Basics
Source: https://docs.codemachine.co/core-concepts/agent-basics
Understand what an agent is, the different types, and when to use each one.
**An agent is a session of an AI coding engine.**
One agent equals one engine session with a unique ID. Each agent has its own engine, model, and configuration.
***
## What Makes Up an Agent
Every agent consists of:
* **[Prompts](#prompts)** - The instructions sent to the agent
* **[Engine](#engines)** - The AI coding CLI that powers the agent
* **[Model](#engines)** - The AI model the engine uses
* **[Interactivity](#interactivity)** - Whether the agent waits for input or runs automatically
* **[MCP](#mcp)** - External tools and integrations available to the agent
***
## Agent Types
Runs as a step in the workflow. Does the primary work.
A main agent that can loop back to earlier steps.
Spawned by main agents via MCP to delegate work.
Orchestrates on your behalf - answers questions, signals next steps.
***
## When to Use Each Type
### Main Agent
Use for standard workflow steps that run once and pass output forward.
* Single-pass tasks (analysis, generation, implementation)
* Steps that don't need to revisit previous work
* Most workflow steps
Learn how to set up main agents
### Module
Use when a step needs to loop back based on results.
* Review and revision cycles
* Iterative refinement
* Quality gates that may require rework
Learn how to set up modules
### Sub-agent
Use to break complex work into delegated tasks within a single step.
* Parallel task execution
* Context isolation
* Specialized subtasks
Sub-agents are not steps. They are a context management tool for delegating work between agents.
Learn how to set up sub-agents
### Controller
Use for autonomous workflows where you want an agent to make decisions between steps.
* Long-running autonomous workflows
* Tasks where you want to review results, not manage process
* Complex multi-step operations with clear objectives
Learn how to set up controllers
***
## Agent vs Step
| Concept | What It Is |
| --------- | --------------------------------------------- |
| **Step** | A position in the workflow sequence |
| **Agent** | The AI session that executes at that position |
Every step has exactly one agent. The step defines when to run. The agent defines how to run.
***
## Engines
An engine is an AI coding CLI that powers the agent. Different engines have different capabilities, strengths, and supported models.
Why this matters: You can mix engines in a single workflow—use one engine for creative tasks, another for complex reasoning, and a fast one for simple operations.
See available engines, model options, and configuration examples
***
## Interactivity
Interactivity determines whether an agent waits for input or proceeds automatically.
**Agent waits for user input.**
* Pauses after each prompt
* User reviews and responds
* Best for exploration and Q\&A
**Agent proceeds automatically.**
* No pauses between prompts
* Runs to completion
* Best for automated pipelines
This is how hybrid workflows work - some agents wait for you, others run automatically.
Learn how to set interactive or non-interactive mode per agent
***
## MCP
MCP (Model Context Protocol) servers extend agent capabilities with additional tools.
**What MCP provides:**
* Custom tool integrations
* External data access
* Sub-agent spawning
* Signals for workflow control
The signals MCP is required for autonomous workflows where agents need to communicate with the controller. It's also required when using sub-agents, since agent coordination works through MCP.
Learn how to add MCP servers to your agents
***
## Prompts
Prompts are the instructions sent to an agent. They define what the agent should do.
### Chained Prompts
Multiple prompts injected into the same agent session, one after another. Instead of overwhelming one step with all instructions, you break it into smaller sequential prompts.
**Example flow:**
1. First prompt: "Analyze the codebase structure"
2. User reviews output
3. Second prompt: "Based on your analysis, identify potential issues"
4. User reviews output
5. Third prompt: "Create a plan to address the top 3 issues"
Same agent, same session. Prompts run in sequence. Common in interactive Q\&A workflows.
Learn how to set up sequential prompts for an agent
### Placeholders
Placeholders inject data into agent prompts.
| Type | Source | Use case |
| ------------------- | ----------------------------------------- | ------------------------------------------- |
| Static (packageDir) | Pre-defined prompts from workflow package | Shared prompts, split large prompts |
| Dynamic (userDir) | Files created during workflow | Agent A outputs a file, Agent B receives it |
**Built-in Placeholders:** System data injected automatically - date, time, username, project name, selected tracks and conditions.
Learn how to use static and dynamic placeholders in prompts
### Directives
Directives allow agents to control the workflow by writing to a JSON file. The workflow listens after each step and takes action.
| Directive | Action |
| ------------ | ------------------------------------------------- |
| `checkpoint` | Shows message to user, option to continue or stop |
| `stop` | Stops the workflow |
| `error` | Shows error message and stops |
| `pause` | Pauses and waits for user input |
| `loop` | Returns back to a previous step (modules only) |
| `trigger` | Triggers any agent in the workflow (modules only) |
Directives come from agents. Signals come from users. Both control execution, but from different sources.
Learn how to enable agents to control workflow execution
***
## Next Steps
Build a complete workflow from scratch
Configure agents for your workflow
# What is CodeMachine?
Source: https://docs.codemachine.co/core-concepts/what-is-codemachine
Understand the philosophy behind CodeMachine and why workflows work this way.
**CodeMachine is an opensource tool that runs AI workflows in your terminal.**
## The Workflow Model
Every time you use an AI coding agent, you're running a workflow. Fix a bug? You ask questions, reproduce, analyze, plan, implement, test. Build a feature? You research, design, code, review. You've already figured out what works.
The workflow lives in your head. You guide the agent through it, step by step, session by session. It works. But every time you start, you rebuild it from scratch. You re-explain the process. You remember to ask the right questions. You manage when to clear context, when to push forward, when to loop back.
CodeMachine lets you capture that workflow and run it again.
Define the steps once. Choose which agents handle what. Add an agent that always asks the right questions at the start. Chain agents together - one to plan, one to implement, one to review. Control exactly what each agent sees, so they stay focused instead of overwhelmed.
Your workflows become tools instead of steps in your head. Share them with your team. Run them on every project. Improve them over time.
## The Conceptual Layer
CodeMachine is built on three ideas:
The structure. What happens, in what order, with what controls. You define this once and reuse it.
What each agent knows. You control the data, the focus, the specialization. Instead of one agent knowing everything, each agent knows exactly what it needs.
No limits on complexity. Interactive, autonomous, continuous, or any combination — CodeMachine handles agent coordination.
No limits on how complex your workflows can get. CodeMachine handles orchestration and agent coordination — interactive, autonomous, continuous, or any combination. [See orchestration patterns →](./workflow/orchestration-patterns)
## How CodeMachine Runs Engines
CodeMachine is an orchestration layer that runs AI coding CLIs through structured workflows. You define the workflow once, and CodeMachine handles execution, context passing, and agent coordination.
CodeMachine uses the headless or detached scripting mode that AI coding engines provide for automation (Claude Code, Codex, Cursor, and others). It spawns engines via CLI wrapping, passes the right arguments and flags, and controls agents through its infrastructure.
This follows each engine's official documentation for scripting and automation use.
Have questions about compliance or engine usage policies? [Read our FAQ →](/resources/faq)
## Origin
CodeMachine started as a single hardcoded workflow, a proof of concept for orchestrating AI coding agents. That workflow was used to build the next iteration, validating the core premise: workflows should build workflows.
Originally called CodexMachine (Codex-only), it was a personal tool. But conversations with teams revealed a pattern: everyone was building their own orchestration layer. The same problems kept surfacing: context management, agent coordination, execution visibility. The market needed what CodeMachine was becoming.
That feedback shaped the architecture. Engine-agnostic. Open source. Built for production autonomy with full transparency into how agents run.
**Open source, always.** Enterprise and hosted versions are in development for teams that need managed infrastructure. Contact [moaz@codemachine.co](mailto:moaz@codemachine.co).
***
## Next Steps
Learn the building blocks of workflows
See the different orchestration patterns
Understand how to control execution
# Workflow Basics
Source: https://docs.codemachine.co/core-concepts/workflow/basics
Understand what a workflow is and how it orchestrates agents to accomplish tasks.
**A workflow is a configured execution plan.**
It defines which agents run, in what order, with what controls, and how context flows between them.
***
## What Makes Up a Workflow
Every workflow has:
* **[Name](#name)** - Defines the objective of the overall workflow
* **[Steps](#steps)** - Agents set in sequence
Optionally, workflows can also include:
* **[Separators](#separators)** - Visual dividers between workflow phases
* **[Tracks](#tracks)** - Different workflow paths users can choose from
* **[Condition Groups](#condition-groups)** - Questions to customize which steps run
* **[Sub-agents](#sub-agents)** - Additional agents the workflow can use
* **[Controller](#controller)** - An agent that guides users before the workflow starts
* **[Modules](#modules)** - Main agents with loop ability
* **[Specification](#specification)** - A project brief needed before starting
* **[Autonomous Mode](#autonomous-mode)** - Who drives the workflow (you or the system)
***
## How Workflows Execute
Workflows run step by step. Each step contains an agent that performs work, produces output, and passes context to the next step.
If tracks or conditions are defined, user answers questions to configure the workflow path.
Each step runs its agent. The agent receives prompts, uses tools, and produces output.
Files, outputs, and user choices flow to the next step as placeholders.
All steps finish. Final outputs are available in the project directory.
***
## Workflow vs Agent
| Concept | What It Is | Scope |
| ------------ | -------------- | ---------------------------- |
| **Workflow** | Execution plan | Orchestrates multiple agents |
| **Agent** | Engine session | Executes a single step |
A workflow coordinates agents. An agent does the actual work.
One workflow can have many agents. One agent belongs to one step.
***
## Components
### Name
The workflow name defines the objective of the overall workflow. It's what users see when selecting which workflow to run.
A clear name helps users understand what the workflow will accomplish before they start.
See how to name your workflow
### Steps
Steps are agents set in sequence. The arrangement matters for execution because each step receives context from previous steps.
Every workflow requires at least one step. Each step runs an agent that performs work and passes output to the next.
Think of steps like an assembly line. Each station (agent) does its job and hands off to the next. The order determines the flow of work and context.
Learn how to set up workflow steps
### Separators
Separators are visual dividers that organize your workflow into phases. They appear in the TUI timeline to help users understand workflow progress.
Use separators to group related steps together, like "Analysis Phase", "Implementation Phase", and "Review Phase".
Learn how to add visual dividers to your workflow
### Tracks
A track is a workflow variant, a path that determines which version of the workflow runs.
* Users pick one track (like choosing a route on a map)
* Each step can belong to specific tracks
* If a step doesn't belong to the selected track, it's skipped
Think of tracks like choosing between "Quick", "Standard", or "Enterprise" versions of the same workflow. Selecting "Quick" runs only the steps meant for that simpler path.
Learn how to set up workflow tracks
### Condition Groups
Conditions are feature flags, options that control which steps run based on what's needed.
* Users can select multiple conditions (like checkboxes)
* Steps can require all selected conditions to match
* Steps can also run if at least one condition matches
Imagine conditions like "Include UI", "Include API", or "Include Database". A step tagged with "Include UI" only runs if the user selected that option.
Learn how to set up workflow conditions
### Sub-Agents
Sub-agents are specialized helpers that main workflow agents can call upon to handle specific tasks.
Think of it like a manager delegating work to team members with different expertise:
* **Main Agent:** "Project Manager"
* **Sub-Agent:** "Frontend Developer" (builds UI)
* **Sub-Agent:** "Backend Developer" (builds API)
* **Sub-Agent:** "QA Engineer" (writes tests)
Sub-agents let you break complex work into specialized roles. Each sub-agent focuses on what it does best.
Learn how to set up workflow sub-agents
### Controller
A controller is a conversational guide, an agent that talks to the user before the main workflow starts.
It's like a project intake meeting: the controller asks questions, gathers requirements, and plans before the automated work begins.
**How it works:**
1. Controller starts and begins a conversation
2. User chats with controller (asks questions, provides context)
3. User presses Enter with no input to signal they're ready
4. Workflow steps execute
Controllers let you have a planning conversation before any automated work begins. The controller remembers the conversation, so it can be resumed later.
Learn how to set up workflow controllers
### Modules
Modules are main agents with loop ability. They can repeat their work until a goal is reached.
Unlike regular agents that run once and finish, modules can cycle back and refine their output based on feedback or changing conditions.
Think of modules as persistent workers. They keep going until the job is done right, not just done once.
View real workflow examples using modules
### Specification
A spec is a plain text document (markdown) that describes what you want to build: your project's goals, requirements, and context.
It's like a project brief you hand to a team before they start working.
You can set a workflow to never start without a spec, ensuring the agents always have clear direction.
Specs keep everyone (and every agent) on the same page. No guessing what needs to be built.
Learn how to require specifications
### Autonomous Mode
Autonomous mode controls who drives the workflow: you or the system.
* **Always autonomous** - The system runs everything automatically. You can't pause or intervene.
* **Never autonomous** - You stay in control. The system won't proceed without your input.
* **Toggle** - You can pause anytime to orchestrate manually, then hand control back to the system.
Choose based on how much oversight you need. Critical workflows might need human control. Routine tasks can run on autopilot.
Learn how to set up autonomous mode
***
## Import Workflows
Imports are external workflows built by the CodeMachine team or community.
* Shared via external repos
* Contains workflows, agents, prompts, and config
* Install via TUI or CLI
* Anyone can share, anyone can install
**Built-in workflows** come with the CodeMachine package. **[Imports](/build-workflows/import-workflows)** are installed separately.
***
## Next Steps
See how workflows take different shapes
Learn how to control workflow execution
# Workflow Controls
Source: https://docs.codemachine.co/core-concepts/workflow/controls
Understand how workflow execution is controlled - signals, modes, state, and recovery.
**How execution is controlled at runtime.**
## Signals
Signals are user-initiated events that interrupt or redirect workflow execution. They let you intervene while agents are running.
Stops execution and switches to manual mode. Use when you need to review or intervene.
Moves to the next step without completing the current one.
Switches between manual and auto mode.
Goes back to controller view (if controller exists).
Want to know the keyboard shortcuts for signals? [Check the shortcuts reference →](/reference/interactive-mode#keyboard-shortcuts)
Signals come from the user. Directives come from agents. Both control execution, but from different sources. [Learn more →](#signals-vs-directives)
***
## Modes
Two modes determine who drives the workflow:
**You control advancement.** Agents wait for you to proceed between steps and prompts.
Best for:
* Learning how workflows behave
* Debugging issues
* High-stakes operations requiring review
**The system controls advancement.** Either a controller agent makes decisions, or agents auto-advance without waiting.
Best for:
* Repetitive tasks
* Trusted workflows
* Background processing
You can switch modes at any time during execution.
### Who Drives the Workflow?
The actual behavior depends on three factors:
* **Mode** - Manual or [Auto](/build-workflows/advanced-workflows#autonomous-mode)
* **Paused** - Whether you've paused execution
* **[Agent Interactivity](/build-workflows/your-first-workflow#interactive-vs-non-interactive-steps)** - Whether the agent is configured to wait for input
| Auto Mode | Paused | Agent Interactive | Who Drives |
| --------- | ------ | ----------------- | --------------------------- |
| OFF | — | Yes | User |
| OFF | — | No | User (forced, with warning) |
| ON | YES | Any | User (pause overrides) |
| ON | NO | Yes | Controller |
| ON | NO | No | System (auto advance) |
**The rule:** Pausing always gives you control. Auto mode only takes over when not paused.
### Four Behaviors
You send input. Agent waits for you.
Controller agent sends input. Agent waits for controller.
System auto-advances. No waiting.
Agent designed to auto-advance but mode is manual. Falls back to user control with a warning.
***
## State
Workflows move through defined states during execution. State determines what actions are available and what the workflow is waiting for.
| State | Meaning |
| ------------------------ | -------------------------------------------------------------- |
| idle | Workflow has not started |
| running | An agent is actively executing |
| awaiting | Workflow is waiting for user input |
| delegated | Workflow is waiting for controller to decide |
| completed | All steps finished successfully |
| stopped | User exited the workflow view |
| error | Agent directive stopped the workflow or a fatal error occurred |
Want to see how states look in the TUI? Check the [Agent Status Icons](/reference/interactive-mode#agent-status-icons).
### How State Changes
**Starting:** `idle` → `running`
**During execution:**
* Agent needs input: `running` → `awaiting` → `running`
* Controller involved: `running` → `delegated` → `running`
**Ending:**
* All steps complete: `running` → `completed`
* Agent directive to stop: `running` → `error`
* User exits workflow view: `running` → `stopped`
***
## Recovery
Workflows are designed to survive interruptions. If the process crashes, loses connection, or terminates unexpectedly, CodeMachine can resume from where it left off.
### How Recovery Works
On startup, CodeMachine checks if a step was running but never completed.
Previous state is loaded from the persisted session.
Workflow continues based on mode:
* **Auto mode:** Sends continuation prompt to agent
* **Manual mode:** Pauses and waits for your input
### What Gets Persisted
Workflow state is continuously saved to `.codemachine/template.json`:
* Current step index
* Prompt queue progress (for chained prompts)
* Step completion status
* Agent session IDs
* Monitoring IDs for logs
### Recovery Scenarios
Resumes from last checkpoint.
Resumes on next workflow start.
State preserved, resume anytime.
Reconnects if session is still valid.
Recovery depends on proper session configuration. Each agent needs a unique session ID for reliable resumption. Want to know how to control workflow progress? See [Manipulating Workflow Progress](/build-workflows/runtime-state#manipulating-workflow-progress).
***
## Signals vs Directives
Both influence workflow execution, but they serve different purposes:
**Source:** User
**When:** Anytime during execution
**Purpose:** User intervention
**Examples:** Pause, Skip, Stop
**Source:** Agent
**When:** After a step completes
**Purpose:** Agent-controlled flow
**Examples:** Loop, Checkpoint, Trigger
Signals let you take control. [Directives](/core-concepts/agent-basics#directives) let agents request what should happen next.
***
## Next Steps
Understand multi-agent orchestration
Create a custom workflow from scratch
All available shortcuts reference
# Orchestration Patterns
Source: https://docs.codemachine.co/core-concepts/workflow/orchestration-patterns
Learn the common orchestration patterns and when to use each execution style.
**Workflows take many shapes. Here's how to choose.**
## At a Glance
You control every step
Controller runs agents
Zero interaction
Mix both styles
***
## Interactive
You respond at every step. Each agent asks questions, gathers insights, and produces output for the next agent. Press enter to proceed and inject the next prompt.
* Tasks need human judgment at each stage
* You want full control over direction
* Multiple perspectives improve the outcome
View a complete interactive workflow with logical flow and technical implementation
***
## Autonomous
This mode is in beta. Behavior may change as we refine controller-agent coordination.
**Controller agent runs agents on your behalf.**
You brief the controller agent with your objective and workflow structure. It manages the agents, makes decisions between steps. You review the results instead of managing the process.
* You have a clear objective but don't need to control every decision
* The task is too long to babysit
* You want to review results, not manage the process
**Prefixes:**
Both controller and step agents see input prefixes: `{USER (username):}` or `{agent_name:}`. You have full control to talk to either at any time.
* Talk to controller agent — give more instructions about the project
* Talk to step agent — give direct instructions for that step
You must brief the controller about the full workflow: what agents it will talk to and what output is expected from each. This keeps it on track. Autonomous is the hardest mode to control, but powerful for long objectives when managed correctly.
Both step agents and controller agent must be configured to use the signals MCP. Step agents propose proceeding to the next step, and the controller accepts or rejects. This replaces user interaction.
View a complete autonomous workflow with logical flow and technical implementation
***
## Continuous
**Auto-advance with zero interaction. Agents run to completion.**
You provide a specification file upfront. Agents iterate on it following a well-defined pattern. No pauses, no approvals — just results.
* The workflow pattern is proven and repeatable
* You have a clear specification file
* Same objective, different inputs each time
View a complete continuous workflow with logical flow and technical implementation
***
## Hybrid
**Mix interactive and auto-advance agents in the same workflow.**
Some steps need your input. Others run automatically. Hybrid gives you both — time effective and controllable.
This is possible because interactivity is set at the agent level, not the workflow level. Each agent decides whether to wait for you or proceed automatically.
* Key decisions need you, routine steps don't
* You want speed without losing control
* Most workflows fit this pattern
View a complete hybrid workflow with logical flow and technical implementation
***
## Choosing a Pattern
**User Involvement:** Every step
Best for tasks needing judgment, exploration, Q\&A
**User Involvement:** Brief controller, review results
Best for long-running tasks, clear objectives
**User Involvement:** None (spec upfront)
Best for repeatable, proven workflows
**User Involvement:** Key decisions only
Best for most real-world workflows
Most workflows end up being **Hybrid** — you want control where it matters and speed everywhere else.
***
## Next Steps
Learn how to control execution at runtime
Understand multi-agent orchestration
# CodeMachine Overview
Source: https://docs.codemachine.co/getting-started/overview
Learn how to install CodeMachine and start orchestrating coding agents into repeatable workflows.
**CodeMachine is an opensource tool that orchestrates AI coding agents into repeatable, long-running workflows.**
## Get Started in 30 Seconds
One working AI engine CLI configured (Codex, Claude Code, OpenCode, or others). [See supported engines →](/resources/engine-compliance)
```bash theme={null}
npm install -g codemachine # or bun/pnpm/yarn
```
```bash theme={null}
cd your-project
codemachine # or cm
```
You will see the interactive session started. That's it! [Continue with Quickstart →](/getting-started/quickstart)
See [**advanced setup**](/resources/advanced-setup) for installation options, manual updates, or uninstallation instructions.
***
## What CodeMachine Does For You
Define complex workflows once and execute them reliably on every project. Stop rebuilding the same patterns manually.
Assign different coding agents to different tasks. Each agent brings its own strengths.
Run multiple agents simultaneously on different parts of your workflow for faster results.
Execute workflows for hours or days. CodeMachine handles persistence so you don't have to babysit.
Centralize prompts, manage dynamic context, and control what each agent sees at each step.
Import community workflows or share your own. Build once, share everywhere.
***
## Next Steps
Build your first workflow in 5 minutes.
Understand how CodeMachine works under the hood.
***
## Resources
Core building blocks
Understanding multi-agent orchestration
Configure AI models for your workflows
Use and share community workflows
# Quick Start
Source: https://docs.codemachine.co/getting-started/quickstart
Get running with AI-powered workflows in minutes.
**Get running in 5 minutes.**
## Setup
```bash theme={null}
npm install -g codemachine
# or bun/pnpm/yarn
```
```bash theme={null}
codemachine
# to run codemachine interactive session
```
```bash theme={null}
/login
# to authenticate one or more AI engines
```
Each workflow specifies which engine(s) it uses. You can override this in the workflow file if needed. [See available engines →](/build-workflows/model-configuration#available-engines)
```bash theme={null}
/templates
# to list all built-in or imported templates
```
The default workflow is [Ali Workflow](/resources/workflow-library#ali-workflow-builder), a built-in workflow builder to help you create your first workflow. More workflows are available in the library but currently experimental. [Browse workflows →](/resources/workflow-library)
```bash theme={null}
/start
# to run the selected workflow
```
Your screen will differ depending on the workflow. You may see onboarding questions, indicating the workflow has [tracks or conditions](/core-concepts/workflow/basics#tracks). Once you reach the workflow screen, you're at the main screen where you can monitor all your agents.
You're now running your first workflow!
***
## Next Steps
Philosophy and core concepts
Learn execution styles
Core building blocks
Multi-agent orchestration
## Getting Help
Join the community
Report issues
Discuss with others
# CLI Reference
Source: https://docs.codemachine.co/reference/cli-reference
Complete reference for all CodeMachine CLI commands, flags, and environment variables.
## Main Command
```bash theme={null}
codemachine [options]
```
Launches the interactive TUI when run without subcommands.
Cannot run from home directory. Use `--dir` or `cd` into a project first.
### Global Options
| Flag | Description | Default |
| :----------------- | :---------------------------------- | :-------------------------------------- |
| `-d, --dir ` | Target workspace directory | Current directory |
| `--spec ` | Path to planning specification file | `.codemachine/inputs/specifications.md` |
| `-V, --version` | Display version | - |
| `-h, --help` | Display help | - |
***
## Commands
### version
```bash theme={null}
codemachine version
```
Display CLI version.
***
### run
```bash theme={null}
codemachine run