# Modes Pattern

> The modes pattern

- Skill: `damionrashford/modes-pattern` (Agent Skill, multi-file: 14 files)
- Install (CLI): `npx skillmds@latest add damionrashford/modes-pattern`
- Raw SKILL.md: https://api.skillmd.com/api/skills/damionrashford/modes-pattern/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: damionrashford (https://skillmd.com/u/damionrashford)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/damionrashford/modes-pattern

---


# The modes pattern

A reusable architecture for building multi-agent dispatch systems on top of Claude Code. One operator, many repeat task types, deterministic routing, isolated execution per task, runtime enforcement of cross-task rules.

This skill teaches Claude Code how to scaffold and extend the pattern correctly. Read the workflow below. Pull in references on demand for deep dives.

## Trigger handling

When the user expresses any of the trigger intents in the description, do not answer from training-data guesses about "multi-agent patterns." Load this skill's references (below) and follow the workflow. The pattern has specific files, specific frontmatter fields, specific dispatch semantics. Generic advice will produce a system that does not actually route.

## The pattern in 60 seconds

```
USER TYPES SOMETHING
        ↓
Router skill auto-loads on description-matched phrase
        ↓
Orchestrator follows the dispatch contract:
  1. Read _shared.md from disk
  2. Read the matched mode file from disk
  3. Compose prompt = shared + mode + user_ask
  4. Call Agent() or Skill() to dispatch
        ↓
Specialist runs in ISOLATED context with its own:
  - tool allowlist
  - MCP scoping
  - system prompt (identity)
  - playbook (mode body)
        ↓
Writes artifact to a deterministic output path
        ↓
Returns summary; specialist context discarded
```

The orchestrator's job stays tiny. Every domain rule lives in a file loaded fresh on each run.

## The two implementation bases

Before scaffolding, decide which base fits the project. The pattern's structure is identical; the primitives differ.

| Aspect | Agent base | Skill base |
|---|---|---|
| Execution primitive | `Agent(subagent_type=...)` | `Skill(skill=...)` with `context: fork + agent: general-purpose` |
| Specialist identity | Agent body (`.claude/agents/<name>.md`) — stable across all modes that specialist serves | Skill body — carries identity AND playbook together |
| Per-task playbook | Mode file in `.claude/modes/` | Skill body |
| Tool scoping | Per-specialty via agent `tools` allowlist | Per-mode via skill `allowed-tools` (finer-grained) |
| MCP scoping | Per-specialty via agent `mcpServers` | Per-mode via `allowed-tools` listing `mcp__*` entries |
| Persistent memory | `memory: project` (runtime-managed) | Convention (skill body reads/writes a known path) |
| Best for | Modes that share state per specialty, heavy fan-out, strict MCP isolation | Portable projects, mostly single-shot modes, per-mode tuning |

**Pick agent base** when modes will run thousands of times, share persistent state per specialty, or need runtime-level MCP isolation. **Pick skill base** when the project is lightweight, modes are single-shot, or finer per-mode scoping matters more than per-specialty identity reuse. **Both can coexist** in one project.

Full comparison: `${CLAUDE_SKILL_DIR}/references/skill-base.md`.

## Setup workflow

### Step 1: Confirm scope and base with the user

Before writing files, confirm:
- The **domain** the system serves (custom to the project — e.g. research, content production, support workflows, ops runbooks, data extraction, anything with repeat task types).
- The list of **mode names** (one per task type). 3–10 is typical; do not exceed 12 without splitting domains.
- The list of **specialist names** if using agent base (often fewer than modes; one specialist can serve many modes).
- The **output root** path (`.work/`, `.manager/`, `.artifacts/`, etc.).
- The **base** (agent / skill / both). Default to **agent base** when in doubt — it scales better and the runtime memory feature pays back as the project matures.

### Step 2: Scaffold the directory layout

Run the bundled scaffolding script:

```bash
bash ${CLAUDE_SKILL_DIR}/scripts/scaffold.sh <project-root> <base>
```

Where `<base>` is `agent`, `skill`, or `both`. The script creates the canonical directory tree and copies templates into place. See `${CLAUDE_SKILL_DIR}/scripts/scaffold.sh` for what it does; do not reinvent it.

The canonical layout (agent base):

