team-lifecycle

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Team Lifecycle Orchestrator

团队生命周期编排器

Full lifecycle team orchestration for specification, implementation, and testing workflows. The orchestrator drives a multi-agent pipeline through five phases: requirement clarification, session initialization, task chain creation, pipeline coordination (spawn/wait/close loop), and completion reporting.
Key design principles:
  • Inline discuss subagent: Produce roles (analyst, writer, reviewer) call a discuss subagent internally rather than spawning a dedicated discussion agent. This halves spec pipeline beats from 12 to 6.
  • Shared explore cache: All agents share a centralized
    explorations/
    directory with
    cache-index.json
    , eliminating duplicate codebase exploration.
  • Fast-advance spawning: After an agent completes, the orchestrator immediately spawns the next agent in a linear chain without waiting for a full coordination cycle.
  • Consensus severity routing: Discussion verdicts route through HIGH/MEDIUM/LOW severity tiers, each with distinct orchestrator behavior (revision, warn-proceed, or pass-through).
  • Beat model: Each pipeline step is a single beat -- spawn agent, wait for result, process output, spawn next. The orchestrator processes one beat per cycle, then yields.

覆盖需求规格定义、实现、测试工作流的全生命周期团队编排能力。编排器驱动多Agent流水线走过五个阶段:需求澄清、会话初始化、任务链创建、流水线协调(生成/等待/关闭循环)以及完成报告。
核心设计原则:
  • 内联讨论子Agent:产出角色(分析师、文档工程师、评审员)会在内部调用讨论子Agent,而非生成独立的讨论Agent。这将规格定义流水线的节拍数从12减半到6。
  • 共享探索缓存:所有Agent共享集中式
    explorations/
    目录和
    cache-index.json
    ,消除重复的代码库探索工作。
  • 快速推进生成:某个Agent完成任务后,编排器会立即生成线性链路中的下一个Agent,无需等待完整的协调周期。
  • 共识严重性路由:讨论结论会按照高/中/低严重等级进行路由,每个等级对应不同的编排器行为(修订、警告后继续、直接通过)。
  • 节拍模型:每个流水线步骤对应一个独立节拍:生成Agent、等待结果、处理输出、生成下一个Agent。编排器每个周期处理一个节拍,之后让出资源。

Architecture

架构

+-------------------------------------------------------------+
|  Team Lifecycle Orchestrator                                  |
|  Phase 1 -> Phase 2 -> Phase 3 -> Phase 4 -> Phase 5         |
|  Require    Init       Dispatch   Coordinate   Report         |
+----------+------------------------------------------------+--+
           |
     +-----+------+----------+-----------+-----------+
     v            v          v           v           v
+---------+ +---------+ +---------+ +---------+ +---------+
| Phase 1 | | Phase 2 | | Phase 3 | | Phase 4 | | Phase 5 |
| Require | | Init    | | Dispatch| | Coord   | | Report  |
+---------+ +---------+ +---------+ +---------+ +---------+
     |            |          |          |||          |
  params       session     tasks     agents      summary
                                    /  |  \
                              spawn  wait  close
                              /        |        \
                       +------+   +-------+   +--------+
                       |agent1|   |agent2 |   |agent N |
                       +------+   +-------+   +--------+
                          |           |            |
                     (may call discuss/explore subagents internally)
Phase 4 Beat Cycle (single beat):
  event (phase advance / user resume)
      |
      v
  [Orchestrator]
      +-- read state file
      +-- find ready tasks (pending + all blockers completed)
      +-- spawn agent(s) for ready task(s)
      +-- wait(agent_ids, timeout)
      +-- process results (consensus routing, artifacts)
      +-- update state file
      +-- close completed agents
      +-- fast-advance: immediately spawn next if linear successor
      +-- yield (wait for next event or user command)

+-------------------------------------------------------------+
|  Team Lifecycle Orchestrator                                  |
|  Phase 1 -> Phase 2 -> Phase 3 -> Phase 4 -> Phase 5         |
|  Require    Init       Dispatch   Coordinate   Report         |
+----------+------------------------------------------------+--+
           |
     +-----+------+----------+-----------+-----------+
     v            v          v           v           v
+---------+ +---------+ +---------+ +---------+ +---------+
| Phase 1 | | Phase 2 | | Phase 3 | | Phase 4 | | Phase 5 |
| Require | | Init    | | Dispatch| | Coord   | | Report  |
+---------+ +---------+ +---------+ +---------+ +---------+
     |            |          |          |||          |
  params       session     tasks     agents      summary
                                    /  |  \
                              spawn  wait  close
                              /        |        \
                       +------+   +-------+   +--------+
                       |agent1|   |agent2 |   |agent N |
                       +------+   +-------+   +--------+
                          |           |            |
                     (may call discuss/explore subagents internally)
第四阶段节拍周期(单节拍)
  event (phase advance / user resume)
      |
      v
  [Orchestrator]
      +-- read state file
      +-- find ready tasks (pending + all blockers completed)
      +-- spawn agent(s) for ready task(s)
      +-- wait(agent_ids, timeout)
      +-- process results (consensus routing, artifacts)
      +-- update state file
      +-- close completed agents
      +-- fast-advance: immediately spawn next if linear successor
      +-- yield (wait for next event or user command)

Agent Registry

Agent注册中心

AgentRole FileResponsibilityPattern
analyst~/.codex/agents/analyst.mdSeed analysis, context gathering, DISCUSS-0012.8 Inline Subagent
writer~/.codex/agents/writer.mdDocument generation, DISCUSS-002 to DISCUSS-0052.8 Inline Subagent
planner~/.codex/agents/planner.mdMulti-angle exploration, plan generation2.9 Cached Exploration
executor~/.codex/agents/executor.mdCode implementation2.1 Standard
tester~/.codex/agents/tester.mdTest-fix cycles2.3 Deep Interaction
reviewer~/.codex/agents/reviewer.mdCode review + spec quality, DISCUSS-0062.8 Inline Subagent
architect~/.codex/agents/architect.mdArchitecture consulting (on-demand)2.1 Standard
fe-developer~/.codex/agents/fe-developer.mdFrontend implementation2.1 Standard
fe-qa~/.codex/agents/fe-qa.mdFrontend QA, GC loop2.3 Deep Interaction
All agent role files MUST be deployed to
~/.codex/agents/
before use. Pattern 2.8 = agent internally spawns discuss subagent for multi-perspective critique. Pattern 2.9 = agent uses shared explore cache before work. Pattern 2.3 = orchestrator may use send_input for iterative correction loops.

Agent角色文件职责模式
analyst~/.codex/agents/analyst.md初始分析、上下文收集、DISCUSS-0012.8 内联子Agent
writer~/.codex/agents/writer.md文档生成、DISCUSS-002 到 DISCUSS-0052.8 内联子Agent
planner~/.codex/agents/planner.md多维度探索、方案生成2.9 缓存探索
executor~/.codex/agents/executor.md代码实现2.1 标准
tester~/.codex/agents/tester.md测试-修复循环2.3 深度交互
reviewer~/.codex/agents/reviewer.md代码评审 + 规格质量校验、DISCUSS-0062.8 内联子Agent
architect~/.codex/agents/architect.md架构咨询(按需调用)2.1 标准
fe-developer~/.codex/agents/fe-developer.md前端实现2.1 标准
fe-qa~/.codex/agents/fe-qa.md前端QA、GC循环2.3 深度交互
所有Agent角色文件使用前必须部署到
~/.codex/agents/
目录下。 模式2.8 = Agent内部生成讨论子Agent完成多视角评审。 模式2.9 = Agent工作前会使用共享探索缓存。 模式2.3 = 编排器可使用send_input实现迭代修正循环。

Subagent Registry

子Agent注册中心

SubagentAgent FileCallable ByPurpose
discuss~/.codex/agents/discuss-agent.mdanalyst, writer, reviewerMulti-perspective critique via CLI tools
explore~/.codex/agents/explore-agent.mdanalyst, planner, any agentCodebase exploration with shared cache
Subagents are spawned by agents themselves (not by the orchestrator). An agent reads the subagent spec, spawns it inline via
spawn_agent
, waits for the result, and closes it. The orchestrator never directly manages subagent lifecycle.

