Skip to content
/

barkain/claude-code-workflow-orchestration

barkain-workflow-orch · barkain/claude-code-workflow-orchestration · ★ 60 · last commit 2026-05-21

Enforce Director/Coder split via adaptive hook-based delegation nudges, native plan mode as the handoff boundary, and 8 specialized agents for domain execution.

Best whenSoft enforcement (adaptive nudges via PreToolUse hooks) is more effective than hard blocks; plan mode is the correct boundary between planning and execution.
Skip ifMain agent executing work tools directly instead of delegating, Entering plan mode when the plan is already approved (re-invocation guard)
vs seeds
bmad-methodin using persona-md agents and a plan-then-execute cycle, but uniquely implements hook-enforced delegation: the main age…
Primitive shape 22 total
Commands 2 Subagents 8 Hooks 12
00

Summary

Barkain Claude Code Workflow Orchestration — Summary

This Claude Code plugin (60 stars) enforces a strict Director/Coder split via adaptive hook-based delegation: the main Claude Code agent is required to use /workflow-orchestrator:delegate to route every task to one of 8 specialized agents rather than directly using tools itself. Hard blocking has been replaced with adaptive nudges (silent → hint → warning → strong) that escalate per turn when the main agent bypasses delegation. The system uses Claude Code's native plan mode (EnterPlanMode/ExitPlanMode) for two-stage execution: Stage 0 decomposes the request into a task DAG with wave assignments, and Stage 1 executes agents in parallel waves. A dual-mode execution model selects between isolated subagents (default) and experimental Agent Teams (when CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1) based solely on tool availability. Hooks cover 6 lifecycle events (PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SubagentStop, Stop) with Python-based validators, lean session injection (stub orchestrator ~1.1KB at startup, full ~7.5KB on-demand), and Python/Ruff validators auto-running PostToolUse on file edits. Compared to seeds, it most closely resembles BMAD-METHOD (persona-md agents, plan-then-execute) but uniquely implements hook-enforced delegation rather than relying on agent discipline, and adds native plan mode integration as the planning/execution handoff mechanism.

01

Overview

Barkain Claude Code Workflow Orchestration — Overview

Origin

Created by barkain (GitHub). Python-based hooks with uv scripting. Active development in 2025–2026.

Philosophy

"Hook-based delegation-enforced workflow architecture that routes tasks to specialized agents."

The core problem it solves: Claude Code agents tend to do work themselves rather than routing to specialized agents. A main agent that can access tools directly will use them directly, bypassing the orchestration system. This plugin's answer is enforcement through hooks rather than through prompt instructions.

"Soft Enforcement via Adaptive Nudges - No hard blocks. PreToolUse hook emits per-turn escalating stderr reminders (silent → hint → warning → strong) when main agent bypasses /workflow-orchestrator:delegate. Subagents immune. Nudge counter resets each turn and zeros when delegation runs."

Key Architectural Decisions

  1. Adaptive nudges over hard blocks — Previous version blocked tool use; current version nudges. The README notes this improves usability while maintaining behavioral pressure.
  2. Lean session start — Stub orchestrator (~1.1KB) injected at startup; full orchestrator loaded on first delegation. Token efficiency is an explicit design goal.
  3. Plan mode as handoff — Native Claude Code EnterPlanMode/ExitPlanMode tools are the Stage 0 → Stage 1 boundary. The plan is written before ExitPlanMode and recovered from disk if context is cleared.
  4. One decision rule for mode selection — "If TeamCreate is in your available tools → team mode. Otherwise → subagent mode." No configuration, no scoring.

Version

Analyzed from main branch (no semver); last pushed 2026-05-21.

02

Architecture

Barkain Claude Code Workflow Orchestration — Architecture

Distribution

  • Type: Claude Code plugin
  • Plugin manifest: .claude-plugin/plugin.json
  • Language: Python (hooks), Markdown (agents/commands)

Installation

# Recommended: plugin marketplace
claude plugin marketplace add barkain/claude-code-workflow-orchestration
claude plugin install workflow-orchestrator@barkain-plugins

# Manual:
git clone https://github.com/barkain/claude-code-workflow-orchestration.git
path/to/repo/install.sh

Directory Tree

