SuperAPI AI Directory

orchestrate

General & other

View repository

Updated 10-16 01:16

About this skill

Multi-Agent Orchestrate v3.4.0

Path resolution (required reading)

This Skill uses shared tools. At runtime, you must first resolve the resource root directory, then use full paths.

Get the Base directory from the command-message header, for example:

Base directory for this skill: /path/to/.../skills/orchestrate

Two installation forms are supported:

  • Plugin install:repo-level shared/ is located at the plugin root.
  • npx skills add:generated _shared/、_scripts/ is located within this skill directory.
if [ -d "$BASE_DIR/_shared" ]; then
  SHARED_DIR="$BASE_DIR/_shared"
  SCRIPTS_DIR="$BASE_DIR/_scripts"
else
  PLUGIN_ROOT="${BASE_DIR%/skills/orchestrate}"
  SHARED_DIR="$PLUGIN_ROOT/shared"
  SCRIPTS_DIR="$PLUGIN_ROOT/scripts"
fi

"$SHARED_DIR/tools/workflow-init.sh" init "$WORKFLOW_ID" orchestrate "需求摘要"

Important: Do not use ./shared/tools/..., because the working directory is the user's project, not the skill/plugin directory.


Pre-checks (important)

Before starting the workflow, check whether the project has a standardized execution mechanism configured:

# 檢查 settings.local.json 是否包含必要的 hooks
cat .claude/settings.local.json 2>/dev/null | grep -q "PostToolUse" && echo "✓ Hooks configured" || echo "✗ Hooks not configured"

If Hooks are not configured, display the following prompt:

⚠️ 專案尚未配置 workflow 規範執行機制。

建議執行 `/setup-workflow` 啟用以下功能:
  • Task 完成後自動 commit(保存進度)
  • 自動運行測試驗證
  • Memory 變更追蹤

執行 `/setup-workflow` 一鍵完成配置。

If the user chooses to continue: execution can continue, but there will be no automatic commit or verification functionality.


Requirements input → 6-phase chain → quality gate → intelligent fallback → delivery complete

Usage

/orchestrate [需求描述]
/orchestrate 建立用戶認證系統,支援 JWT 和 OAuth2

Flags:

  • --profile <mode> - Execution mode:default(default) | express(fast) | quality(highest quality)
  • --start-from STAGE - Start from the specified phase
  • --skip STAGE - Skip the specified phase
  • --quick - Fast mode (equivalent to --profile express)
  • --deep - Deep mode (equivalent to --profile quality)

Workflow phases

RESEARCH → PLAN → TASKS → IMPLEMENT → REVIEW → VERIFY
                                        ↑__________↓
                                      智慧回退機制
Phase Input Output Gate score
RESEARCH Requirements synthesis.md ≥70
PLAN Research report implementation-plan.md ≥75
TASKS Implementation plan tasks.yaml ≥80
IMPLEMENT Task list Code ≥80
REVIEW Code review-summary.md ≥75
VERIFY Review report Verification result ≥85

Execution flow

Phase 0: 初始化工作流
    ├── 生成 workflow-id
    ├── **【必要】執行 workflow-init.sh 初始化通訊環境**
    │   └── Bash: "$SHARED_DIR/tools/workflow-init.sh" init <workflow-id> orchestrate "<需求摘要>"
    │   └── 這會創建 .claude/workflow/current.json(Hooks 依賴此檔案)
    ├── 載入執行模式配置
    │   └── 讀取 $SHARED_DIR/config/execution-profiles.yaml
    │   └── 套用視角數和模型配置
    ├── 建立報告目錄
    └── 記錄開始時間
    ↓
For each stage in [RESEARCH, PLAN, TASKS, IMPLEMENT, REVIEW, VERIFY]:
    ↓
    Phase 1: 執行階段
    ├── 呼叫對應 skill
    └── 等待完成
    ↓
    Phase 2: 早期終止檢查
    ├── 滿足條件?→ 可跳過後續步驟
    └── 不滿足 → 繼續
    ↓
    Phase 3: 品質閘門
    ├── 通過 → 下一階段
    └── 失敗 → 智慧回退
    ↓
