SuperAPI AI Directory

ccw loop-b

Coding & development

View repository

Updated 10-15 17:32

About this skill

CCW Loop-B - Hybrid Orchestrator Pattern

Iterative development workflow with a coordinator + dedicated workers. Supports three execution modes (Interactive / Auto / Parallel). Each action is executed by an independent worker agent, while the coordinator handles scheduling, state management, and result aggregation.

Architecture Overview

+------------------------------------------------------------+
|                    Main Coordinator                         |
|  职责: 状态管理 + worker 调度 + 结果汇聚 + 用户交互        |
+------------------------------------------------------------+
          |                    |                    |
          v                    v                    v
+----------------+   +----------------+   +----------------+
| Worker-Develop |   | Worker-Debug   |   | Worker-Validate|
| 专注: 代码实现 |   | 专注: 问题诊断 |   | 专注: 测试验证 |
+----------------+   +----------------+   +----------------+
          |                    |                    |
          v                    v                    v
   .workers/              .workers/             .workers/
   develop.output.json    debug.output.json     validate.output.json

Subagent API

API Purpose Notes
spawn_agent({ message }) Create worker, returns agent_id First message loads the role
wait({ ids, timeout_ms }) Wait for result The only entry point for getting results, not close
send_input({ id, message }) Continue interaction/follow-up interrupt=true use with caution
close_agent({ id }) Close and reclaim Irreversible; close only after confirming no further interaction is needed

Key Design Principles

  1. Keep the coordinator lightweight: only does scheduling and state management; leave concrete work to workers
  2. Single responsibility for workers: each worker focuses on one domain (develop/debug/validate)
  3. Passing role paths: Workers read the role file themselves; the main flow does not pass the content
  4. Delay close_agent: close the worker only after confirming no further interaction is needed
  5. Two-phase workflow: for complex tasks, clarify first and then execute to reduce rework
  6. Batch wait optimization: in parallel mode, use wait({ ids: [...] }) for batch waiting
  7. Standardized results: Worker output follows the unified WORKER_RESULT format
  8. Flexible mode switching: choose interactive/auto/parallel based on task complexity

Arguments

Arg Required Description
TASK One of TASK or --loop-id Task description (for new loop)
--loop-id One of TASK or --loop-id Existing loop ID to continue
--mode No interactive (default) / auto / parallel

Execution Modes

Mode: Interactive (default)

The coordinator displays a menu, the user selects an action, and the corresponding worker is spawned to execute it.

Coordinator -> Show menu -> User selects -> spawn worker -> wait -> Display result -> Loop

Mode: Auto

Execute automatically in a preset order; after a worker completes, the coordinator decides the next step.

Init -> Develop -> [if issues] Debug -> Validate -> [if fail] Loop back -> Complete

Mode: Parallel

Spawn multiple workers in parallel, aggregate results with batch wait, and the coordinator makes an overall decision.

Coordinator -> spawn [develop, debug, validate] in parallel -> wait({ ids: all }) -> Merge -> Decide

Execution Flow

Input Parsing:
   └─ Parse arguments (TASK | --loop-id + --mode)
   └─ Convert to structured context (loopId, state, mode)

Phase 1: Session Initialization
   └─ Ref: phases/01-session-init.md
      ├─ Create new loop OR resume existing loop
      ├─ Initialize state file and directory structure
      └─ Output: loopId, state, progressDir, mode

Phase 2: Orchestration Loop
   └─ Ref: phases/02-orchestration-loop.md
      ├─ Mode dispatch: interactive / auto / parallel
      ├─ Worker spawn with structured prompt (Goal/Scope/Context/Deliverables)
      ├─ Wait + timeout handling + result parsing
      ├─ State update per iteration
      └─ close_agent on loop exit

Phase Reference Documents (read on-demand when phase executes):

Phase Document Purpose
1 phases/01-session-init.md Argument parsing, state creation/resume, directory init
2 phases/02-orchestration-loop.md 3-mode orchestration, worker spawn, batch wait, result merge

Data Flow

User Input (TASK | --loop-id + --mode)
    ↓
[Parse Arguments]
    ↓ loopId, state, mode

Phase 1: Session Initialization
    ↓ loopId, state (initialized/resumed), progressDir

Phase 2: Orchestration Loop
    ↓
    ┌─── Interactive Mode ──────────────────────────────────┐
    │ showMenu → user selects → spawn worker → wait →       │
    │ parseResult → updateState → close worker → loop       │
    └───────────────────────────────────────────────────────┘
    ┌─── Auto Mode ─────────────────────────────────────────┐
    │ selectNext → spawn worker → wait → parseResult →      │
    │ updateState → close worker → [loop_back?] → next      │
    └───────────────────────────────────────────────────────┘
    ┌─── Parallel Mode ─────────────────────────────────────┐
    │ spawn [develop, debug, validate] → batch wait →       │
    │ mergeOutputs → coordinator decides → close all        │
    └───────────────────────────────────────────────────────┘
    ↓