barkain/claude-code-workflow-orchestration/
├── .claude-plugin/
│   ├── plugin.json          # Plugin manifest
│   └── marketplace.json
├── agents/                  # 8 specialized agent persona files
│   ├── tech-lead-architect.md
│   ├── code-cleanup-optimizer.md
│   ├── code-reviewer.md
│   ├── codebase-context-analyzer.md
│   ├── dependency-manager.md
│   ├── devops-experience-architect.md
│   ├── documentation-expert.md
│   └── task-completion-verifier.md
├── commands/
│   ├── delegate.md          # Main orchestrator command
│   └── add-statusline.md    # Enable status line display
├── hooks/
│   ├── plugin-hooks.json    # Hook configuration
│   ├── PreToolUse/          # require_delegation.py, validate_task_graph.py, token_rewrite_hook.py
│   ├── PostToolUse/         # python_posttooluse_hook.py, validate_task_graph_depth.py, remind_todo.py
│   ├── UserPromptSubmit/    # clear-delegation-sessions.py
│   ├── SessionStart/        # inject_all.py
│   ├── SubagentStop/        # remind_todo_update.py, trigger_verification.py
│   └── stop/                # python_stop_hook.py
├── system-prompts/          # Orchestrator system prompts
├── output-styles/           # technical-adaptive output style
├── docs/                    # Documentation
└── settings.json            # Plugin settings schema