End for
    ↓
Phase 4: 完成
    ├── 生成報告
    ├── 更新 Memory
    └── 驗證變更已 commit(見下方 Fallback)

Phase 4 Fallback: Manual Commit

If the automatic checkpoint commit is not triggered (for example, hooks are not configured), execute manually:

# 檢查是否有未 commit 的變更
git status

# 如果有變更,手動 commit
git add -A
git commit -m "chore(workflow): complete {workflow-id}"

Automatic Commit trigger timing:

  • Write synthesis.md → RESEARCH complete
  • Write implementation-plan.md → PLAN complete
  • Write tasks.yaml → TASKS complete
  • Write summary.md → IMPLEMENT complete
  • Write review-summary.md → REVIEW complete
  • Write verify-summary.md → VERIFY complete

Intelligent fallback mechanism

Determine the fallback target based on the iteration count:

Iteration Fallback target Reason
1-2 IMPLEMENT May be an implementation issue
3 TASKS May be a task decomposition issue
4 PLAN May be a design issue
5+ HUMAN Exceeds automatic repair capability

Loop detection:

  • Same error twice → escalate the fallback level
  • Oscillation between phases → pause and analyze the root cause
  • Total iterations > 10 → force stop

→ Configuration:shared/quality/rollback-strategy.yaml

Partial Completion handling

When the workflow is interrupted or a phase fails, automatically save progress so it can be resumed.

Automatically save progress

After each phase completes, immediately save progress to .claude/workflow/{id}/recovery/progress.yaml:

workflow_id: "orchestrate_20260206_123456_abc123"
status: "interrupted"  # completed | interrupted | failed
current_stage: "IMPLEMENT"
completed_stages:
  - stage: RESEARCH
    output: ".claude/memory/research/{topic-id}/synthesis.md"
    score: 82
    timestamp: "2026-02-06T12:35:00Z"
  - stage: PLAN
    output: ".claude/memory/plans/{feature-id}/implementation-plan.md"
    score: 78
    timestamp: "2026-02-06T12:40:00Z"
  - stage: TASKS
    output: ".claude/memory/tasks/{plan-id}/tasks.yaml"
    score: 85
    timestamp: "2026-02-06T12:45:00Z"
failed_stage:
  stage: IMPLEMENT
  error: "Tests failed after 3 retries"
  last_checkpoint: "task-3-of-8"
  timestamp: "2026-02-06T13:00:00Z"

Resume execution

/orchestrate --resume {workflow-id}
# 或
/orchestrate --resume  # 自動找到最近中斷的工作流

Resume flow:

  1. Read progress.yaml to confirm the interruption point
  2. Verify that the output of completed stages is still valid (files exist + git status clean)
  3. Resume execution from the interrupted stage/task
  4. If the output of a completed stage is corrupted, roll back to that stage and re-execute

Partial completion notification

Output on interruption:

⚠️ 工作流部分完成 (3/6 階段)
✅ RESEARCH → PLAN → TASKS
❌ IMPLEMENT(失敗:Tests failed after 3 retries)
⏸️ REVIEW → VERIFY(未執行)

進度已保存至:.claude/workflow/{id}/recovery/progress.yaml
恢復命令:/orchestrate --resume {id}

Difference from smart rollback

Scenario Mechanism Description
Quality gate failure Smart rollback Automatically roll back to the appropriate stage and retry (up to 5 times)
Rollback count exceeded Partial completion Save progress, wait for manual intervention, then --resume
Context Limit Partial completion Save progress, in a new session --resume
External error (network/permissions) Partial completion Save progress, after fixing the issue --resume
Session crash Partial completion Rely on git checkpoint,--resume recover from the last commit