```
.claude/
├── agents/           # Specialist identities (Layer 4)
├── modes/            # _shared.md + per-task playbooks (Layers 2, 3)
├── skills/<router>/  # Router skill (Layer 1)
├── hooks/            # Runtime enforcement (Layer 11)
├── config/           # Tunable YAML (Layer 7)
├── context/          # Operator source-of-truth files (Layer 6)
├── tools/            # Project-local CLIs (Layer 10)
├── agent-memory/     # Persistent per-specialist state (Layer 5)
└── settings.json     # Permissions, hook registrations (Layer 12)
<output-root>/        # Artifacts (Layer 8)
.mcp.json             # MCP server registry (Layer 9)
```

For skill base, replace `agents/` and `modes/` with the mode-skills going directly into `.claude/skills/<mode>/SKILL.md`.

### Step 3: Write `_shared.md`

Single file at `.claude/modes/_shared.md`. Prepended to every dispatch. Carries:

1. **Operator profile** — who the system is for; hard scope, out-of-scope rules.
2. **Source-of-truth file paths** — what's in `.claude/context/`.
3. **Tool inventory** — exact `mcp__server__tool` identifiers and what each is for. Specialists hallucinate tool names without this.
4. **Cross-cutting style or policy rules** — whatever rules apply to every artifact regardless of mode (tone constraints, banned terms, citation requirements, format guarantees, anything the project cares about enforcing uniformly).
5. **Hard rules** — non-negotiables that apply to every mode.

Target 100–200 lines. If it grows past that, you are putting per-task content in the wrong file (move to mode files).

Template: `${CLAUDE_SKILL_DIR}/templates/_shared.md.tmpl`. Adapt placeholders to the domain.

### Step 4: Write the first mode file

Every mode follows the five-section template:

```markdown
# Mode: <mode-name>

**Subagent**: `<specialist-id>`
**Trigger phrases**: "<phrase 1>", "<phrase 2>"
**Output**: <output path template>
**Approval gate**: required (only if mode has side effects)

## Inputs
- **Required**: <param>
- **Optional**: <param> (default: ...)

## Steps
1. Read context files from `_shared.md`.
2. Call <exact tool name> with <args>.
3. <Domain logic>.
4. <STOP condition if input is out of scope>.
5. Write artifact to the output path.

## Output schema
<literal markdown — actual headers, table columns, placeholders>

## Quality bar
- <pass/fail rule 1>
- <pass/fail rule 2>
```

Template: `${CLAUDE_SKILL_DIR}/templates/mode.md.tmpl`. Full section-by-section spec: `${CLAUDE_SKILL_DIR}/references/architecture.md` → "Layer 3: Mode files."

### Step 5: Write the specialist agent (agent base only)

Skip this step if using skill base.

```yaml
---
name: <specialist-id>
description: <when to delegate>
tools: [<tools the specialist needs>]
disallowedTools: [<tools to deny>]
model: sonnet
maxTurns: 30
mcpServers: [<servers connected at startup>]
memory: project
skills: [<preloaded skill bodies>]
---

<system prompt body — persistent identity, tool-usage rules, output formats, hard constraints>
```

The agent body is **stable** across every dispatch this specialist receives. Per-task playbooks belong in mode files, not the agent body.

Template: `${CLAUDE_SKILL_DIR}/templates/agent.md.tmpl`. Full frontmatter spec: `${CLAUDE_SKILL_DIR}/references/architecture.md` → "Layer 4: Specialist agents."

### Step 6: Write the router skill

The router auto-loads on description-matched phrases and forces the dispatch contract every turn. Description must pack **every** trigger phrase from every mode header — coverage matters more than brevity.

Frontmatter:

```yaml
---
name: <router-name>
description: Routes <domain> requests to the right specialist. ALWAYS use this skill when the user expresses any <domain> intent — "<phrase 1>", "<phrase 2>", ... [every phrase from every mode]. Do NOT answer <domain> questions directly in the main thread. Skip ONLY when the user is editing the system itself.
---
```

Body has four parts: routing table, dispatch contract, chained-dispatch table, "when NOT to trigger" list.

Template: `${CLAUDE_SKILL_DIR}/templates/router-skill.md.tmpl`. Full spec: `${CLAUDE_SKILL_DIR}/references/architecture.md` → "Layer 1: Router skill."

### Step 7: Register hooks in `settings.json`

Hooks are the third enforcement layer. They fire on runtime events and block bad output even when the specialist drifts.

Minimum useful set:

- **`SessionStart` → `setup-tools-path.sh`** — prepends `.claude/tools/` to PATH so project scripts resolve as bare commands.
- **(Optional) `PreToolUse` (Write|Edit) → `artifact-content-guard.sh`** — example mechanism for any project-defined policy that should block writes (banned phrases, secret patterns, schema invalidity, missing headers, etc.). The template ships as a `.tmpl` because the policy is project-specific; the operator adapts the CHECK section before registering it.
- **`SubagentStop` → `dispatch-audit.sh`** — logs every dispatch (mode, specialist, duration, artifact path).