return finalState

Session Structure

{projectRoot}/.workflow/.loop/
├── {loopId}.json                    # Master state (API + Skill shared)
├── {loopId}.workers/                # Worker structured outputs
│   ├── init.output.json
│   ├── develop.output.json
│   ├── debug.output.json
│   ├── validate.output.json
│   └── complete.output.json
└── {loopId}.progress/               # Human-readable progress
    ├── develop.md
    ├── debug.md
    ├── validate.md
    └── summary.md

State Management

Master state file: {projectRoot}/.workflow/.loop/{loopId}.json

{
  "loop_id": "loop-b-20260122-abc123",
  "title": "Task title",
  "description": "Full task description",
  "mode": "interactive | auto | parallel",
  "status": "running | paused | completed | failed",
  "current_iteration": 0,
  "max_iterations": 10,
  "created_at": "ISO8601",
  "updated_at": "ISO8601",

  "skill_state": {
    "phase": "init | develop | debug | validate | complete",
    "action_index": 0,
    "workers_completed": [],
    "parallel_results": null,
    "pending_tasks": [],
    "completed_tasks": [],
    "findings": []
  }
}

Control Signal Checking: the coordinator checks before each worker spawn state.status:

  • running → continue
  • paused → exit gracefully, wait for resume
  • failed → terminate