Early termination

Stage Condition Action
RESEARCH consensus ≥ 0.9 Skip conflict resolution
PLAN risk < 0.2 Fast mode
REVIEW No BLOCKER/HIGH Pass directly
VERIFY pass_rate ≥ 0.98 Releasable

→ Configuration:shared/config/early-termination.yaml

Report generation

Automatically generated after completion:

  • dashboard.md - Overview
  • timeline.md - Timeline
  • quality-report.md - Quality report
  • decisions.md - Decision log

→ Tools:shared/tools/generate-report.sh

Output structure

.claude/memory/workflows/[workflow-id]/
├── dashboard.md        # 總覽報告
├── timeline.md         # 時間線
├── decisions.md        # 決策記錄
├── quality-report.md   # 品質報告
├── stages/             # 各階段報告
├── agents/             # Agent 記錄
└── exports/            # 匯出格式

Shared modules

Module Purpose
quality/gates.yaml Quality gate
quality/rollback-strategy.yaml Smart rollback
config/early-termination.yaml Early termination
config/execution-profiles.yaml Execution mode
config/context-freshness.yaml Context freshness
tools/generate-report.sh Report generation
tools/workflow-init.sh Workflow initialization

[Important] Initialization steps

Before executing any stage,you mustfirst initialize the workflow environment:

# 0. 從 command-message header 取得 Base directory,計算 Plugin Root
# 例如:Base directory: /path/.../2.4.2/skills/orchestrate
# SHARED_DIR 是 repo-level shared 或本 skill 內 generated _shared

# 1. 生成 workflow ID(格式:orchestrate_YYYYMMDD_HHMMSS_xxxx)
WORKFLOW_ID="orchestrate_$(date +%Y%m%d_%H%M%S)_$(openssl rand -hex 4)"

# 2. 執行初始化(創建 current.json,讓 Hooks 能記錄活動)
# 使用完整路徑,不要用 ./shared/...
"$SHARED_DIR/tools/workflow-init.sh" init "$WORKFLOW_ID" orchestrate "需求摘要"

Why is this important?

  • Hooks (log-tool-pre.sh, log-tool-post.sh, log-agent-lifecycle.sh) depend on .claude/workflow/current.json
  • Without this file, all Agent activity will not be recorded
  • This will cause /status and the statusline to fail to display the correct workflow status

File-Based Handoff Protocol (v3.3 core mechanism)

The fundamental solution to Context Limit: Use the file system as "external memory" between Agents.

→ Full description:shared/coordination/file-based-handoff.md

Why does Context Limit occur?

傳統方式:
  Agent A 完成 → 15K tokens 回傳 Orchestrator
  Agent B 完成 → 15K tokens 回傳
  Agent C 完成 → 15K tokens 回傳
  Agent D 完成 → 15K tokens 回傳
  ─────────────────────────────────
  總計:60K+ tokens → 爆炸 💥

New approach

File-Based Handoff:
  Agent A 完成 → 寫入檔案 → 回傳 "完成,見 path/a.md" (~100 tokens)
  Agent B 完成 → 寫入檔案 → 回傳 "完成,見 path/b.md" (~100 tokens)
  ...
  ─────────────────────────────────
  Orchestrator 只累積:~400 tokens ✅
  完整結果在:檔案系統 + Git

Execution rules

  1. Use background execution for large tasks:

    Task({
      description: "複雜任務",
      prompt: "...結果寫入 {path},只回覆確認",
      run_in_background: true  // 關鍵!
    })
    
  2. Agent outputs to a file:

    • Full report → .claude/memory/{type}/{id}/result.md
    • Return to Orchestrator → only say "Done, results are in {path}"
  3. Git Checkpoint:

    • Each batch of tasks completed → git commit
    • Even if the session crashes, results are preserved
  4. The next stage reads the file:

    • The Orchestrator tells the next Agent the file path
    • Agent reads it itself using Read

