| name | chain-builder |
| description | Set up workflow templates and manage chain flows. Trigger when user says: "set up a workflow", "create a development workflow", "I need a CI/CD pipeline", "set up devops", "bump develop", "bump devops", "add agent to chain", "show chain flow", "edit chain config", "create custom workflow", "add a team node", "run agents in parallel", "create agent team", "validate chain", "check chain config", "verify chain". |
Chain Builder
Set Up a Workflow Template
Use MCP tool:
mcp__brainbrew__template_bump(template: "develop")
Templates
| Template | Chain |
|---|
develop | planner → plan-reviewer → implementer → parallel-review (team) → tester → git-manager |
devops | code-scanner → security-auditor → test-runner → deployer → monitor |
marketing | researcher → content-writer → editor → seo-optimizer → publisher |
research | topic-researcher → source-gatherer → analyzer → synthesizer → report-writer |
docs | code-scanner → doc-generator → doc-reviewer → formatter → publisher |
support | ticket-classifier → router → knowledge-searcher → response-drafter → reviewer |
data | data-collector → cleaner → analyzer → visualizer → reporter |
moderation | content-scanner → classifier → flagger → reviewer → actioner |
review | code-reviewer → END |
skill-dev | skill-finder → skill-creator → skill-reviewer (PASS = END, FIXES → skill-improver) |
Show Chain Flow
List chains and show the active one:
mcp__brainbrew__chain_list()
View active chain config:
cat .claude/chains/$(grep 'active:' .claude/chain-config.yaml | cut -d' ' -f2).yaml
Validate Chain Config
mcp__brainbrew__chain_validate()
Checks:
- All agents in flow have matching
.claude/agents/{name}.md files
- Team nodes have valid teammates with
name and agent fields
- Teammate agents exist in
.claude/agents/
- All routes point to nodes defined in the flow
- No dead-end nodes (nodes without routes)
Returns ✅ PASS or list of ❌/⚠ issues.
Chain Config Structure
The project uses a pointer file + chain directory:
.claude/chain-config.yaml # pointer to active chain
.claude/chains/
develop.yaml # chain definition (hooks + flow)
discovery.yaml # another chain
Pointer file (.claude/chain-config.yaml):
active: develop
chains_dir: .claude/chains/
Each chain file in .claude/chains/ only contains a flow: section (and optional saveOutput:). Hook dispatch is handled by runner.cjs automatically.
saveOutput:
- explore
- scout
flow:
agent-name:
routes:
next-agent: "When to go here"
decide: |
AI routing rules
The saveOutput: list at the top level specifies which agent types always save their output. The explore agent is saved by default even without this field. Outputs go to .claude/outputs/{agent}/{timestamp}.md.
List Chains
mcp__brainbrew__chain_list()
Shows all chains and which is active.
Switch Active Chain
mcp__brainbrew__chain_switch(chain: "discovery")
Takes effect immediately for subsequent agent runs. Use chain_switch when you want to change the active chain without enforcing the first agent.
Run a Chain (Recommended)
mcp__brainbrew__chain_run(chain: "discovery")
Switches to the chain, clears previous chain state, and enforces the first agent immediately. PreToolUse and Stop hooks will block until the first agent is spawned. Use chain_run as the preferred way to start a chain from scratch.
Flow Node Types
There are two node types: agent (default) and team.
Add Agent Node
Edit the active chain file in .claude/chains/:
flow:
new-agent:
routes:
next-agent: "Success — move forward"
fallback: "Failed — try alternative"
decide: |
If SUCCESS → "next-agent"
If FAILED → "fallback"
Then update the previous agent's routes to point to the new agent.
Agent Node Fields
| Field | Required | Purpose |
|---|
routes | Yes | Map of agent-name: "description". Multiple routes allowed |
decide | No | AI prompt sent to Haiku to pick route based on agent output |
reset_counters | No | Reset loop counters when routing (for approval gates). Loop protection is off by default. |
context | No | Extra context injected into the agent's system-reminder via SubagentStart. Supports inline text or multiline block (|). |
config_keys | No | List of top-level keys from .claude/config.yaml to inject for this agent. Omit or leave empty → no config injected. Example: [user, git]. |
saveOutput | No | Set to true to save this agent's output to .claude/outputs/{agent}/{timestamp}.md regardless of the top-level saveOutput: list. |
next | No | Legacy: simple next agent (use routes instead) |
on_fail | No | Legacy: fallback on failure keywords |
on_issues | No | Legacy: fallback on issue keywords |
How Routing Works
- Agent completes → PostToolUse hook fires
- If
decide prompt exists and output > 50 chars → Haiku analyzes output against routing rules
- Haiku returns
{"route": "agent-name", "reason": "..."}
- If Haiku fails → fallback to keyword matching (pass/approved/success vs fail/error/issues)
- If no match → default to first route
- Route
"END" stops the chain
Chain Enforcement
runner.cjs enforces pending chain steps before running any hook:
- PreToolUse: If a chain step is pending (
currentAgent is set), any non-Agent tool call is blocked with a reminder to spawn the required agent first.
- Stop: If a chain step is pending, the session stop is blocked with a MANDATORY NEXT STEP reminder.
- Release after 3 blocks: If the same event is blocked 3 times, the pending state is cleared and execution is released with a hint to spawn the agent.
- Bypass: Type
skip chain or /skip-chain in any message to clear the pending state immediately.
Chain state is stored per session in ~/.claude/tmp/chain-state/{sessionId}.json with two fields: currentAgent (the pending next agent) and chainBlockCount (how many times the current step has been blocked).
Agent Communication
When an agent completes, PostToolUse saves its full output to ~/.claude/tmp/agent-outputs/{agentId}.md. Before the next agent spawns, the PreToolUse hook (runner.cjs) reads this file and injects it directly into the new agent's prompt as a ## Previous Agent Output ({type}) section via updatedInput. This gives every agent in the chain automatic access to what the previous agent produced, without any manual wiring.
Add Agent Team Node
Agent teams run multiple agents in parallel at a chain step. Each teammate gets its own context and they can communicate with each other.
flow:
parallel-review:
type: team
teammates:
- name: code-quality
agent: code-reviewer
prompt: "Review code for bugs, quality, and adherence to plan"
- name: security-check
agent: security-scan
prompt: "Scan for security vulnerabilities and exposed secrets"
routes:
tester: "All reviews passed"
implementer: "Issues found, needs fixes"
decide: |
If ALL reviews PASSED with no issues → "tester"
If ANY review found bugs, issues, vulnerabilities → "implementer"
Team Node Fields
| Field | Required | Purpose |
|---|
type | Yes | Must be team |
teammates | Yes | Array of teammate definitions |
routes | Yes | Same as agent node — where to go after team completes |
decide | No | AI routing rules applied to synthesized team output |
Teammate Fields
| Field | Required | Purpose |
|---|
name | Yes | Unique identifier for this teammate |
agent | Yes | Agent type to spawn (must exist in .claude/agents/) |
prompt | No | Specific instructions for this teammate's focus area |
model | No | Override model (sonnet, opus, haiku) |
How Teams Work
- Previous agent completes → hook detects next node is
type: team
- Hook emits MANDATORY NEXT STEP instructing Claude to create an agent team
- Claude spawns all teammates in parallel using TeamCreate
- Each teammate works independently with its own context
- After all teammates finish, results are synthesized
- Hook routes to next agent based on
decide rules
When to Use Teams vs Sequential Agents
| Use Teams | Use Sequential |
|---|
| Independent tasks (review + security + tests) | Tasks that depend on each other |
| Different perspectives on same work | Each step builds on previous output |
| Speed matters — parallel is faster | Order matters — must be sequential |
| Teammates don't edit same files | Agents modify shared files |
Team Examples
Parallel code review (security + quality + performance):
comprehensive-review:
type: team
teammates:
- name: security
agent: security-scan
prompt: "Focus on vulnerabilities, injection risks, exposed secrets"
- name: quality
agent: code-reviewer
prompt: "Focus on bugs, logic errors, naming, patterns"
- name: performance
agent: code-reviewer
prompt: "Focus on performance bottlenecks, memory leaks, N+1 queries"
routes:
tester: "All clear"
implementer: "Issues found"
Parallel research:
parallel-research:
type: team
teammates:
- name: frontend-scout
agent: scout
prompt: "Explore frontend architecture, components, state management"
- name: backend-scout
agent: scout
prompt: "Explore backend architecture, APIs, database schema"
- name: test-scout
agent: scout
prompt: "Explore test coverage, testing patterns, CI setup"
routes:
planner: "Research complete, ready to plan"
Create Custom Workflow
- Create the chain file directly:
.claude/chains/{name}.yaml with a flow: section
- Create agents:
.claude/agents/{name}.md
- Create skills (optional):
.claude/skills/{name}/SKILL.md
- Run chain:
mcp__brainbrew__chain_run(chain: "name") (recommended) or mcp__brainbrew__chain_switch(chain: "name") to switch without enforcement
- Restart Claude Code session
Hook System
runner.cjs dispatches built-in chain scripts (post-agent, subagent-start, subagent-stop, post-tool-use) inline for the relevant events. Chain files do not carry a hooks: section.
For user customization, create .claude/hooks.yaml to register additional scripts that run after the built-ins:
PreToolUse:
- plugin:safety-guard.cjs
- ./my-linter.js
SessionStart:
- plugin:session-start.cjs
- ./setup-env.js
SessionEnd:
- plugin:session-end.cjs
PostToolUse:
- ./my-logger.js
SubagentStart:
- ./inject-context.js
SubagentStop:
- ./my-validator.js
UserPromptSubmit:
- ./my-prompt-filter.js
Stop:
- ./cleanup.js
Notification:
- ./my-notifier.js
Scripts go in .claude/hooks/. Each receives stdin JSON from Claude Code.
Return {"decision": "block", "reason": "..."} to block, or exit 0 to pass through.
Available lifecycle events: PreToolUse, PostToolUse, SubagentStart, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, Stop, Notification
Plugin scripts (opt-in via plugin: prefix in hooks.yaml):
| Script | Purpose |
|---|
plugin:safety-guard.cjs | Block dangerous commands (rm -rf, git push --force, DROP TABLE, etc.) |
plugin:session-start.cjs | Session initialization and context setup |
plugin:session-end.cjs | Session cleanup |
Script Path Resolution
| Prefix | Resolves to |
|---|
plugin: | Plugin's built-in scripts |
./ | .claude/hooks/ in project |
/absolute | Absolute path |
Post-Bump Tuning
After template_bump, review and tune these files:
1. Chain Config (.claude/chains/{name}.yaml)
- Adjust routing rules in
decide prompts
- Add/remove agents from flow
- Configure
reset_counters for approval gates
2. Agent Definitions (.claude/agents/*.md)
- Update
description for your project context
- Adjust
tools list (add/remove as needed)
- Add project-specific skills in
skills: frontmatter
3. Skills (.claude/skills/*/SKILL.md)
- Update skill instructions for your stack/conventions
- Add project-specific rules and patterns
- Reference common patterns from
.claude/skills/common/
4. Project Config (.claude/config.yaml)
- Scaffolded on first bump; tune values for this project.
- Personal overrides →
.claude/config.local.yaml (deep-merged; add to .gitignore yourself).
- Inject per agent via
config_keys: [user, git, ...] in the chain flow.
5. Validate
mcp__brainbrew__chain_validate()
Install Plugins
Plugins extend Claude Code sessions with background tools (notifications, cost tracking, sandboxing, etc.).
Browse available plugins:
mcp__brainbrew__plugin_list()
Search by keyword:
mcp__brainbrew__plugin_list(query: "docker")
mcp__brainbrew__plugin_list(query: "cost")
Each result includes the plugin path. Read its CLAUDE.md for install instructions — the AI handles the rest.
To customize a plugin, copy it into the project:
cp -r <plugin-path> .claude/plugins/<name>/
Output Saving
Agents can save their output to .claude/outputs/{agent}/{timestamp}.md. There are two ways to enable this:
Top-level list — add a saveOutput: section to the chain YAML to auto-save specific agent types:
saveOutput:
- explore
- planner
Per-node flag — set saveOutput: true on any agent node in the flow:
flow:
scout:
saveOutput: true
routes:
planner: "Research complete"
The explore agent is always saved by default even without explicit config.
Output File Format
Each saved file has a YAML frontmatter block followed by the agent's prompt and output:
---
agent: planner
id: {agentId}
tokens: 12450
duration_ms: 34200
tools_used: 8
timestamp: 2026-04-11T10:15:22.000Z
session: {sessionId}
next: implementer
description: "Create implementation plan for feature X"
tool_breakdown:
Read: 4
Bash: 2
Grep: 2
files_read:
- /path/to/file.ts
files_modified: []
files_created: []
bash_commands:
- "git status"
grep_searches:
- "pattern in src/"
---
## Prompt
{agent prompt}
## Output
{agent output}
Agent stats (tool_breakdown, files_read, files_modified, files_created, bash_commands, grep_searches) are parsed from the agent's JSONL transcript by SubagentStop and stored in ~/.claude/tmp/agent-stats/{agentId}.json before the output file is written.
Output Directory Structure
.claude/outputs/
explore/
2026-04-10T22-36-35.md
planner/
2026-04-11T10-15-22.md
scout/
2026-04-11T11-00-01.md
After Setup
Tell user:
Workflow ready! You can:
- "Create an agent for X"
- "Create a skill for Y"
- "Add a team node for parallel review"
- "Add agent context for X" (context injection)
- "Show the chain flow"
- "List available plugins" (plugin_list)