子AgentAgent文件可调用方用途
discuss~/.codex/agents/discuss-agent.mdanalyst, writer, reviewer通过CLI工具完成多视角评审
explore~/.codex/agents/explore-agent.mdanalyst, planner, 任意Agent带共享缓存的代码库探索
子Agent由Agent自身生成(而非编排器)。Agent读取子Agent规格,通过
spawn_agent
内联生成,等待结果后关闭。编排器从不直接管理子Agent的生命周期。

Fast-Advance Spawning

快速推进生成机制

After
wait()
returns a completed agent result, the orchestrator checks whether the next pipeline step is a simple linear successor (exactly one task becomes ready, no parallel window, no checkpoint).
Decision table:
ConditionAction
1 ready task, simple linear successor, no checkpointImmediately
spawn_agent
for next task (fast-advance)
Multiple ready tasks (parallel window)Spawn all ready tasks in batch, then
wait
on all
No ready tasks, other agents still runningYield, wait for those agents to complete
No ready tasks, nothing runningPipeline complete, proceed to Phase 5
Checkpoint task completed (e.g., QUALITY-001)Pause, output checkpoint message, wait for user
Fast-advance failure recovery: When the orchestrator detects that a fast-advanced agent has failed (wait returns error or timeout with no result):
  1. Record failure in state file
  2. Mark that task as "pending" again in state
  3. Spawn a fresh agent for the same task
  4. If the same task fails 3+ times, pause pipeline and report to user

wait()
返回已完成的Agent结果后,编排器会检查下一个流水线步骤是否是简单线性后继(恰好有一个任务就绪,无并行窗口,无检查点)。
决策表
条件操作
1个就绪任务,简单线性后继,无检查点立即为下一个任务执行
spawn_agent
(快速推进)
多个就绪任务(并行窗口)批量生成所有就绪任务对应的Agent,然后统一等待结果
无就绪任务,仍有其他Agent在运行让出资源,等待这些Agent完成
无就绪任务,无运行中Agent流水线完成,进入第五阶段
检查点任务完成(如QUALITY-001)暂停,输出检查点消息,等待用户操作
快速推进故障恢复: 当编排器检测到快速推进的Agent运行失败(等待返回错误或超时无结果):
  1. 在状态文件中记录失败信息
  2. 在状态中将对应任务重新标记为「待处理」
  3. 为该任务生成一个新的Agent
  4. 如果同一任务失败超过3次,暂停流水线并向用户报告

Consensus Severity Routing

共识严重性路由

When a produce agent (analyst, writer, reviewer) reports a discuss result, the orchestrator parses the verdict from the agent output.
Output format from agents (written to their artifact, also in wait() result):
DISCUSS_RESULT:
- verdict: <consensus_reached | consensus_blocked>
- severity: <HIGH | MEDIUM | LOW>
- average_rating: <N>/5
- divergences: <summary>
- action_items: <list>
- recommendation: <revise | proceed-with-caution | escalate>
- discussion_path: <path-to-discussion-record>
Routing table:
VerdictSeverityOrchestrator Action
consensus_reached-Proceed normally, fast-advance to next task
consensus_blockedLOWTreat as reached with notes, proceed normally
consensus_blockedMEDIUMLog warning to
wisdom/issues.md
, include divergence in next task context, proceed
consensus_blockedHIGHCreate revision task (see below) OR pause for user
consensus_blockedHIGH (DISCUSS-006)Always pause for user decision (final sign-off gate)
Revision task creation (HIGH severity, not DISCUSS-006):
javascript
// Add revision entry to state file
const revisionTask = {
  id: "<original-task-id>-R1",
  owner: "<same-agent-role>",
  blocked_by: [],
  description: "Revision of <original-task-id>: address consensus-blocked divergences.\n"
    + "Session: <session-dir>\n"
    + "Original artifact: <artifact-path>\n"
    + "Divergences: <divergence-details>\n"
    + "Action items: <action-items-from-discuss>\n"
    + "InlineDiscuss: <same-round-id>",
  status: "pending",
  is_revision: true
}

// Max 1 revision per task. If already revised once, pause for user.
if (stateHasRevision(originalTaskId)) {
  // Pause pipeline, ask user
} else {
  // Insert revision task into state, spawn agent
}

当产出类Agent(analyst、writer、reviewer)返回讨论结果时,编排器会从Agent输出中解析出结论。
Agent输出格式(写入其产出物,同时包含在wait()结果中):
DISCUSS_RESULT:
- verdict: <consensus_reached | consensus_blocked>
- severity: <HIGH | MEDIUM | LOW>
- average_rating: <N>/5
- divergences: <summary>
- action_items: <list>
- recommendation: <revise | proceed-with-caution | escalate>
- discussion_path: <path-to-discussion-record>
路由表
结论严重等级编排器操作
达成共识-正常推进,快速进入下一个任务
共识阻塞视为附带备注的达成共识,正常推进
共识阻塞
wisdom/issues.md
中记录警告,将分歧内容加入下一个任务的上下文,继续推进
共识阻塞创建修订任务(见下文)或者暂停等待用户处理
共识阻塞高(DISCUSS-006)始终暂停等待用户决策(最终签署关卡)
修订任务创建(高严重等级,非DISCUSS-006场景):
javascript
// Add revision entry to state file
const revisionTask = {
  id: "<original-task-id>-R1",
  owner: "<same-agent-role>",
  blocked_by: [],
  description: "Revision of <original-task-id>: address consensus-blocked divergences.\n"
    + "Session: <session-dir>\n"
    + "Original artifact: <artifact-path>\n"
    + "Divergences: <divergence-details>\n"
    + "Action items: <action-items-from-discuss>\n"
    + "InlineDiscuss: <same-round-id>",
  status: "pending",
  is_revision: true
}

// Max 1 revision per task. If already revised once, pause for user.
if (stateHasRevision(originalTaskId)) {
  // Pause pipeline, ask user
} else {
  // Insert revision task into state, spawn agent
}

Phase Execution

阶段执行

PhaseFileSummary
Phase 1phases/01-requirement-clarification.mdParse user input, detect mode, frontend auto-detection, gather parameters
Phase 2phases/02-team-initialization.mdCreate session directory, initialize state file, wisdom, explore cache
Phase 3phases/03-task-chain-creation.mdBuild pipeline task chain based on mode, write to state file
Phase 4phases/04-pipeline-coordination.mdMain spawn/wait/close loop, fast-advance, consensus routing, checkpoints
Phase 5phases/05-completion-report.mdSummarize results, list artifacts, offer next steps
阶段文件概述
阶段1phases/01-requirement-clarification.md解析用户输入、检测模式、前端自动识别、收集参数
阶段2phases/02-team-initialization.md创建会话目录、初始化状态文件、知识库、探索缓存
阶段3phases/03-task-chain-creation.md基于模式构建流水线任务链,写入状态文件
阶段4phases/04-pipeline-coordination.md核心生成/等待/关闭循环、快速推进、共识路由、检查点处理
阶段5phases/05-completion-report.md结果汇总、产出物列表、下一步建议

Phase 0: Session Resume Check (before Phase 1)

阶段0:会话恢复检查(阶段1之前)

Before entering Phase 1, the orchestrator checks for interrupted sessions:
  1. Scan
    .workflow/.team/TLS-*/team-session.json
    for files with
    status: "active"
    or
    status: "paused"
  2. No sessions found -> proceed to Phase 1
  3. Single session found -> resume it (Session Reconciliation below)
  4. Multiple sessions found -> ask user to select
Session Reconciliation (when resuming):
  1. Read state file -> get pipeline state
  2. For each task in state file:
    • If status is "in_progress" but no agent is running -> reset to "pending" (interrupted)
    • If status is "completed" -> verify artifact exists
  3. Rebuild task readiness from reconciled state
  4. Proceed to Phase 4 with reconciled state (spawn ready tasks)