Recovery: If state corrupted, rebuild from .progress/ markdown files and .workers/*.output.json.

Worker Catalog

Worker Role File Purpose Output Files
init ccw-loop-b-init.md Session initialization, task parsing init.output.json
develop ccw-loop-b-develop.md Code implementation, refactoring develop.output.json, develop.md
debug ccw-loop-b-debug.md Problem diagnosis, hypothesis validation debug.output.json, debug.md
validate ccw-loop-b-validate.md Test execution, coverage validate.output.json, validate.md
complete ccw-loop-b-complete.md Summary and wrap-up complete.output.json, summary.md

Worker Dependencies

Worker Depends On Leads To
init - develop (auto) / menu (interactive)
develop init validate / debug
debug init develop / validate
validate develop or debug complete / develop (if fail)
complete - Terminal

Worker Sequences

Simple Task (Auto):     init → develop → validate → complete
Complex Task (Auto):    init → develop → validate (fail) → debug → develop → validate → complete
Bug Fix (Auto):         init → debug → develop → validate → complete
Analysis (Parallel):    init → [develop ‖ debug ‖ validate] → complete
Interactive:            init → menu → user selects → worker → menu → ...

Worker Prompt Protocol

Spawn Message Structure (§7.1)

function buildWorkerPrompt(action, loopId, state) {
  return `
## TASK ASSIGNMENT

### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: ~/.codex/agents/ccw-loop-b-${action}.md (MUST read first)
2. Read: ${projectRoot}/.workflow/project-tech.json
3. Read: ${projectRoot}/.workflow/project-guidelines.json

---

Goal: ${goalForAction(action, state)}

Scope:
- 可做: ${allowedScope(action)}
- 不可做: ${forbiddenScope(action)}
- 目录限制: ${directoryScope(action, state)}

Context:
- Loop ID: ${loopId}
- State: ${projectRoot}/.workflow/.loop/${loopId}.json
- Output: ${projectRoot}/.workflow/.loop/${loopId}.workers/${action}.output.json
- Progress: ${projectRoot}/.workflow/.loop/${loopId}.progress/${action}.md

Deliverables:
- 按 WORKER_RESULT 格式输出
- 写入 output.json 和 progress.md

Quality bar:
- ${qualityCriteria(action)}
`
}

Key: the role file is read by the worker itself; the main flow only passes the path. Do not embed role content.

Worker Output Format (WORKER_RESULT)

WORKER_RESULT:
- action: {action_name}
- status: success | failed | needs_input
- summary: <brief summary>
- files_changed: [list]
- next_suggestion: <suggested next action>
- loop_back_to: <action name if needs loop back, or null>

DETAILED_OUTPUT:
<action-specific structured output>

Two-Phase Clarification (§5.2)

When a worker encounters ambiguous requirements, it uses the two-phase mode:

阶段 1: Worker 输出 CLARIFICATION_NEEDED + Open questions
阶段 2: 协调器收集用户回答 → send_input → Worker 继续执行
// 解析 worker 是否需要澄清
if (output.includes('CLARIFICATION_NEEDED')) {
  const userAnswers = await collectUserAnswers(output)
  send_input({
    id: workerId,
    message: `## CLARIFICATION ANSWERS\n${userAnswers}\n\n## CONTINUE EXECUTION`
  })
  const finalResult = wait({ ids: [workerId], timeout_ms: 600000 })
}

Parallel Split Strategy (§6)

Strategy 1: Split by responsibility domain (recommended)

Worker Responsibility Deliverables Prohibited actions
develop Locate entry points, call chains, implementation approach List of change points Do not test
debug Problem diagnosis, risk assessment Problem list + fix suggestions Do not write code
validate Test strategy, coverage analysis Test results + quality report Do not change the implementation

Strategy 2: Split by module domain

Worker 1: src/auth/**     → 认证模块变更
Worker 2: src/api/**      → API 层变更
Worker 3: src/database/** → 数据层变更

Splitting principles

  1. File isolation: avoid multiple workers modifying the same file at the same time
  2. Single responsibility: each worker does only one thing
  3. Clear boundaries: if out of scope, use CLARIFICATION_NEEDED to request confirmation
  4. Minimal context: pass only the minimal information needed to complete the task

Result Merge (Parallel Mode)

function mergeWorkerOutputs(outputs) {
  return {
    develop: parseWorkerResult(outputs.develop),
    debug: parseWorkerResult(outputs.debug),
    validate: parseWorkerResult(outputs.validate),
    conflicts: detectConflicts(outputs),  // 检查 worker 间建议冲突
    merged_at: getUtc8ISOString()
  }
}

Conflict detection: When multiple workers suggest modifying the same file, the coordinator marks a conflict, and the user decides.

TodoWrite Pattern

Phase-Level Tracking (Attached)

[
  {"content": "Phase 1: Session Initialization", "status": "completed"},
  {"content": "Phase 2: Orchestration Loop (auto mode)", "status": "in_progress"},
  {"content": "  → Worker: init", "status": "completed"},
  {"content": "  → Worker: develop (task 2/5)", "status": "in_progress"},
  {"content": "  → Worker: validate", "status": "pending"},
  {"content": "  → Worker: complete", "status": "pending"}
]

Parallel Mode Tracking

[
  {"content": "Phase 1: Session Initialization", "status": "completed"},
  {"content": "Phase 2: Parallel Analysis", "status": "in_progress"},
  {"content": "  → Worker: develop (parallel)", "status": "in_progress"},
  {"content": "  → Worker: debug (parallel)", "status": "in_progress"},
  {"content": "  → Worker: validate (parallel)", "status": "in_progress"},
  {"content": "  → Merge results", "status": "pending"}
]

Core Rules

  1. Start Immediately: First action is TodoWrite initialization, then Phase 1 execution
  2. Progressive Phase Loading: Read phase docs ONLY when that phase is about to execute
  3. Parse Every Output: Extract WORKER_RESULT from worker output for next decision
  4. Worker lifecycle: spawn → wait → [send_input if needed] → close, workers are not retained long-term
  5. Result persistence: Worker output is written to {projectRoot}/.workflow/.loop/{loopId}.workers/
  6. State synchronization: Update master state each time a worker completes
  7. Timeout handling: send_input requests converge; if it times out again, continue with existing results
  8. DO NOT STOP: Continuous execution until completed, paused, or max iterations

Error Handling

Error Type Recovery
Worker timeout send_input requests converge → if it times out again, skip
Worker failed Log error, coordinator decides whether to retry
Batch wait partial timeout Continue with completed results
State corrupted Rebuild from the progress file and worker output
Conflicting worker results Mark conflict, user decides
Max iterations reached Generate a summary, record incomplete items

Coordinator Checklist

Before Each Phase

  • Read phase reference document
  • Check current state and control signals
  • Update TodoWrite with phase tasks

After Each Worker

  • Parse WORKER_RESULT from output
  • Persist output to .workers/{action}.output.json
  • Update master state file
  • close_agent (confirm interaction is no longer needed)
  • Determine next action (continue / loop back / complete)

Reference Documents

Document Purpose
workers/ Worker definition (init, develop, debug, validate, complete)

Usage

# Interactive mode (default)
/ccw-loop-b TASK="Implement user authentication"

# Auto mode
/ccw-loop-b --mode=auto TASK="Fix login bug"

# Parallel analysis mode
/ccw-loop-b --mode=parallel TASK="Analyze and improve payment module"

# Resume existing loop
/ccw-loop-b --loop-id=loop-b-20260122-abc123