Context usage comparison

Method 4 large Agents Orchestrator Context
Traditional Return everything ~60K tokens (dangerous)
File-Based Return only paths ~10K tokens (safe)

Intelligent parallel decision-making (new in v3.2)

When the user requests multiple tasks to be executed simultaneously, the Orchestrator intelligently decides the execution strategy.

→ Configuration:shared/config/parallel-execution.yaml

Parallelism control

Task complexity Maximum parallelism Basis for judgment
Simple 4 Single module, < 3 files, tests already exist
Medium 2 Cross-module, 3-10 files, new tests needed
Complex 1 Architecture changes, > 10 files, multiple stages

Decision flow

用戶請求多任務
    ↓
┌─────────────────────────────────────┐
│  1. 分析每個任務的複雜度              │
│  2. 偵測任務間的依賴關係              │
│  3. 估算 context 消耗                │
└─────────────────────────────────────┘
    ↓
┌─────────────────────────────────────┐
│  決策:                              │
│  - 無依賴 + 簡單 → 全部並行           │
│  - 有依賴 → 拓撲排序後分批            │
│  - 複雜任務 → 順序執行                │
│  - context 緊張 → 降低並行度          │
└─────────────────────────────────────┘
    ↓
執行並監控

Dependency detection

Automatically detect the following dependencies:

  • File overlap: Tasks that modify the same file cannot run in parallel
  • Module dependency: Module A imports Module B, so B must be completed first
  • Test dependency: Tests depend on the implementation, so the implementation must be completed first

Example

Input: Execute 4 Phase 1 tasks simultaneously

Analysis:

  • Complexity: All are complex tasks
  • Dependencies: No direct dependencies
  • Estimated context: High

Decision:

批次 1: [智能待辦 P1, 動態 Skill P1]  → 並行
  ↓ 完成後 /compact
批次 2: [記憶演化 P1, 分布式記憶 P1]  → 並行

Reason: 2 tasks per batch to avoid context explosion.

Context Limit handling (new in v3.2)

→ Guidelines:shared/coordination/context-limit-handler.md

Prevention mechanisms

  1. Monitoring thresholds:

    • < 50%: Normal parallelism
    • 50-70%: Reduce to 2 parallel
    • 70-85%: Sequential execution
    • > 85%: Pause and compress
  2. Real-time compression:

    • After an Agent completes, keep only the summary in context
    • Save the full output to a file
  3. Background execution:

    • Use for large tasks run_in_background: true
    • Does not consume the orchestrator's context

Handling when it occurs

When you see "Context limit reached":

┌─────────────────────────────────────┐
│  1. 記錄哪些 Agent 已完成            │
│  2. 記錄哪些 Agent 還在運行          │
│  3. 開新 session                    │
│  4. 執行完成狀態檢查:               │
│     - git status                    │
│     - pnpm typecheck                │
│     - pnpm test <paths>             │
│  5. 從中斷點繼續,降低並行度          │
└─────────────────────────────────────┘

Progress saving

Automatically save to .claude/workflow/{id}/recovery/progress.yaml:

tasks:
  - id: "task-1"
    status: "completed"
    commit: "abc123"
  - id: "task-2"
    status: "in_progress"
    last_checkpoint: "80%"

Recovery command template

我需要繼續之前因 context limit 中斷的工作。

**已完成**:
- [x] 任務 A(已 commit)
- [x] 任務 B(未 commit 但完整)

**未完成**:
- [ ] 任務 C(進度 80%)

請:
1. 先 commit 任務 B
2. 驗證並繼續任務 C
3. **一個一個執行,不要並行**

New Flags (v3.2)

  • --max-parallel <n> - Limit the maximum parallelism (default: automatically determined)
  • --sequential - Force sequential execution of all tasks
  • --save-progress - Save a progress file after each task completes
  • --resume <progress-file> - Resume execution from a progress file