Required Runtime

  • Claude Code
  • Python 3.12+ (for uv script hooks)
  • uv (curl -LsSf https://astral.sh/uv/install.sh | sh)
  • bun (for parallel workflow state tracking)
  • jq (for parallel workflow features)

Target AI Tools

Claude Code exclusively (hooks are Claude Code lifecycle events)

03

Components

Barkain Claude Code Workflow Orchestration — Components

Commands (2)

Command Purpose
delegate.md Main orchestration command: plan mode → DAG decomposition → wave execution
add-statusline.md Enable workflow status line display in Claude Code

Agents (8 specialized)

Agent Domain Return Format
tech-lead-architect Design, research, best practices, architecture DONE|{output_file_path}
code-cleanup-optimizer Refactoring, dead code removal, optimization DONE|{output_file_path}
code-reviewer Code review, quality checks DONE|{output_file_path}
codebase-context-analyzer Codebase exploration, pattern detection DONE|{output_file_path}
dependency-manager Dependency updates, compatibility DONE|{output_file_path}
devops-experience-architect CI/CD, deployment, infrastructure DONE|{output_file_path}
documentation-expert Documentation creation and updates DONE|{output_file_path}
task-completion-verifier Verification, testing, quality gates DONE|{output_file_path}

All agents share the same return protocol: write output to $CLAUDE_SCRATCHPAD_DIR, return DONE|{path}. In Agent Teams mode, they also use SendMessage for peer communication.

Hooks (6 lifecycle events)

Event Hook Files Purpose
PreToolUse (*) require_delegation.py Adaptive nudge when bypassing delegation
PreToolUse (*) validate_task_graph_compliance.py Validate Agent/Task invocations against task graph
PreToolUse (Bash) token_rewrite_hook.py Rewrite bash through compact_run.py for token efficiency
PostToolUse (Edit|Write|MultiEdit) python_posttooluse_hook.py Ruff + Pyright validation on Python file edits
PostToolUse (ExitPlanMode|Skill|SlashCommand) remind_skill_continuation.py Remind to continue after skill
PostToolUse (Agent|Task) validate_task_graph_depth.py Enforce min depth-3 decomposition
PostToolUse (Agent|Task) remind_todo_after_task.py Async todo reminder
UserPromptSubmit clear-delegation-sessions.py Reset delegation counter per user turn
SessionStart (startup|resume|clear|compact) inject_all.py Inject stub orchestrator + CLI guide
SubagentStop (*) remind_todo_update.py Async todo update reminder
SubagentStop (*) trigger_verification.py Trigger task-completion-verifier
Stop python_stop_hook.py Session cleanup

Scripts

  • hooks/compact_run.py — Token-efficient bash output wrapper
  • All hook scripts: uv-invokable Python scripts with inline deps (uv run --no-project --script)
05

Prompts

Barkain Claude Code Workflow Orchestration — Prompts

Verbatim Excerpt 1: delegate.md — Routing Logic (Four-Step Check)

## ROUTING (CHECK FIRST - MANDATORY)

**Four-step routing check. MUST follow this order:**

### Step 1: Write Detection
**Write indicators:** create, write, save, generate, produce, output, report, build, make, implement, fix, update
**If ANY write indicator found -> Continue to Step 2**

### Step 2: Breadth Task Detection
**Pattern:** Same operation applied to multiple items (e.g., "review 16 files", "analyze all modules")
**Breadth keywords:** review, analyze, summarize, scan + quantifiers like "all", "each", "files in", or explicit counts

### Step 3: Fully-Specified Task Detection
**Pattern:** The user provided explicit, ordered steps with no ambiguities or design decisions needed.
**Indicators (ANY of these):**
- Numbered or ordered steps in the request ("1. do X, 2. do Y, 3. do Z")
- Explicit skip-planning signals: "just do it", "no plan needed", "skip planning", "don't plan"
...
**If fully-specified -> DIRECT SEQUENTIAL EXECUTION** (skip plan mode)

Prompting technique: Keyword-matching routing decision table — the model is given explicit vocabulary lists ("Write indicators", "Breadth keywords") and ordered decision rules. This reduces routing ambiguity by making the decision algorithm explicit and enumerable rather than left to model judgment.


Verbatim Excerpt 2: tech-lead-architect.md — Agent Return Protocol

## RETURN FORMAT (CRITICAL)

Return EXACTLY: `DONE|{output_file_path}` — nothing else. Example: `DONE|$CLAUDE_SCRATCHPAD_DIR/design_payment_api.md`
All findings go in the output file. No summaries, explanations, or text beyond `DONE|{path}` in return value.

...

## COMMUNICATION MODE

**Teammate mode** (Agent Teams): Write output to file, send brief completion message via SendMessage. Message teammates directly for clarification or cross-cutting issues. Never call TeamCreate.
**Subagent mode**: Return EXACTLY `DONE|{output_file_path}`, nothing else.

Prompting technique: Machine-parseable return format (DONE|{path}) enables the orchestrator to reliably parse agent completion without natural language parsing. Dual-mode communication (file+SendMessage for teams vs. DONE|path for subagents) is explicitly encoded in the agent prompt rather than inferred from context.


Verbatim Excerpt 3: hooks/plugin-hooks.json — Adaptive Nudge Hook

"PreToolUse": [
  {
    "matcher": "*",
    "hooks": [
      {
        "type": "command",
        "command": "uv run --no-project --script \"${CLAUDE_PLUGIN_ROOT}/hooks/PreToolUse/require_delegation.py\"",
        "timeout": 5
      }
    ]
  }
]

Design pattern: uv run --no-project --script pattern loads dependencies inline per-script invocation (specified as inline metadata in the .py file). No venv setup required. The * matcher means every tool use goes through the delegation check — the script decides whether to emit a nudge based on context.

09

Uniqueness

Barkain Claude Code Workflow Orchestration — Uniqueness

Differs from Seeds

Closest seed: BMAD-METHOD — both use persona-md agents and a plan-then-execute workflow. Key architectural deltas: (1) Barkain uniquely implements hook-enforced delegation — the main agent is physically nudged (via PreToolUse hook stderr) when it bypasses the orchestration pattern, whereas BMAD relies entirely on prompt instructions; (2) Barkain uses Claude Code's native plan mode (EnterPlanMode/ExitPlanMode) as the Stage 0/Stage 1 handoff — BMAD has no equivalent Claude Code-specific integration; (3) Barkain's dual-mode execution (subagent vs. experimental Agent Teams) routes based solely on tool availability, requiring no configuration; (4) Python/Ruff PostToolUse validators auto-run on every Python file edit — BMAD has no automated post-edit validation. Also comparable to claude-flow (both have multi-agent wave execution) but Barkain is a Claude Code plugin rather than an npm library.

Positioning

This framework occupies the "maximum automation with enforcement" niche: it doesn't trust the agent to follow the orchestration pattern voluntarily — it enforces it via hooks. The soft enforcement model (adaptive nudges vs. hard blocks) represents a pragmatic refinement from the previous hard-blocking approach.

Observable Failure Modes

  1. uv dependency — All hooks use uv run --no-project --script. If uv is not installed or the uv version changes behavior, all hooks fail silently or noisily.
  2. Token rewrite complexity — The token_rewrite_hook.py Bash output rewriter adds latency to every Bash call and could produce unexpected output formats for complex commands.
  3. Agent Teams experimental flag — The dual-mode system selects team mode based on TeamCreate tool availability. If Claude enables this tool broadly before the feature stabilizes, teams accidentally run in unstable mode.
  4. Depth-3 enforcementvalidate_task_graph_depth.py enforces minimum depth-3 decomposition. Simple tasks get over-decomposed, adding coordination overhead without benefit.
  5. Python-only validation — PostToolUse validators run Ruff/Pyright. Non-Python projects get no auto-validation benefit.
04

Workflow

Barkain Claude Code Workflow Orchestration — Workflow

Two-Stage Execution Pipeline

Stage 0: Planning (native plan mode)

Main agent → /workflow-orchestrator:delegate <task>
             → EnterPlanMode
             → Routing check (write detection → breadth → fully-specified → multi-phase)
             → Decompose into atomic phases
             → Dependency analysis (sequential vs. parallel)
             → Keyword-based agent assignment
             → Wave scheduling (parallel groups)
             → TaskCreate entries with metadata
             → Write approved_execution_plan.json
             → ExitPlanMode (requires user approval)

Stage 1: Execution

Subagent mode (default): Spawn isolated Agent instances per wave
                          Each returns DONE|{path}
                          Consolidate results per wave
                          Trigger verification via SubagentStop hook

Team mode (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1):
                          TeamCreate once
                          Agent(team_name=...) per phase (concurrent)
                          Teammates use SendMessage for coordination
                          Self-coordinating via shared task lists

Routing Decision Table

Pattern Route
Breadth + Write (same op × many items) DIRECT EXECUTION (skip plan mode)
Fully-specified sequential (all steps explicit) DIRECT SEQUENTIAL EXECUTION (skip plan mode)
Multi-phase workflow (needs design/decomposition) Plan mode → Stage 1
Read-only breadth Parallel Explore agents
Single simple task General-purpose agent

Phase/Artifact Map

Phase Artifact
Plan mode Task graph in Tasks API + .claude/state/approved_execution_plan.json
Wave execution Agent output files in $CLAUDE_SCRATCHPAD_DIR/
Verification task-completion-verifier agent output

Approval Gates

Gate Where Type
ExitPlanMode After Stage 0 Native Claude Code ExitPlanMode (user approves)
Delegation bypass Per tool use Adaptive nudge (not a hard gate)
06

Memory Context

Barkain Claude Code Workflow Orchestration — Memory & Context

State Storage

Type: File-based + Claude Code Tasks API
Persistence: Session (Tasks API) + Project (approved_execution_plan.json)

State Files

Path Content
.claude/state/approved_execution_plan.json Approved task graph survives context compaction
$CLAUDE_SCRATCHPAD_DIR/<run-id>/batch*.md Agent output files (session-isolated, no permission prompts)

Tasks API Integration

The system uses Claude Code's native Tasks API (TaskCreate, TaskUpdate, TaskGet, TaskList) to track task state:

  • Tasks have structured metadata: wave assignments, phase IDs, agent assignments, dependencies
  • CLAUDE_CODE_ENABLE_TASKS=true (default)
  • CLAUDE_CODE_TASK_LIST_ID for sharing task lists across sessions

Context Compaction Handling

.claude/state/approved_execution_plan.json is written just before ExitPlanMode. If the session compacts or the user approves with "clear context and bypass permissions", the plan is recovered by reading this file. The delegate.md command has an explicit re-invocation guard for this case:

## RE-INVOCATION GUARD (READ FIRST)
...if you arrived here via a "PLAN ALREADY APPROVED" continuation message from the Stop hook, the plan is already approved. **Do NOT call EnterPlanMode. Do NOT re-enter Stage 0.**

Lean Session Injection

  • SessionStart hook injects a stub orchestrator (~1.1KB) on startup
  • Full orchestrator (~7.5KB) loaded on-demand on first delegation
  • Token savings: ~6.6K tokens per session

Agent Output Isolation

All agent outputs go to $CLAUDE_SCRATCHPAD_DIR — a session-isolated directory that doesn't trigger Claude Code permission prompts. Agents never write directly to project files.

07

Orchestration

Barkain Claude Code Workflow Orchestration — Orchestration

Multi-Agent Pattern

Hierarchical with parallel fan-out — The main orchestrator decomposes into a wave-scheduled DAG, then spawns agents per wave in parallel.

Two modes:

  1. Subagent mode (default): Isolated Agent instances per wave, each returning DONE|{path}
  2. Team mode (experimental): TeamCreate + Agent(team_name=...) per phase, SendMessage for peer communication

Mode selection rule: "If TeamCreate is in available tools → team mode. Otherwise → subagent mode." Tool availability is the only signal.

Enforcement Mechanism

Hook-based delegation enforcement — unique in this corpus:

  • Every tool use triggers require_delegation.py via PreToolUse hook
  • If the main agent uses tools directly (bypassing delegation), the hook emits escalating stderr reminders
  • Counter: turn 1 = silent, turn 2 = hint, turn 3+ = strong reminder with explanation
  • Counter resets on each user turn; zeros when /workflow-orchestrator:delegate runs
  • /workflow-orchestrator:bypass for emergency access without restarting

Subagents are immune — the hook checks if the caller is a subagent and skips enforcement for them.

Task Graph Validation

  • validate_task_graph_compliance.py — Validates Agent/Task invocations against the active task graph plan
  • validate_task_graph_depth.py — Enforces minimum depth-3 decomposition for atomic tasks

Auto-Validators

PostToolUse on Edit|Write|MultiEdit → python_posttooluse_hook.py:

  • Ruff linting (configurable: CHECK_RUFF=0 to disable)
  • Pyright type-checking (configurable: CHECK_PYRIGHT=0 to disable)
  • CLAUDE_SKIP_PYTHON_VALIDATION=1 to skip all Python validation

Isolation Mechanism

$CLAUDE_SCRATCHPAD_DIR for agent outputs (session-isolated directory). No git worktrees used for agent isolation.

Execution Mode

Interactive-loop (with plan mode approval gate at Stage 0/Stage 1 boundary)

Concurrent Agents

CLAUDE_MAX_CONCURRENT=8 (default 8 parallel agents per batch)

08

Ui Cli Surface

Barkain Claude Code Workflow Orchestration — UI, CLI & Surface

CLI Binary

None. No dedicated CLI binary. The framework is a Claude Code plugin — users interact via Claude Code's native interface.

Local UI

None — no web dashboard, no TUI. Optional status line can be enabled in Claude Code's interface via /workflow-orchestrator:add-statusline.

Claude Code-Native Features

The plugin leverages several Claude Code-specific features:

  • Native plan mode (EnterPlanMode/ExitPlanMode) for Stage 0/Stage 1 boundary
  • Tasks API (TaskCreate, TaskUpdate, TaskList, TaskGet) for structured task tracking
  • Agent Teams (TeamCreate, Agent(team_name=...), SendMessage) in experimental mode
  • $CLAUDE_SCRATCHPAD_DIR for session-isolated scratchpad output
  • Plugin marketplace for installation

Output Style

The plugin ships a technical-adaptive output style:

  • Located in output-styles/ directory
  • Configured via outputStyle in Claude Code project/user settings
  • Optimized for workflow orchestration output

Session Start Display

On startup:

  • Stub orchestrator prompt injected (~1.1KB)
  • Optional token-efficient CLI guide
  • Full orchestrator loaded on-demand on first delegation invocation

Debugging

DEBUG_DELEGATION_HOOK=1  # Enable hook debug logging
DELEGATION_HOOK_DISABLE=1  # Emergency bypass (disable enforcement)

Observability

Agent outputs in $CLAUDE_SCRATCHPAD_DIR/ provide per-agent artifacts. Task tracking via Tasks API provides structured state. No external log format beyond these.

Related frameworks

same archetype · same primary tool · same memory type

Claude-Flow / Ruflo ★ 55k

Eliminates single-agent context limits and sequential bottlenecks by orchestrating fault-tolerant swarms of specialized AI agents…

Hermes Agent (NousResearch) ★ 168k

Self-improving personal AI agent with closed learning loop, 7 terminal backends, and messaging gateway — not tied to any AI…

OpenCode ★ 165k

Terminal-first AI coding agent with multi-model routing, native desktop app, and a typed .opencode/ configuration system for…

OpenHands ★ 75k

Open-source AI software development platform (open-source Devin alternative) with Docker sandbox isolation, 77.6% SWE-bench…

DeerFlow ★ 70k

Long-horizon superagent that researches, codes, and creates by orchestrating parallel sub-agents with isolated contexts in Docker…

oh-my-openagent (omo) ★ 60k

Multi-provider AI agent orchestration for OpenCode: escape vendor lock-in by routing Sisyphus (Claude/Kimi/GLM) and Hephaestus…