进入阶段1之前,编排器会检查是否存在中断的会话:
  1. 扫描
    .workflow/.team/TLS-*/team-session.json
    ,查找状态为
    active
    paused
    的文件
  2. 未找到会话 -> 进入阶段1
  3. 找到单个会话 -> 恢复该会话(见下文会话对账)
  4. 找到多个会话 -> 提示用户选择
会话对账(恢复会话时执行):
  1. 读取状态文件 -> 获取流水线状态
  2. 遍历状态文件中的每个任务:
    • 如果状态为「进行中」但无对应运行中Agent -> 重置为「待处理」(被中断)
    • 如果状态为「已完成」 -> 验证产出物是否存在
  3. 基于对账后的状态重新计算任务就绪情况
  4. 使用对账后的状态进入阶段4(生成就绪任务的Agent)

Pipeline Definitions

流水线定义

Spec-only (6 beats)

仅规格定义(6个节拍)

RESEARCH-001(+D1) -> DRAFT-001(+D2) -> DRAFT-002(+D3) -> DRAFT-003(+D4) -> DRAFT-004(+D5) -> QUALITY-001(+D6)
Each task includes inline discuss.
(+DN)
= inline discuss round N executed by the agent internally.
RESEARCH-001(+D1) -> DRAFT-001(+D2) -> DRAFT-002(+D3) -> DRAFT-003(+D4) -> DRAFT-004(+D5) -> QUALITY-001(+D6)
每个任务都包含内联讨论。
(+DN)
= Agent内部执行的第N轮内联讨论。

Impl-only (3 beats with parallel window)

仅实现(3个节拍,含并行窗口)

PLAN-001 -> IMPL-001 -> TEST-001 || REVIEW-001
TEST-001 and REVIEW-001 run in parallel after IMPL-001 completes.
PLAN-001 -> IMPL-001 -> TEST-001 || REVIEW-001
IMPL-001完成后,TEST-001和REVIEW-001并行运行。

Full-lifecycle (9 beats)

全生命周期(9个节拍)

[Spec pipeline: RESEARCH-001 -> DRAFT-001 -> ... -> QUALITY-001]
    |
    CHECKPOINT: pause for user confirmation
    |
PLAN-001(blockedBy: QUALITY-001) -> IMPL-001 -> TEST-001 || REVIEW-001
[Spec pipeline: RESEARCH-001 -> DRAFT-001 -> ... -> QUALITY-001]
    |
    CHECKPOINT: pause for user confirmation
    |
PLAN-001(blockedBy: QUALITY-001) -> IMPL-001 -> TEST-001 || REVIEW-001

FE-only (3 beats)

仅前端(3个节拍)

PLAN-001 -> DEV-FE-001 -> QA-FE-001
GC loop: if QA-FE verdict is NEEDS_FIX, dynamically create DEV-FE-002 -> QA-FE-002 (max 2 rounds).
PLAN-001 -> DEV-FE-001 -> QA-FE-001
GC循环:如果QA-FE结论为NEEDS_FIX,动态创建DEV-FE-002 -> QA-FE-002(最多2轮)。

Fullstack (4 beats with dual parallel)

全栈(4个节拍,双并行窗口)

PLAN-001 -> IMPL-001 || DEV-FE-001 -> TEST-001 || QA-FE-001 -> REVIEW-001
REVIEW-001 is blocked by both TEST-001 and QA-FE-001.
PLAN-001 -> IMPL-001 || DEV-FE-001 -> TEST-001 || QA-FE-001 -> REVIEW-001
REVIEW-001等待TEST-001和QA-FE-001都完成后才会执行。

Full-lifecycle-FE (12 tasks)

全生命周期含前端(12个任务)

[Spec pipeline] -> PLAN-001 -> IMPL-001 || DEV-FE-001 -> TEST-001 || QA-FE-001 -> REVIEW-001
PLAN-001 blockedBy QUALITY-001. Spec-to-impl checkpoint applies.

[Spec pipeline] -> PLAN-001 -> IMPL-001 || DEV-FE-001 -> TEST-001 || QA-FE-001 -> REVIEW-001
PLAN-001依赖QUALITY-001完成。适用规格到实现的检查点规则。

Task Metadata Registry

任务元数据注册中心

Task IDAgentPhaseDependenciesDescriptionInline Discuss
RESEARCH-001analystspec(none)Seed analysis and context gatheringDISCUSS-001
DRAFT-001writerspecRESEARCH-001Generate Product BriefDISCUSS-002
DRAFT-002writerspecDRAFT-001Generate Requirements/PRDDISCUSS-003
DRAFT-003writerspecDRAFT-002Generate Architecture DocumentDISCUSS-004
DRAFT-004writerspecDRAFT-003Generate Epics and StoriesDISCUSS-005
QUALITY-001reviewerspecDRAFT-0045-dimension spec quality + sign-offDISCUSS-006
PLAN-001plannerimpl(none or QUALITY-001)Multi-angle exploration and planning-
IMPL-001executorimplPLAN-001Code implementation-
TEST-001testerimplIMPL-001Test-fix cycles-
REVIEW-001reviewerimplIMPL-0014-dimension code review-
DEV-FE-001fe-developerimplPLAN-001Frontend implementation-
QA-FE-001fe-qaimplDEV-FE-0015-dimension frontend QA-

任务IDAgent阶段依赖描述内联讨论
RESEARCH-001analyst规格定义初始分析和上下文收集DISCUSS-001
DRAFT-001writer规格定义RESEARCH-001生成产品简介DISCUSS-002
DRAFT-002writer规格定义DRAFT-001生成需求/PRDDISCUSS-003
DRAFT-003writer规格定义DRAFT-002生成架构文档DISCUSS-004
DRAFT-004writer规格定义DRAFT-003生成史诗和用户故事DISCUSS-005
QUALITY-001reviewer规格定义DRAFT-0045维度规格质量校验 + 签署DISCUSS-006
PLAN-001planner实现无或QUALITY-001多维度探索和规划-
IMPL-001executor实现PLAN-001代码实现-
TEST-001tester实现IMPL-001测试-修复循环-
REVIEW-001reviewer实现IMPL-0014维度代码评审-
DEV-FE-001fe-developer实现PLAN-001前端实现-
QA-FE-001fe-qa实现DEV-FE-0015维度前端QA-

Cadence Control

节奏控制

Beat Model

节拍模型

Event-driven pipeline. Each beat = orchestrator processes one event -> spawns agent(s) -> waits -> processes result -> yields.
Beat Cycle (single beat)
======================================================================
  Event                 Orchestrator                  Agents
----------------------------------------------------------------------
  advance/resume --> +- read state file ------+
                     |  find ready tasks       |
                     |  spawn agent(s) --------+--> [Agent A] executes
                     |  wait(ids, timeout) ----+--> [Agent B] executes
                     +- process results -------+         |
                     |  update state file      |         |
                     |  close agents           |         |
                     +- yield -----------------+         |
                                                         |
  next beat <--- result from wait() <-------------------+
======================================================================

  Fast-Advance (skips full yield for linear successors)
======================================================================
  [Agent A] completes via wait()
    +- 1 ready task? simple linear successor?
    |   YES -> spawn Agent B immediately, enter wait() again
    |   NO  -> yield, wait for user/event
======================================================================
事件驱动的流水线。每个节拍 = 编排器处理一个事件 -> 生成Agent -> 等待结果 -> 处理输出 -> 让出资源。
Beat Cycle (single beat)
======================================================================
  Event                 Orchestrator                  Agents
----------------------------------------------------------------------
  advance/resume --> +- read state file ------+
                     |  find ready tasks       |
                     |  spawn agent(s) --------+--> [Agent A] executes
                     |  wait(ids, timeout) ----+--> [Agent B] executes
                     +- process results -------+         |
                     |  update state file      |         |
                     |  close agents           |         |
                     +- yield -----------------+         |
                                                         |
  next beat <--- result from wait() <-------------------+
======================================================================

  Fast-Advance (skips full yield for linear successors)
======================================================================
  [Agent A] completes via wait()
    +- 1 ready task? simple linear successor?
    |   YES -> spawn Agent B immediately, enter wait() again
    |   NO  -> yield, wait for user/event