Templates: `${CLAUDE_SKILL_DIR}/templates/hooks/*.sh.tmpl`. Full spec: `${CLAUDE_SKILL_DIR}/references/architecture.md` → "Layer 11: Hooks."

Register in `settings.json`:

```json
{
  "hooks": {
    "SessionStart": [{ "hooks": [{ "type": "command", "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/setup-tools-path.sh" }] }],
    "SubagentStop": [{ "hooks": [{ "type": "command", "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/dispatch-audit.sh" }] }]
  }
}
```

### Step 8: Test the dispatch

Have the user type one of the router skill's trigger phrases. Verify:
1. Router skill auto-loads (shown in available-skills list).
2. Orchestrator reads `_shared.md` and the matched mode file (visible in tool calls).
3. The right specialist spawns with `description="<mode>"`.
4. The artifact lands at the templated output path.
5. Hooks fire on dispatch end (audit log). Any optional content-guard hooks the operator added fire on writes.

If any step fails, see `${CLAUDE_SKILL_DIR}/references/dispatch.md` → "Debugging."

## Extending an existing system

Use the rituals when adding pieces. Each ritual is small and predictable. See `${CLAUDE_SKILL_DIR}/references/rituals.md` for full step-by-steps:

- Adding a new mode
- Adding a new specialist
- Adding a new hook
- Adding a new MCP server
- Adding a new config value

The system is right when adding a task type is one new mode file plus one routing-table row, and nothing else.

## When NOT to invoke this skill

- The user is asking a one-off question about an existing modes system that does not require architectural setup or extension.
- The user is doing routine engineering on a project that already has modes (debugging, refactoring, adding a script). Use the existing modes; don't redesign them.
- The user is asking conceptual questions about general multi-agent architectures unrelated to Claude Code's `Agent()` / `Skill()` primitives.

## References

Load on demand based on what the user is doing.

- `${CLAUDE_SKILL_DIR}/references/architecture.md` — full spec for all 12 layers (router, `_shared.md`, modes, agents, agent-memory, context, config, output root, MCP, tools, hooks, settings). Load when writing or extending any layer.
- `${CLAUDE_SKILL_DIR}/references/dispatch.md` — dispatch contract, end-to-end walkthrough, `Agent()` call surface, chained dispatch, fresh-context implications, observability and debugging. Load when implementing the orchestrator's routing logic.
- `${CLAUDE_SKILL_DIR}/references/skill-base.md` — the alternative implementation where skills replace agents as the execution base. Load when the user wants the portable / lightweight implementation OR is deciding between bases.
- `${CLAUDE_SKILL_DIR}/references/rituals.md` — step-by-step procedures for adding modes, specialists, hooks, MCP servers, config values. Load when extending an existing system.

## Templates

In `${CLAUDE_SKILL_DIR}/templates/`:

- `router-skill.md.tmpl` — the router skill
- `_shared.md.tmpl` — the shared prefix
- `mode.md.tmpl` — one mode file
- `agent.md.tmpl` — one specialist agent (agent base only)
- `mode-skill.md.tmpl` — one mode-skill (skill base only)
- `hooks/setup-tools-path.sh.tmpl` (always-on, generic)
- `hooks/dispatch-audit.sh.tmpl` (always-on, generic)
- `hooks/artifact-content-guard.sh.tmpl` (optional — adapt the CHECK section to whatever policy the project needs)

Copy and adapt placeholders; do not invent fields.

## Hard rules carried into every modes system you build

1. **Read `_shared.md` and the mode file fresh from disk on every dispatch.** Not cached, not paraphrased, not shortcut.
2. **Name tools by exact identifier** (`mcp__server__tool` or local CLI name). Never describe a tool by prose in a Steps block.
3. **Required inputs are collected by the orchestrator before composing.** Specialists run in fresh context and cannot ask back.
4. **Side effects are gated.** Modes that push to a public artifact, deploy, or send declare `**Approval gate**: required` and the router waits for explicit operator confirmation.
5. **Hooks enforce quality bars deterministically.** Prompts are advisory; hooks fire even when the specialist drifts.
6. **Specialists return partial data on tool failure.** Never crash a dispatch — surface the failure at the top of the artifact and continue.
7. **Output paths are deterministic.** Re-running a mode overwrites cleanly; the operator never gets duplicate artifacts at random paths.