======================================================================

Pipeline Beat View

流水线节拍视图

Spec-only (6 beats, was 12 in v3)
-------------------------------------------------------
Beat  1         2         3         4         5         6
      |         |         |         |         |         |
    R1+D1 --> W1+D2 --> W2+D3 --> W3+D4 --> W4+D5 --> Q1+D6
    ^                                                     ^
  pipeline                                            sign-off
   start                                               pause

R=RESEARCH  W=DRAFT(writer)  Q=QUALITY  D=DISCUSS(inline)

Impl-only (3 beats, with parallel window)
-------------------------------------------------------
Beat  1         2              3
      |         |         +----+----+
      PLAN --> IMPL --> TEST || REVIEW    <-- parallel window
                         +----+----+
                           pipeline
                            done

Full-lifecycle (9 beats)
-------------------------------------------------------
Beat 1-6: [Spec pipeline as above]
                                    |
Beat 6 (Q1+D6 done):      CHECKPOINT -- user confirms then resume
                                    |
Beat 7      8           9
 PLAN --> IMPL --> TEST || REVIEW

Fullstack (with dual parallel windows)
-------------------------------------------------------
Beat  1              2                    3                4
      |         +----+----+         +----+----+           |
      PLAN --> IMPL || DEV-FE --> TEST || QA-FE -->  REVIEW
              ^                ^                   ^
         parallel 1       parallel 2          sync barrier
Spec-only (6 beats, was 12 in v3)
-------------------------------------------------------
Beat  1         2         3         4         5         6
      |         |         |         |         |         |
    R1+D1 --> W1+D2 --> W2+D3 --> W3+D4 --> W4+D5 --> Q1+D6
    ^                                                     ^
  pipeline                                            sign-off
   start                                               pause

R=RESEARCH  W=DRAFT(writer)  Q=QUALITY  D=DISCUSS(inline)

Impl-only (3 beats, with parallel window)
-------------------------------------------------------
Beat  1         2              3
      |         |         +----+----+
      PLAN --> IMPL --> TEST || REVIEW    <-- parallel window
                         +----+----+
                           pipeline
                            done

Full-lifecycle (9 beats)
-------------------------------------------------------
Beat 1-6: [Spec pipeline as above]
                                    |
Beat 6 (Q1+D6 done):      CHECKPOINT -- user confirms then resume
                                    |
Beat 7      8           9
 PLAN --> IMPL --> TEST || REVIEW

Fullstack (with dual parallel windows)
-------------------------------------------------------
Beat  1              2                    3                4
      |         +----+----+         +----+----+           |
      PLAN --> IMPL || DEV-FE --> TEST || QA-FE -->  REVIEW
              ^                ^                   ^
         parallel 1       parallel 2          sync barrier

Checkpoints

检查点

TriggerPositionBehavior
Spec-to-impl transitionQUALITY-001 completedPause, output "SPEC PHASE COMPLETE", wait for user
GC loop max reachedQA-FE max 2 roundsStop iteration, report current QA state
Pipeline stallNo ready + no runningCheck for missing tasks, report to user
DISCUSS-006 HIGH severityFinal sign-offAlways pause for user decision
触发条件位置行为
规格到实现的过渡QUALITY-001完成暂停,输出「SPEC阶段完成」,等待用户操作
GC循环达到最大次数QA-FE最多2轮停止迭代,报告当前QA状态
流水线停滞无就绪任务 + 无运行中任务检查是否缺失任务,向用户报告
DISCUSS-006高严重等级最终签署环节始终暂停等待用户决策

Stall Detection

停滞检测

CheckConditionResolution
Agent unresponsivewait() timeout on active agentClose agent, reset task to pending, respawn
Pipeline deadlockNo ready + no running + has pendingInspect blocked_by chains, report blockage to user
GC loop exceededDEV-FE / QA-FE iteration > 2 roundsTerminate loop, output latest QA report
Fast-advance orphanTask is "in_progress" in state but agent closedReset to pending, respawn

检查项条件解决方案
Agent无响应运行中Agent的wait()超时关闭Agent,将任务重置为待处理,重新生成
流水线死锁无就绪任务 + 无运行中任务 + 有待处理任务检查阻塞依赖链,向用户报告阻塞详情
GC循环超限DEV-FE/QA-FE迭代超过2轮终止循环,输出最新QA报告
快速推进孤儿任务状态中标记为「进行中」但Agent已关闭重置为待处理,重新生成

Agent Spawn Template

Agent生成模板

When the orchestrator spawns an agent for a pipeline task, it uses this template:
javascript
const agentId = spawn_agent({
  message: `
编排器为流水线任务生成Agent时,使用以下模板:
javascript
const agentId = spawn_agent({
  message: `

TASK ASSIGNMENT

TASK ASSIGNMENT

MANDATORY FIRST STEPS (Agent Execute)

MANDATORY FIRST STEPS (Agent Execute)

  1. Read role definition: ~/.codex/agents/<agent-role>.md (MUST read first)
  2. Read session state: <session-dir>/team-session.json
  3. Read wisdom files: <session-dir>/wisdom/*.md (if exists)

  1. Read role definition: ~/.codex/agents/<agent-role>.md (MUST read first)
  2. Read session state: <session-dir>/team-session.json
  3. Read wisdom files: <session-dir>/wisdom/*.md (if exists)

Session

Session

Session directory: <session-dir> Task ID: <task-id> Pipeline mode: <mode>
Session directory: <session-dir> Task ID: <task-id> Pipeline mode: <mode>

Scope

Scope

<scope-description>
<scope-description>

Task

Task

<task-description>
<task-description>

InlineDiscuss

InlineDiscuss

<discuss-round-id or "none">
<discuss-round-id or "none">

Dependencies

Dependencies

Completed predecessors: <list of completed task IDs and their artifact paths>
Completed predecessors: <list of completed task IDs and their artifact paths>

Constraints

Constraints

  • Only process <PREFIX>-* tasks
  • All output prefixed with [<agent-role>] tag
  • Write artifacts to <session-dir>/<artifact-subdir>/
  • Before each major output, read wisdom files for cross-task knowledge
  • After task completion, write discoveries to <session-dir>/wisdom/
  • If InlineDiscuss is set, call discuss subagent after primary artifact creation
  • Only process <PREFIX>-* tasks
  • All output prefixed with [<agent-role>] tag
  • Write artifacts to <session-dir>/<artifact-subdir>/
  • Before each major output, read wisdom files for cross-task knowledge
  • After task completion, write discoveries to <session-dir>/wisdom/
  • If InlineDiscuss is set, call discuss subagent after primary artifact creation

Completion Protocol

Completion Protocol

When work is complete, output EXACTLY:
TASK_COMPLETE:
  • task_id: <task-id>
  • status: <success | failed>
  • artifact: <path-to-primary-artifact>
  • discuss_verdict: <consensus_reached | consensus_blocked | none>
  • discuss_severity: <HIGH | MEDIUM | LOW | none>
  • summary: <one-line summary> ` })

---
When work is complete, output EXACTLY:
TASK_COMPLETE:
  • task_id: <task-id>
  • status: <success | failed>
  • artifact: <path-to-primary-artifact>
  • discuss_verdict: <consensus_reached | consensus_blocked | none>
  • discuss_severity: <HIGH | MEDIUM | LOW | none>
  • summary: <one-line summary> ` })

---

Session Directory

会话目录

.workflow/.team/TLS-<slug>-<date>/
+-- team-session.json           # Pipeline state (replaces TaskCreate/TaskList)
+-- spec/                       # Spec artifacts
|   +-- spec-config.json
|   +-- discovery-context.json
|   +-- product-brief.md
|   +-- requirements/
|   +-- architecture/
|   +-- epics/
|   +-- readiness-report.md
|   +-- spec-summary.md
+-- discussions/                # Discussion records (written by discuss subagent)
+-- plan/                       # Plan artifacts
|   +-- plan.json
|   +-- tasks/                  # Detailed task specs
+-- explorations/               # Shared explore cache
|   +-- cache-index.json        # { angle -> file_path }
|   +-- explore-<angle>.json
+-- architecture/               # Architect assessments + design-tokens.json
+-- analysis/                   # Analyst design-intelligence.json (UI mode)
+-- qa/                         # QA audit reports
+-- wisdom/                     # Cross-task knowledge accumulation
|   +-- learnings.md            # Patterns and insights
|   +-- decisions.md            # Architecture and design decisions
|   +-- conventions.md          # Codebase conventions
|   +-- issues.md               # Known risks and issues
+-- .msg/                       # Message bus (UI integration)
|   +-- meta.json               # Pipeline metadata (stages, roles, team_name)
|   +-- messages.jsonl          # NDJSON event log
+-- shared-memory.json          # Cross-agent state

.workflow/.team/TLS-<slug>-<date>/
+-- team-session.json           # Pipeline state (replaces TaskCreate/TaskList)
+-- spec/                       # Spec artifacts
|   +-- spec-config.json
|   +-- discovery-context.json
|   +-- product-brief.md
|   +-- requirements/
|   +-- architecture/
|   +-- epics/
|   +-- readiness-report.md
|   +-- spec-summary.md
+-- discussions/                # Discussion records (written by discuss subagent)
+-- plan/                       # Plan artifacts
|   +-- plan.json
|   +-- tasks/                  # Detailed task specs
+-- explorations/               # Shared explore cache
|   +-- cache-index.json        # { angle -> file_path }
|   +-- explore-<angle>.json
+-- architecture/               # Architect assessments + design-tokens.json
+-- analysis/                   # Analyst design-intelligence.json (UI mode)
+-- qa/                         # QA audit reports
+-- wisdom/                     # Cross-task knowledge accumulation
|   +-- learnings.md            # Patterns and insights
|   +-- decisions.md            # Architecture and design decisions
|   +-- conventions.md          # Codebase conventions
|   +-- issues.md               # Known risks and issues
+-- .msg/                       # Message bus (UI integration)
|   +-- meta.json               # Pipeline metadata (stages, roles, team_name)
|   +-- messages.jsonl          # NDJSON event log
+-- shared-memory.json          # Cross-agent state

State File Schema (team-session.json)

状态文件Schema(team-session.json)

The state file replaces Claude's TaskCreate/TaskList/TaskGet/TaskUpdate system. The orchestrator owns this file exclusively.
json
{
  "session_id": "TLS-<slug>-<date>",
  "mode": "<spec-only | impl-only | full-lifecycle | fe-only | fullstack | full-lifecycle-fe>",
  "scope": "<project description>",
  "status": "<active | paused | completed>",
  "started_at": "<ISO8601>",
  "updated_at": "<ISO8601>",
  "tasks_total": 0,
  "tasks_completed": 0,
  "pipeline": [
    {
      "id": "RESEARCH-001",
      "owner": "analyst",
      "status": "pending | in_progress | completed | failed",
      "blocked_by": [],
      "description": "...",
      "inline_discuss": "DISCUSS-001",
      "agent_id": null,
      "artifact_path": null,
      "discuss_verdict": null,
      "discuss_severity": null,
      "started_at": null,
      "completed_at": null,
      "revision_of": null,
      "revision_count": 0
    }
  ],
  "active_agents": [],
  "completed_tasks": [],
  "revision_chains": {},
  "wisdom_entries": [],
  "checkpoints_hit": [],
  "gc_loop_count": 0
}

状态文件替代了Claude的TaskCreate/TaskList/TaskGet/TaskUpdate系统,由编排器独占管理。
json
{
  "session_id": "TLS-<slug>-<date>",
  "mode": "<spec-only | impl-only | full-lifecycle | fe-only | fullstack | full-lifecycle-fe>",
  "scope": "<project description>",
  "status": "<active | paused | completed>",
  "started_at": "<ISO8601>",
  "updated_at": "<ISO8601>",
  "tasks_total": 0,
  "tasks_completed": 0,
  "pipeline": [
    {
      "id": "RESEARCH-001",
      "owner": "analyst",
      "status": "pending | in_progress | completed | failed",
      "blocked_by": [],
      "description": "...",
      "inline_discuss": "DISCUSS-001",
      "agent_id": null,
      "artifact_path": null,
      "discuss_verdict": null,
      "discuss_severity": null,
      "started_at": null,
      "completed_at": null,
      "revision_of": null,
      "revision_count": 0
    }
  ],
  "active_agents": [],
  "completed_tasks": [],
  "revision_chains": {},
  "wisdom_entries": [],
  "checkpoints_hit": [],
  "gc_loop_count": 0
}

Message Bus (.msg/)

消息总线(.msg/)

The
.msg/
directory provides pipeline metadata for the frontend UI. This is the same format used by Claude version's
team_msg
tool with
type: "state_update"
.
.msg/
目录为前端UI提供流水线元数据,格式与Claude版本
team_msg
工具使用的
type: "state_update"
格式完全一致。

meta.json

meta.json

Pipeline metadata read by the API for frontend display:
json
{
  "status": "active",
  "pipeline_mode": "<mode>",
  "pipeline_stages": ["role1", "role2", "..."],
  "roles": ["coordinator", "role1", "role2", "..."],
  "team_name": "lifecycle",
  "role_state": {
    "<role>": {
      "status": "completed",
      "task_id": "TASK-ID",
      "_updated_at": "<ISO8601>"
    }
  },
  "updated_at": "<ISO8601>"
}
pipeline_stages by mode:
Modepipeline_stages
spec-only
["analyst", "writer", "reviewer"]
impl-only
["planner", "executor", "tester", "reviewer"]
fe-only
["planner", "fe-developer", "fe-qa"]
fullstack
["planner", "executor", "fe-developer", "tester", "fe-qa", "reviewer"]
full-lifecycle
["analyst", "writer", "planner", "executor", "tester", "reviewer"]
full-lifecycle-fe
["analyst", "writer", "planner", "executor", "fe-developer", "tester", "fe-qa", "reviewer"]
供API读取用于前端展示的流水线元数据:
json
{
  "status": "active",
  "pipeline_mode": "<mode>",
  "pipeline_stages": ["role1", "role2", "..."],
  "roles": ["coordinator", "role1", "role2", "..."],
  "team_name": "lifecycle",
  "role_state": {
    "<role>": {
      "status": "completed",
      "task_id": "TASK-ID",
      "_updated_at": "<ISO8601>"
    }
  },
  "updated_at": "<ISO8601>"
}
不同模式的pipeline_stages
模式pipeline_stages
仅规格定义
["analyst", "writer", "reviewer"]
仅实现
["planner", "executor", "tester", "reviewer"]
仅前端
["planner", "fe-developer", "fe-qa"]
全栈
["planner", "executor", "fe-developer", "tester", "fe-qa", "reviewer"]
全生命周期
["analyst", "writer", "planner", "executor", "tester", "reviewer"]
全生命周期含前端
["analyst", "writer", "planner", "executor", "fe-developer", "tester", "fe-qa", "reviewer"]

messages.jsonl

messages.jsonl

NDJSON event log (one JSON object per line):
json
{"id":"MSG-001","ts":"<ISO8601>","from":"coordinator","to":"coordinator","type":"state_update","summary":"Session initialized","data":{...}}
{"id":"MSG-002","ts":"<ISO8601>","from":"analyst","to":"coordinator","type":"impl_complete","summary":"RESEARCH-001 completed","data":{...}}
Message types:
state_update
,
impl_complete
,
impl_progress
,
test_result
,
review_result
,
error
,
shutdown

NDJSON事件日志(每行一个JSON对象):
json
{"id":"MSG-001","ts":"<ISO8601>","from":"coordinator","to":"coordinator","type":"state_update","summary":"Session initialized","data":{...}}
{"id":"MSG-002","ts":"<ISO8601>","from":"analyst","to":"coordinator","type":"impl_complete","summary":"RESEARCH-001 completed","data":{...}}
消息类型
state_update
,
impl_complete
,
impl_progress
,
test_result
,
review_result
,
error
,
shutdown

Session Resume

会话恢复

When the orchestrator detects an existing active/paused session:
  1. Read
    team-session.json
    from session directory
  2. For each task with status "in_progress":
    • No matching active agent -> task was interrupted -> reset to "pending"
    • Has matching active agent -> verify agent is still alive (attempt wait with 0 timeout)
  3. Reconcile: ensure all expected tasks for the mode exist in state
  4. Create missing tasks with correct blocked_by dependencies
  5. Verify dependency chain integrity (no cycles, no dangling references)
  6. Update state file with reconciled state
  7. Proceed to Phase 4 to spawn ready tasks

当编排器检测到存在活跃/暂停的会话时:
  1. 从会话目录读取
    team-session.json
  2. 遍历所有状态为「进行中」的任务:
    • 无匹配的活跃Agent -> 任务被中断 -> 重置为「待处理」
    • 有匹配的活跃Agent -> 验证Agent仍在运行(尝试0超时等待)
  3. 对账:确保当前模式对应的所有预期任务都存在于状态中
  4. 创建缺失的任务,设置正确的阻塞依赖
  5. 验证依赖链完整性(无循环、无悬垂引用)
  6. 用对账后的状态更新状态文件
  7. 进入阶段4生成就绪任务的Agent

User Commands

用户命令

During pipeline execution, the user may issue commands:
CommandAction
check
/
status
Output execution status graph (read-only, no advancement)
resume
/
continue
Check agent states, advance pipeline
New session requestPhase 0 detects, enters normal Phase 1-5 flow
Status graph output format:
[orchestrator] Pipeline Status
[orchestrator] Mode: <mode> | Progress: <completed>/<total> (<percent>%)

[orchestrator] Execution Graph:
  Spec Phase: (if applicable)
    [V RESEARCH-001(+D1)] -> [V DRAFT-001(+D2)] -> [>>> DRAFT-002(+D3)]
    -> [o DRAFT-003(+D4)] -> [o DRAFT-004(+D5)] -> [o QUALITY-001(+D6)]
  Impl Phase: (if applicable)
    [o PLAN-001]
      +- BE: [o IMPL-001] -> [o TEST-001] -> [o REVIEW-001]
      +- FE: [o DEV-FE-001] -> [o QA-FE-001]

  V=completed  >>>=running  o=pending  .=not created

[orchestrator] Active Agents:
  > <task-id> (<agent-role>) - running <elapsed>

[orchestrator] Ready to spawn: <task-ids>
[orchestrator] Commands: 'resume' to advance | 'check' to refresh

流水线执行过程中,用户可发出以下命令:
命令操作
check
/
status
输出执行状态图(只读,不推进流程)
resume
/
continue
检查Agent状态,推进流水线
新会话请求阶段0检测到后,进入正常的1-5阶段流程
状态图输出格式
[orchestrator] Pipeline Status
[orchestrator] Mode: <mode> | Progress: <completed>/<total> (<percent>%)

[orchestrator] Execution Graph:
  Spec Phase: (if applicable)
    [V RESEARCH-001(+D1)] -> [V DRAFT-001(+D2)] -> [>>> DRAFT-002(+D3)]
    -> [o DRAFT-003(+D4)] -> [o DRAFT-004(+D5)] -> [o QUALITY-001(+D6)]
  Impl Phase: (if applicable)
    [o PLAN-001]
      +- BE: [o IMPL-001] -> [o TEST-001] -> [o REVIEW-001]
      +- FE: [o DEV-FE-001] -> [o QA-FE-001]

  V=completed  >>>=running  o=pending  .=not created

[orchestrator] Active Agents:
  > <task-id> (<agent-role>) - running <elapsed>

[orchestrator] Ready to spawn: <task-ids>
[orchestrator] Commands: 'resume' to advance | 'check' to refresh

Lifecycle Management

生命周期管理

Timeout Protocol

超时协议

PhaseTimeoutOn Timeout
Phase 1 (requirements)None (interactive)N/A
Phase 2 (init)60sFail with error
Phase 3 (dispatch)60sFail with error
Phase 4 per agent15 min (spec agents), 30 min (impl agents)Send convergence request via
send_input
, wait 2 min more, then close
Phase 5 (report)60sOutput partial report
Convergence request (sent via
send_input
on timeout):
javascript
send_input({
  id: <agent-id>,
  message: `
阶段超时时间超时处理
阶段1(需求)无(交互模式)N/A
阶段2(初始化)60秒报错失败
阶段3(分发)60秒报错失败
阶段4单Agent15分钟(规格类Agent),30分钟(实现类Agent)通过
send_input
发送收敛请求,再等待2分钟后关闭
阶段5(报告)60秒输出部分报告
收敛请求(超时时通过
send_input
发送):
javascript
send_input({
  id: <agent-id>,
  message: `

TIMEOUT NOTIFICATION

TIMEOUT NOTIFICATION

Execution timeout reached. Please:
  1. Save all current progress to artifact files
  2. Output TASK_COMPLETE with status: partial
  3. Include summary of completed vs remaining work ` })
undefined
Execution timeout reached. Please:
  1. Save all current progress to artifact files
  2. Output TASK_COMPLETE with status: partial
  3. Include summary of completed vs remaining work ` })
undefined

Cleanup Protocol

清理协议

When the pipeline completes (or is aborted):
javascript
// Close all active agents
for (const agentEntry of state.active_agents) {
  try {
    close_agent({ id: agentEntry.agent_id })
  } catch (e) {
    // Agent already closed, ignore
  }
}

// Update state file
state.status = "completed"  // or "aborted"
state.updated_at = new Date().toISOString()
// Write state file

流水线完成(或被中止)时:
javascript
// Close all active agents
for (const agentEntry of state.active_agents) {
  try {
    close_agent({ id: agentEntry.agent_id })
  } catch (e) {
    // Agent already closed, ignore
  }
}

// Update state file
state.status = "completed"  // or "aborted"
state.updated_at = new Date().toISOString()
// Write state file

Error Handling

错误处理

ScenarioDetectionResolution
Agent timeoutwait() returns timed_outsend_input convergence request, retry wait 2 min, then close + reset task
Agent crash / unexpected closewait() returns error statusReset task to pending, respawn agent (max 3 retries)
3+ failures on same taskRetry count in state filePause pipeline, report to user
Fast-advance orphanTask in_progress but no active agent and > 5 min elapsedReset to pending, respawn
Consensus blocked HIGHDISCUSS_RESULT parsed from agent outputCreate revision task (max 1) or pause
Consensus blocked HIGH on DISCUSS-006Same as above but final sign-off roundAlways pause for user
Revision also blockedRevision task returns blocked HIGHPause pipeline, escalate to user
Session file corruptJSON parse errorAttempt recovery from last known good state, or report error
Pipeline stallNo ready + no running + has pendingInspect blocked_by, report blockage details
Unknown agent output formatTASK_COMPLETE not found in wait resultLog warning, attempt to extract status, mark as partial
Duplicate task in stateTask ID already exists during dispatchSkip creation, log warning
Missing dependencyblocked_by references non-existent taskLog error, halt pipeline

场景检测方式解决方案
Agent超时wait()返回timed_out发送收敛请求,重试等待2分钟,然后关闭+重置任务
Agent崩溃/意外关闭wait()返回错误状态将任务重置为待处理,重新生成Agent(最多重试3次)
同一任务失败超过3次状态文件中的重试计数暂停流水线,向用户报告
快速推进孤儿任务任务标记为进行中但无活跃Agent且已运行超过5分钟重置为待处理,重新生成
共识阻塞高严重等级从Agent输出解析到DISCUSS_RESULT创建修订任务(最多1次)或暂停
DISCUSS-006共识阻塞高严重等级同上但属于最终签署环节始终暂停等待用户处理
修订任务仍阻塞修订任务返回高严重等级阻塞暂停流水线,升级给用户处理
会话文件损坏JSON解析错误尝试从最后已知的正常状态恢复,或报告错误
流水线停滞无就绪任务 + 无运行中任务 + 有待处理任务检查阻塞依赖,报告阻塞详情
未知Agent输出格式wait()结果中未找到TASK_COMPLETE记录警告,尝试提取状态,标记为部分完成
状态中存在重复任务分发阶段发现任务ID已存在跳过创建,记录警告
缺失依赖blocked_by引用不存在的任务记录错误,暂停流水线

Frontend Auto-Detection

前端自动检测

During Phase 1, the orchestrator detects whether frontend work is needed:
SignalDetectionPipeline Upgrade
FE keywords in descriptionMatch: component, page, UI, React, Vue, CSS, HTML, Tailwind, Svelte, Next.js, Nuxt, shadcn, design systemimpl-only -> fe-only or fullstack
BE keywords also presentMatch: API, database, server, endpoint, backend, middlewareimpl-only -> fullstack
FE framework in projectDetect react/vue/svelte/next in package.jsonfull-lifecycle -> full-lifecycle-fe

阶段1执行期间,编排器会检测是否需要前端工作:
信号检测规则流水线升级
描述中存在前端关键词匹配:component, page, UI, React, Vue, CSS, HTML, Tailwind, Svelte, Next.js, Nuxt, shadcn, design system仅实现 -> 仅前端或全栈
同时存在后端关键词匹配:API, database, server, endpoint, backend, middleware仅实现 -> 全栈
项目中存在前端框架检测package.json中存在react/vue/svelte/next全生命周期 -> 全生命周期含前端

Inline Discuss Protocol (for agents)

内联讨论协议(面向Agent)

Produce agents (analyst, writer, reviewer) call the discuss subagent after completing their primary artifact. The protocol is documented here for reference; each agent's role file contains the specific invocation.
Discussion round mapping:
AgentAfter TaskDiscuss RoundPerspectives
analystRESEARCH-001DISCUSS-001product, risk, coverage
writerDRAFT-001DISCUSS-002product, technical, quality, coverage
writerDRAFT-002DISCUSS-003quality, product, coverage
writerDRAFT-003DISCUSS-004technical, risk
writerDRAFT-004DISCUSS-005product, technical, quality, coverage
reviewerQUALITY-001DISCUSS-006all 5 (product, technical, quality, risk, coverage)
Agent-side discuss invocation (inside the agent, not orchestrator):
javascript
// Agent spawns discuss subagent internally
const discussId = spawn_agent({
  message: `
产出类Agent(analyst、writer、reviewer)完成主产出物后会调用讨论子Agent。本协议仅供参考,每个Agent的角色文件包含具体的调用逻辑。
讨论轮次映射
Agent完成任务后讨论轮次评审视角
analystRESEARCH-001DISCUSS-001产品、风险、覆盖度
writerDRAFT-001DISCUSS-002产品、技术、质量、覆盖度
writerDRAFT-002DISCUSS-003质量、产品、覆盖度
writerDRAFT-003DISCUSS-004技术、风险
writerDRAFT-004DISCUSS-005产品、技术、质量、覆盖度
reviewerQUALITY-001DISCUSS-006全部5项(产品、技术、质量、风险、覆盖度)
Agent端讨论调用逻辑(在Agent内部执行,非编排器):
javascript
// Agent spawns discuss subagent internally
const discussId = spawn_agent({
  message: `

MANDATORY FIRST STEPS (Agent Execute)

MANDATORY FIRST STEPS (Agent Execute)

  1. Read agent definition: ~/.codex/agents/discuss-agent.md (MUST read first)

  1. Read agent definition: ~/.codex/agents/discuss-agent.md (MUST read first)

Multi-Perspective Critique: <round-id>

Multi-Perspective Critique: <round-id>

Input

Input

  • Artifact: <artifact-path>
  • Round: <round-id>
  • Perspectives: <perspective-list>
  • Session: <session-dir>
  • Discovery Context: <session-dir>/spec/discovery-context.json
  • Artifact: <artifact-path>
  • Round: <round-id>
  • Perspectives: <perspective-list>
  • Session: <session-dir>
  • Discovery Context: <session-dir>/spec/discovery-context.json

Execution

Execution

Per-perspective CLI analysis -> divergence detection -> consensus determination -> write record.
Per-perspective CLI analysis -> divergence detection -> consensus determination -> write record.

Output

Output

Write discussion record to: <session-dir>/discussions/<round-id>-discussion.md Return verdict summary with: verdict, severity, average_rating, action_items, recommendation. ` })
const discussResult = wait({ ids: [discussId], timeout_ms: 300000 }) close_agent({ id: discussId }) // Agent includes discuss result in its TASK_COMPLETE output

---
Write discussion record to: <session-dir>/discussions/<round-id>-discussion.md Return verdict summary with: verdict, severity, average_rating, action_items, recommendation. ` })
const discussResult = wait({ ids: [discussId], timeout_ms: 300000 }) close_agent({ id: discussId }) // Agent includes discuss result in its TASK_COMPLETE output

---

Shared Explore Protocol (for agents)

共享探索协议(面向Agent)

Any agent needing codebase context calls the explore subagent. Results are cached in
explorations/
.
Agent-side explore invocation (inside the agent, not orchestrator):
javascript
// Agent spawns explore subagent internally
const exploreId = spawn_agent({
  message: `
任何需要代码库上下文的Agent都可以调用探索子Agent,结果缓存到
explorations/
目录。
Agent端探索调用逻辑(在Agent内部执行,非编排器):
javascript
// Agent spawns explore subagent internally
const exploreId = spawn_agent({
  message: `

MANDATORY FIRST STEPS (Agent Execute)

MANDATORY FIRST STEPS (Agent Execute)

  1. Read agent definition: ~/.codex/agents/explore-agent.md (MUST read first)

  1. Read agent definition: ~/.codex/agents/explore-agent.md (MUST read first)

Explore Codebase

Explore Codebase

Query: <query> Focus angle: <angle> Keywords: <keyword-list> Session folder: <session-dir>
Query: <query> Focus angle: <angle> Keywords: <keyword-list> Session folder: <session-dir>

Cache Check

Cache Check

  1. Read <session-dir>/explorations/cache-index.json (if exists)
  2. If matching angle found AND file exists -> return cached result
  3. If not found -> proceed to exploration
  1. Read <session-dir>/explorations/cache-index.json (if exists)
  2. If matching angle found AND file exists -> return cached result
  3. If not found -> proceed to exploration

Output

Output

Write JSON to: <session-dir>/explorations/explore-<angle>.json Update cache-index.json with new entry. Return summary: file count, pattern count, top 5 files, output path. ` })
const exploreResult = wait({ ids: [exploreId], timeout_ms: 300000 }) close_agent({ id: exploreId })

**Cache lookup rules**:

| Condition | Action |
|-----------|--------|
| Exact angle match exists in cache-index.json | Return cached result |
| No match | Execute exploration, cache result |
| Cache file missing but index has entry | Remove stale entry, re-explore |

---
Write JSON to: <session-dir>/explorations/explore-<angle>.json Update cache-index.json with new entry. Return summary: file count, pattern count, top 5 files, output path. ` })
const exploreResult = wait({ ids: [exploreId], timeout_ms: 300000 }) close_agent({ id: exploreId })

**缓存查询规则**:

| 条件 | 操作 |
|-----------|--------|
| cache-index.json中存在精确的角度匹配 | 返回缓存结果 |
| 无匹配 | 执行探索,缓存结果 |
| 索引有对应条目但缓存文件缺失 | 删除过期条目,重新探索 |

---

Wisdom Accumulation

知识沉淀

Cross-task knowledge accumulation. Orchestrator creates
wisdom/
at session init.
Directory:
<session-dir>/wisdom/
+-- learnings.md      # Patterns and insights discovered
+-- decisions.md      # Architecture and design decisions made
+-- conventions.md    # Codebase conventions identified
+-- issues.md         # Known risks and issues flagged
Agent responsibilities:
  • On start: read all wisdom files for cross-task context
  • During work: append discoveries to appropriate wisdom file
  • On complete: include significant findings in TASK_COMPLETE summary

跨任务的知识积累能力。编排器在会话初始化时创建
wisdom/
目录。
目录结构
<session-dir>/wisdom/
+-- learnings.md      # 发现的模式和洞察
+-- decisions.md      # 做出的架构和设计决策
+-- conventions.md    # 识别出的代码库规范
+-- issues.md         # 标记的已知风险和问题
Agent职责
  • 启动时:读取所有知识库文件获取跨任务上下文
  • 工作期间:将发现的内容追加到对应的知识库文件
  • 完成时:在TASK_COMPLETE摘要中包含重要发现

Role Isolation Rules

角色隔离规则

AllowedProhibited
Agent processes only its own prefix tasksProcessing other agents' tasks
Agent communicates results via TASK_COMPLETE outputDirect agent-to-agent communication
Agent calls discuss/explore subagents internallyAgent modifying orchestrator state file
Agent writes artifacts to its designated directoryAgent writing to other agents' directories
Agent reads wisdom files and shared-memory.jsonAgent deleting or overwriting other agents' artifacts
Orchestrator additionally prohibited: directly write/modify code, call implementation tools, execute analysis/test/review work.

允许操作禁止操作
Agent仅处理自身前缀的任务处理其他Agent的任务
Agent通过TASK_COMPLETE输出传递结果Agent之间直接通信
Agent内部调用discuss/explore子AgentAgent修改编排器的状态文件
Agent将产出物写入指定目录Agent写入其他Agent的目录
Agent读取知识库文件和shared-memory.jsonAgent删除或覆盖其他Agent的产出物
编排器额外禁止:直接编写/修改代码、调用实现工具、执行分析/测试/评审工作。

GC Loop (Frontend QA)

GC循环(前端QA)

For FE pipelines, QA-FE may trigger a fix-retest cycle:
Round 1: DEV-FE-001 -> QA-FE-001
  QA-FE verdict: NEEDS_FIX?
    YES -> Round 2: DEV-FE-002(blocked_by: QA-FE-001) -> QA-FE-002(blocked_by: DEV-FE-002)
    QA-FE-002 verdict: NEEDS_FIX?
      YES -> max rounds reached (2), stop loop, report current state
      NO  -> proceed to next pipeline step
    NO -> proceed to next pipeline step
The orchestrator dynamically adds DEV-FE-NNN and QA-FE-NNN tasks to the state file when a GC loop iteration is needed.

前端流水线中,QA-FE可能触发修复-重测循环:
Round 1: DEV-FE-001 -> QA-FE-001
  QA-FE verdict: NEEDS_FIX?
    YES -> Round 2: DEV-FE-002(blocked_by: QA-FE-001) -> QA-FE-002(blocked_by: DEV-FE-002)
    QA-FE-002 verdict: NEEDS_FIX?
      YES -> max rounds reached (2), stop loop, report current state
      NO  -> proceed to next pipeline step
    NO -> proceed to next pipeline step
需要执行GC循环迭代时,编排器会动态向状态文件中添加DEV-FE-NNN和QA-FE-NNN任务。

Mode-to-Pipeline Quick Reference

模式-流水线快速参考

ModeTotal TasksFirst TaskCheckpoint
spec-only6RESEARCH-001None (QUALITY-001 is final)
impl-only4PLAN-001None
fe-only3 (+GC)PLAN-001None
fullstack6PLAN-001None
full-lifecycle10RESEARCH-001After QUALITY-001
full-lifecycle-fe12 (+GC)RESEARCH-001After QUALITY-001

模式总任务数首个任务检查点
仅规格定义6RESEARCH-001无(QUALITY-001是最终步骤)
仅实现4PLAN-001
仅前端3(+GC循环)PLAN-001
全栈6PLAN-001
全生命周期10RESEARCH-001QUALITY-001完成后
全生命周期含前端12(+GC循环)RESEARCH-001QUALITY-001完成后

Shared Spec Resources

共享规格资源

ResourcePath (relative to skill)Usage
Document Standardsspecs/document-standards.mdYAML frontmatter, naming, structure
Quality Gatesspecs/quality-gates.mdPer-phase quality gates
Product Brief Templatetemplates/product-brief.mdDRAFT-001
Requirements Templatetemplates/requirements-prd.mdDRAFT-002
Architecture Templatetemplates/architecture-doc.mdDRAFT-003
Epics Templatetemplates/epics-template.mdDRAFT-004

资源路径(相对于skill)用途
文档标准specs/document-standards.mdYAML frontmatter、命名、结构规范
质量关卡specs/quality-gates.md各阶段质量门限
产品简介模板templates/product-brief.mdDRAFT-001
需求模板templates/requirements-prd.mdDRAFT-002
架构文档模板templates/architecture-doc.mdDRAFT-003
史诗模板templates/epics-template.mdDRAFT-004

Coordinator Role Constraints (Main Agent)

协调者角色约束(主Agent)

CRITICAL: The coordinator (main agent executing this skill) is responsible for orchestration only, NOT implementation.
  1. Coordinator Does NOT Execute Code: The main agent MUST NOT write, modify, or implement any code directly. All implementation work is delegated to spawned team agents. The coordinator only:
    • Spawns agents with task assignments
    • Waits for agent callbacks
    • Merges results and coordinates workflow
    • Manages workflow transitions between phases
  2. Patient Waiting is Mandatory: Agent execution takes significant time (typically 10-30 minutes per phase, sometimes longer). The coordinator MUST:
    • Wait patiently for
      wait()
      calls to complete
    • NOT skip workflow steps due to perceived delays
    • NOT assume agents have failed just because they're taking time
    • Trust the timeout mechanisms defined in the skill
  3. Use send_input for Clarification: When agents need guidance or appear stuck, the coordinator MUST:
    • Use
      send_input()
      to ask questions or provide clarification
    • NOT skip the agent or move to next phase prematurely
    • Give agents opportunity to respond before escalating
    • Example:
      send_input({ id: agent_id, message: "Please provide status update or clarify blockers" })
  4. No Workflow Shortcuts: The coordinator MUST NOT:
    • Skip phases or stages defined in the workflow
    • Bypass required approval or review steps
    • Execute dependent tasks before prerequisites complete
    • Assume task completion without explicit agent callback
    • Make up or fabricate agent results
  5. Respect Long-Running Processes: This is a complex multi-agent workflow that requires patience:
    • Total execution time may range from 30-90 minutes or longer
    • Each phase may take 10-30 minutes depending on complexity
    • The coordinator must remain active and attentive throughout the entire process
    • Do not terminate or skip steps due to time concerns
重要提示:执行本skill的协调者(主Agent)仅负责编排工作,不负责实现。
  1. 协调者不执行代码:主Agent严禁直接编写、修改或实现任何代码,所有实现工作都委托给生成的团队Agent。协调者仅负责:
    • 生成带任务分配的Agent
    • 等待Agent回调
    • 合并结果、协调工作流
    • 管理阶段之间的工作流过渡
  2. 必须耐心等待:Agent执行需要较长时间(通常每个阶段10-30分钟,有时更长)。协调者必须:
    • 耐心等待
      wait()
      调用完成
    • 不得因感知到延迟而跳过工作流步骤
    • 不得仅因Agent运行时间长就假设其失败
    • 信任本skill定义的超时机制
  3. 使用send_input进行澄清:当Agent需要指导或看起来卡住时,协调者必须:
    • 使用
      send_input()
      提问或提供澄清信息
    • 不得跳过该Agent或提前进入下一阶段
    • 在升级问题前给Agent响应的机会
    • 示例:
      send_input({ id: agent_id, message: "Please provide status update or clarify blockers" })
  4. 无工作流捷径:协调者严禁:
    • 跳过工作流定义的阶段或步骤
    • 绕过要求的审批或评审步骤
    • 前置条件未完成就执行依赖任务
    • 未收到Agent明确回调就假设任务完成
    • 编造或虚构Agent结果
  5. 尊重长运行流程:这是一个复杂的多Agent工作流,需要耐心:
    • 总执行时间可能在30-90分钟甚至更长
    • 每个阶段根据复杂度可能需要10-30分钟
    • 协调者必须在整个过程中保持活跃和专注
    • 不得因时间问题终止或跳过步骤