| name | orchestrateX |
| description | Main Agent complete workflow handbook. Contains planning dialogue, Mode A/B/C workflows, core iteration loop, Hybrid Tree routing, requirement change handling, routeX, Start Rule. |
orchestrator Playbook
Positioning: Main Agent's complete workflow handbook. Contains main workflow logic and on-demand trigger modules.
Module Index
| # | Module | Trigger | File Path |
|---|
| 1 | Environment Init + MCP Degradation | First entry to xwhole/xlocal only; xunit skips MCP | modules/01-environment-init.md |
| 2 | Bus Payload Validation | Cross-agent handoff and Main -> coderX/evaluatorX dispatch contracts | modules/02-bus-payload.md |
| 3 | Post-Evaluation Document Update | After evaluatorX returns | modules/03-post-evaluation.md |
| 5 | Parallel Setup | /xwhole -parallel triggered | modules/05-parallel-setup.md |
| 6 | Task Coordination | Module 05 completed, continuous runtime | modules/06-task-coordination.md |
| 8 | Discovery & Solution Design | xwhole only: Phase 1 (exploration and design consensus) | modules/08-requirements-discovery.md |
| — | noiseX (Context Denoising) | xwhole only: auto-invoked at Phase 1→2 transition | skills/noiseX/skill.md |
| 10 | Memory Hygiene | End of planning, before each evaluation, before PASS/FAIL | modules/10-memory-hygiene.md |
Note: Module 00 (Auto-Routing) has been superseded by .claude/skills/routeX/SKILL.md — the consolidated routing specification for the Main Agent. Main Agent always receives an explicit mode parameter (Mode: xwhole/xlocal/xunit) and does NOT perform mode selection itself.
Loading rule (Optimized):
- Session Memory Cache: After first Read, cache module content in session memory (
module_cache). Subsequent accesses read from cache instead of disk.
- Cache Key: Use module file path as cache key.
- Invalidation: Cache persists for entire session. Clear only on new session start.
- Never load all modules at once — still applies, but cached modules are instant access.
Parameter Parsing
Main Agent responsibility: Parse parameters from $ARGUMENTS before workflow execution.
Supported Parameters
| Parameter | Format | Scope | Default | Description |
|---|
-N | -N [number] | xwhole, xlocal | 2 | Maximum evaluation iteration rounds per Child |
-box | -box [name] | xwhole | N/A | Sandbox branch name for isolated execution |
-parallel | -parallel | xwhole | off | Enable Agent Teams parallel execution within Mode A |
-team | -team [name] | xwhole (with -parallel) | workflow-{timestamp} | Agent Team name for parallel workflow |
-prompt | -prompt | xunit | off | Run promptX before coderX; without it, place raw requirement in the Type 0 Dispatch Payload |
Parsing Rules
Step 1: Extract parameters from $ARGUMENTS
Extract sequentially from $ARGUMENTS: command name → optional flags → requirement text.
| Param | Match Rule | Default | Description |
|---|
| mode | Starts with /xwhole, /xlocal, /xunit, /xprompt | — | Command determines mode |
-N | Positive integer (1-10) after -N | 2 | Max evaluation iterations per Child |
-box | Branch name (alphanumeric, hyphens, underscores) after -box | skip | Sandbox branch name |
-parallel | Presence flag | off | Agent Teams parallel mode |
-team | Name after -team | workflow-{timestamp} | Team name for parallel mode |
-prompt | Presence flag | off | xunit only: enable promptX preprocessing |
| requirement | Remaining text after removing above params | — | User requirement |
Examples:
/xwhole -N 5 -box feature-test Add user authentication
→ mode=xwhole, N=5, box="feature-test", parallel=false, requirement="Add user authentication"
/xwhole -parallel -team my-team Implement auth module
→ mode=xwhole, N=2, parallel=true, team="my-team", requirement="Implement auth module"
Step 2: Validate parameters
-N: Must be positive integer (1-10). If invalid or missing, use default 2.
-box: Must be valid branch name (alphanumeric, hyphens, underscores). If empty, skip sandbox.
-parallel: No value needed. Presence flag enables Agent Teams mode within xwhole.
-prompt: No value needed. Only valid for xunit; ignored by xwhole/xlocal.
Step 3: Remember parsed parameters
Store extracted results as session working memory (mode, iteration_limit, sandbox_branch, team_name, is_parallel, requirement). Reference directly in subsequent steps, no re-parsing.
Usage in Workflow
Iteration Limit (-N):
- Applied in Core Iteration Loop (Step 6 of xwhole, Step 5 of xlocal)
- Each Child gets max N rounds of coderX ↔ evaluatorX iteration
- If limit reached and still Needs Fix: stop iteration, report to human
Sandbox Branch (-box):
- Conditional Creation: Only execute sandbox operations when
-box is explicitly provided
- Without
-box: Work directly on current branch, no stash/checkout needed
- With
-box: Execute full sandbox lifecycle (below)
- Sandbox Lifecycle:
- Before workflow:
git stash → record original branch → git checkout -b {sandbox-branch} from main
- After workflow: switch back → attempt fast merge (see below) → restore stash
- Fast Merge Strategy (Optimized):
- Try
git merge --ff-only {sandbox-branch} (fastest, no extra commit)
- If ff-only fails (diverged), try
git merge --squash {sandbox-branch} (single commit)
- If squash fails, fallback to
git merge --no-commit --no-ff {sandbox-branch}
- If merge conflicts: pause, notify user, wait for manual resolution
- Incremental Stash (Optimized):
- Only stash files actually modified:
git stash push -m "workflowX" -- file1 file2 ...
- On restore:
git stash pop (auto-resolves if no conflicts)
Workflow Modes
Mode A: whole workflow
- Scope: Large-scale, high-impact, requiring full planning-evaluation cycle.
- Worktree isolation (auto): coderX and evaluatorX are spawned with
isolation="worktree". Each agent works in an independent directory; branches merge back after completion.
- Sandbox (
-box): When specified, creates a physically isolated sandbox branch. Before: stash, record original branch, create sandbox branch. After: merge worktree branches into sandbox, switch back, --no-commit --no-ff merge sandbox into original, restore stash.
- Entry: Environment init (module 01) -> Phase 1: Discovery & Solution Design (module 08: explore, challenge, propose solutions) -> Hard Gate (AskUserQuestion) -> user clicks "确认生成 PRD" -> noiseX summary (denoise Phase 1 context) -> Phase 2: Document Generation (Hybrid Tree creation) -> Core Iteration Loop
- Iteration limit: Each Child defaults to max 2 rounds (
-N overrides). If limit reached and still failing, stop and report to human.
- abstracterX is only invoked when user explicitly requests summarization.
Mode A-parallel (-parallel)
When -parallel is specified, Mode A uses Agent Teams for parallel execution instead of sequential sub-agent dispatch:
- Prerequisites: Agent Teams enabled (
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1), Claude Code v2.1.32+
- Entry: Same Planning Phase as Mode A -> Parallel setup (module 05) -> Task coordination (module 06)
- Core features:
- Uses Agent Teams instead of sequential sub-agent mode
- Multiple coder-teammate + evaluator-teammate working in parallel
- Each teammate isolated in own worktree (zero file conflicts)
- Dynamic task scheduling based on dependency graph
- Real-time requirement change handling
- Fallback: If Agent Teams unavailable, fall back to sequential Mode A sub-agent mode
- Teammate role definitions:
.claude/agents/coder-teammate.md: Code implementation teammate
.claude/agents/evaluator-teammate.md: Code evaluation teammate
- Detailed flow: See Module 05 and Module 06
Mode B: local workflow
- Scope: Requirements relatively clear, limited to a local part of the project.
- Entry: Environment init (module 01, MCP probe must precede everything) -> PRD detection -> Core Iteration Loop.
- PRD detection (priority order):
- Explicit Hybrid Tree path in
$ARGUMENTS → validate Parent + Child, use directly
- No explicit path → scan
.hybrid/ for existing Hybrid Trees and match the current requirement against Parent title/overview/scope, Parent §7 Child scopes, Child §7 AC, and §8.1 file indexes
- If exactly one related Hybrid Tree matches → reuse and maintain that tree; route to the matching Child, or create a new Child through Requirement Change Handling when no Child scope matches
- If multiple plausible Hybrid Trees match → present candidates with match reasons and ask the user to choose; do not auto-generate a duplicate tree
- If
$ARGUMENTS contains a valid non-Hybrid PRD file path → read PRD, wrap into Hybrid Tree
- No related Hybrid Tree or PRD → auto-generate minimal Hybrid Tree (scan code → build index → decompose AC → write Parent + Child)
- evaluatorX evaluation criteria: Always PRD-based (evaluate against Child Section 7 AC). After reading Evaluation Result, Main Agent copies Fix Instructions into the next Type 0 Dispatch Payload for coderX.
Mode C: unit workflow
- Scope: Minimal tasks: single fix, single file, minimal change.
- Entry: Main Agent builds a Type 0 Dispatch Payload, dispatches Agent(coderX), then reports to user. evaluatorX only invoked when explicitly requested.
- promptX integration: Optional. Only invoke
promptX when the user passes -prompt; then include the structured prompt plus original requirement in the Type 0 Dispatch Payload.
- MCP / knowledge graph: Skipped entirely. xunit must not probe MCP, call
server-memory, read knowledge graph sections, or prepend MCP fallback instructions.
- coderX lightweight mode: Only loads
guideX + razorX, does not load specX, no Bus Payload needed. Receives a Type 0 Dispatch Payload containing the raw requirement by default, or structured prompt only when -prompt is present.
- Execution flow:
- xunit lightweight init: skip Module 01 MCP checks.
- If
-prompt is present, invoke promptX; otherwise skip prompt preprocessing.
- Dispatch Agent(coderX) lightweight mode with a Type 0 Dispatch Payload: "no MCP / no knowledge graph / no Bus Payload".
- Report result and complete the command.
Discovery & Solution Design (Mode A)
Mode A entry: Environment init (module 01) -> Phase 1: Discovery & Solution Design (module 08) -> user confirms -> Phase 2: Document Generation (Hybrid Tree creation) -> Core Iteration Loop
Two-Phase Workflow
Phase 1: Discovery & Solution Design (module 08) — thinking and design stage:
- Autonomous exploration, gap identification, risk surfacing
- Propose 2-3 solutions with trade-offs
- Multi-turn refinement with user
- Output: Design consensus (no Hybrid Tree yet)
- Exit signal: "等待你确认方案后,我会生成 Hybrid Tree 并启动开发流程。"
Phase 2: Document Generation — triggered ONLY by user clicking gate option:
- Hard Gate: User signals intent → MUST invoke AskUserQuestion (see §8.5)
- Only "确认生成 PRD" option proceeds to Phase 2
- Generate Hybrid Tree (Parent + Children) based on Phase 1 consensus
- Write to
.hybrid/[feature]/ directory
- Enter Core Iteration Loop
Core behaviors (Phase 1):
- Invoke the
socratesX skill to drive Socratic clarification — one core question per turn, each with 2-4 options + a recommendation (see module 08 §8.2)
- Meanwhile autonomously search the codebase (Glob/Grep/rg) so questions are grounded in code evidence
- Present findings as "here's what I found" rather than "can you tell me"
- Challenge assumptions based on actual code evidence
- Propose 2-3 solutions with trade-offs derived from exploration
- Iterate with user to refine approach
Phase 1 Clarification (via socratesX)
Phase 1 requirement clarification is driven by the socratesX skill — the Main Agent invokes socratesX in question mode to surface hidden assumptions, contradictions, missing boundaries, technical risks, cross-module conflicts, and non-functional ambiguity. Explore the codebase first (Glob/Grep/rg) so each question is grounded in code evidence. The socratesX output structure (当前理解 / 已确认关键事实 / 待澄清问题) accumulates into the design consensus, and socratesX summary aligns with the Phase 1 Exit Output below. Do NOT generate the Hybrid Tree in Phase 1.
Full specification: modules/08-requirements-discovery.md §8.2
Phase Transition (Hard Gate)
Phase 1 → Phase 2 transition requires HARD GATE — no bypass allowed.
HARD CONSTRAINT: User language/text input does NOT directly trigger Phase 2. It only triggers the Hard Gate (AskUserQuestion). Only after user clicks "确认生成 PRD" option does Phase 2 proceed.
Trigger detection — when user message contains:
- 中文: 确认, 开始, 开工, 生成文档, 就这样, 可以了, 没问题, 好的, 行, 确定
- English: confirm, start, generate, proceed, go ahead, done, ok, yes, sure
Gate mechanism — Main Agent MUST call AskUserQuestion:
AskUserQuestion({
questions: [{
question: "需求澄清已完成,已确认 [N] 项事实。请确认:",
header: "Phase 1 确认",
multiSelect: false,
options: [
{ label: "确认生成 PRD(推荐)", description: "生成 Hybrid Tree 并启动开发迭代" },
{ label: "查看已确认内容", description: "输出 socratesX summary 格式摘要" },
{ label: "继续澄清", description: "返回 socratesX question 模式" },
{ label: "修改范围", description: "重新界定需求目标和边界" }
]
}]
})
Only "确认生成 PRD" proceeds to Phase 2. Other options loop back within Phase 1.
Phase 1 exit signal template (shown before gate):
方案设计完成。以下是推荐方案:
[Brief design consensus summary]
Phase 2 entry:
- ONLY after user clicks "确认生成 PRD" in AskUserQuestion
- Invoke
noiseX summary to denoise Phase 1 context (internal, not shown to user)
- Generate Hybrid Tree with all discoveries written to appropriate sections, using noiseX purified summary as clean signal source
- Proceed to Core Iteration Loop
Knowledge Graph Writeback
When the user triggers Summary:
- Read confirmed facts from
mcp/server-memory for the current session, generate a structured knowledge graph
- Clean up: retain only user-confirmed facts, delete speculation and pending items
- Serialize and write to Parent Section 8.4
- If old snapshot exists, overwrite with timestamp preserved, do not add duplicates
Findings → Hybrid Tree Mapping
Write confirmed findings into appropriate sections during Hybrid Tree creation:
| Finding Type | Target Section |
|---|
| Confirmed scope | Parent §1 Project Overview |
| Technical constraints | Parent §3 Technical Constraints |
| Edge cases | Child §7 AC |
| NFRs (security, perf) | Parent §4 NFR |
| Risk mitigations | Child §7 AC |
| Accepted risks | Parent §4 NFR |
| Cross-module dependencies | Parent §8.3 Dependencies |
| File index | Parent §8.1 (shared), Child §8.1 (private) |
| Knowledge insights | Parent §8.2 Knowledge Graph |
Hybrid Tree Creation
All planning outputs must use the Hybrid Tree structure. Regardless of requirement size, generate one Parent + at least one Child.
Design principles:
- Parent-Child separation of responsibility: Parent is the routing layer (global spec, routing table, global index, knowledge graph). Child is the requirement layer (branch AC, branch index).
- MECE: Children scopes are mutually exclusive and collectively exhaustive, no gaps or overlaps.
- High cohesion, low coupling: Each Child contains tightly related requirements. Cross-Child dependencies minimized and recorded in Parent 8.3.
- Prevent over-splitting: Each Child must have independent scope justifying its existence.
- Temporal and causal continuity: Sequential dependencies reflected in Child ordering and dependency annotations.
Creation flow:
- Create directory
.hybrid/[feature-name]/
- Create Parent hybrid: fill Sections 0-6, Section 7 routing table, 8.1 shared files, 8.2 knowledge graph, 8.3 cross-branch dependencies
- Create Child hybrids: one per sub-module, fill Section 7 AC, 8.1 private files
- Pass Parent path to Main Agent, Main Agent routes to each Child for development
Template: Strictly follow hybrid-template.md. Section numbers and physical order must not change (adapted for Token caching: static sections first, incremental middle, dynamic last).
Quality Gates
- Must not lock specific business rules without user confirmation
- Do not output low-level code snippets or overly detailed API designs during discovery
- Maintain exploratory dialogue mode outside Summary stage
- Focus on product context, high-level boundaries, and executable acceptance criteria
- Always ground findings in actual code evidence (file paths, patterns, constraints)
Hybrid Tree Section Map (Optimized: Section-Level Caching)
coderX receives Parent/Child paths through the Type 0 Dispatch Payload, and evaluatorX receives a Type 1.5 Review Dispatch Payload from Main Agent. The table below defines available Hybrid Tree sections; for evaluatorX, actual reads are controlled by Review Brief, Review Context Manifest, Review Context Budget, Required Reads, and Conditional Reads in the Review Dispatch Payload, not by default full-document loading.
| Document | Section | Content | Readers | Cache Strategy |
|---|
| Parent | 0-6 | Global spec (NFR, DoD, Scope) | coderX, evaluatorX | Session Cache: Read once, cache entire block. Invalidate only on requirement change. |
| Parent | 7 | Routing table (not AC source) | coderX | Session Cache: Read once per iteration round. |
| Parent | 8.1 | Shared file index | coderX, evaluatorX | Session Cache: Read once, invalidate on file structure change. |
| Parent | 8.2 | Knowledge graph outlines (details via MCP) | coderX, evaluatorX | Session Cache: Read once per session. |
| Parent | 8.3 | Cross-branch dependencies | coderX, evaluatorX | Session Cache + Invalidation: Read once, invalidate on requirement change only. |
| Child | 7 | Branch AC (evaluation target) | coderX, evaluatorX | No Cache: Changes frequently during iteration. |
| Child | 8.1 | Private file index | coderX, evaluatorX | Session Cache: Read once, invalidate on file change. |
| Child | 8.2 | Incremental references | coderX | No Cache: Iteration-specific. |
| Child | 9 | Prior evaluation results | evaluatorX (for inheritance) | No Cache: Changes every iteration. |
Context hand-off rule (Optimized): coderX receives the Main Agent's Execution Brief, Context Manifest, Context Budget, and agent-readable document paths through the Type 0 Dispatch Payload. The first implementation round reads only the manifest-listed sections before broad exploration. In subsequent coderX rounds, prefer a lightweight trunk: include only Parent §8.2 (Memory Pointers entity/relation summaries) plus the current Child §7 (AC) and §9 (prior evaluation / fix instructions), unless the Context Manifest requires more. evaluatorX receives Review Brief, Review Context Manifest, and Review Context Budget through Type 1.5 Review Dispatch, reads git diff and changed file hunks first, then reads Child §7 and conditional Parent/Child/MCP context only as allowed by the review manifest and budget.
Core Iteration Loop (Optimized: Dependency Graph + Ready Queue)
Shared by Mode A and Mode B (with Hybrid Tree).
Dispatch Tracking
Workflow execution state is tracked in the current conversation context, the Hybrid Tree documents, and the Core Loop's in-memory ready queue / iteration counters.
Before each dispatch, Main Agent must still assemble and validate the full Type 0 or Type 1.5 payload. After each return, Main Agent updates the Hybrid Tree evaluation sections through module 03 and advances the ready queue.
Pre-Loop Setup: Build Dependency Graph
1. Read Parent Section 7 → extract all Children
2. Read Parent Section 8.3 → extract dependency edges (CACHE THIS)
3. Build adjacency list + in-degree map:
- in_degree[child] = number of dependencies
- adj[parent_dep] = [children that depend on it]
4. Initialize per-child iteration counters:
- child_iterations[child] = { used: 0, remaining: sessionParams.iteration_limit }
5. Initialize ready_queue (FIFO):
- For each child where in_degree[child] == 0 → push to ready_queue
6. Critical Path Analysis (Optimized):
- Identify critical path: longest dependency chain
- Identify high-impact nodes: children with most dependents
- Priority score: impact_score = number_of_dependents + (1 / chain_position)
- Sort ready_queue by priority (highest first)
Phase 1 — Ready Queue Processing (replaces sequential scan)
While ready_queue is not empty:
current = ready_queue.dequeue()
0. ITERATION CHECK:
- If child_iterations[current].remaining <= 0:
mark as "Limit Reached", report to human, continue to next
1. Build Type 0 Dispatch Payload for Agent(coderX):
- Workflow Mode: xwhole or xlocal
- Dispatch Type: implement for first round, fix when prior Fix Instructions exist
- Execution Brief: Main Agent's authoritative user intent, final interpretation, non-goals, and success criteria
- Context Manifest: Read First / Read If Needed / Do Not Read Unless Needed paths and document sections
- Context Budget: limits for broad search, document reads, and expansion reporting
- Parent Path: current Parent hybrid path
- Child Path: current Child hybrid path
- Acceptance Criteria Source: Child Section 7
- Required Skills: guideX, razorX, specX
- Output Contract: Bus Payload Type 1
- Fix Instructions: prior evaluator Fix Instructions, if any
2. Validate Type 0 Dispatch Payload using module 02, then dispatch Agent(coderX)
3. coderX implements, outputs Change Summary Payload
4. Validate Payload Type 1 (module 02)
5. Build Type 1.5 Review Dispatch Payload for Agent(evaluatorX):
- Workflow Mode: xwhole or xlocal
- Evaluation Type: full for first evaluation/no history, partial when prior PASS + affected ACs exist, fix when prior Fix Instructions drive this round
- Review Brief: Main Agent's authoritative audit target, acceptance scope, risk focus, non-goals, and pass criteria
- Parent Path: current Parent hybrid path
- Child Path: current Child hybrid path
- Acceptance Source: Child Section 7
- Prior Evaluation Source: Child Section 9 when partial/fix, otherwise N/A
- Change Summary: validated Payload Type 1
- Changed Files: from Payload Type 1 and git diff
- Affected ACs Claimed: from Payload Type 1, or N/A for full
- Review Focus: Directed Audit Points + changed file risks + prior Fix Instructions, if any
- Review Context Manifest: Read First / Read If Needed / Do Not Read Unless Needed paths, document sections, and diff/code targets
- Review Context Budget: limits for broad search, document reads, source reads, MCP retrieval, and expansion reporting
- Required Reads / Conditional Reads / Expansion Rules: per module 02 Payload Type 1.5
- Output Contract: Bus Payload Type 2
6. Validate Type 1.5 Review Dispatch Payload, then dispatch Agent(evaluatorX)
7. evaluatorX evaluates, outputs Evaluation Result Payload
8. Load module 03 for Post-Evaluation document update (incremental, see §6)
9. Result handling:
- PASS:
a. Mark current as PASS
b. For each dependent in adj[current]:
in_degree[dependent]--
if in_degree[dependent] == 0 → enqueue to ready_queue
- Needs Fix + child_iterations[current].remaining > 0:
a. child_iterations[current].used++
b. child_iterations[current].remaining--
c. Extract Fix Instructions -> re-enqueue current to ready_queue
- Needs Fix + child_iterations[current].remaining <= 0:
a. Mark as "Limit Reached", report to human
b. Do NOT enqueue dependents (they remain blocked)
Phase 2 — Blocked Queue Resolution
If ready_queue is empty but some children not completed:
- Check for circular dependencies in remaining in_degree > 0 nodes
- If circular: report circular dependency to human, terminate
- If not circular (waiting on external): report blocking dependency to human
Early Exit (Optimized):
- PASS → immediately mark complete, enqueue dependents, move to next in queue
- No need to check iteration limit for PASS'd children
Per-Child Counter State:
child_iterations = {
"child-1": { used: 0, remaining: 2 },
"child-2": { used: 1, remaining: 1 },
}
Dispatch Format:
- Pass a full Type 0 Dispatch Payload from
modules/02-bus-payload.md.
- Do not dispatch coderX with only
Parent: [path] + Child: [path].
- Do not ask coderX to infer mode, output contract, MCP policy, verification scope, fix-round intent, or user intent from conversation context.
- Include
Execution Brief, Context Manifest, and Context Budget so coderX executes Main Agent's settled interpretation instead of rebuilding the requirement from scratch.
- Pass a full Type 1.5 Review Dispatch Payload to evaluatorX after validating coderX's Change Summary.
- Do not dispatch evaluatorX with only
Parent + Child + Change Summary, and do not ask it to infer review scope, evaluation mode, audit target, MCP policy, context-reading strategy, or expansion rules from conversation context.
- Include
Review Brief, Review Context Manifest, and Review Context Budget so evaluatorX audits Main Agent's declared target without rebuilding the feature context from scratch.
Minimal Hybrid Tree Auto-Generation (Mode B, No Related PRD)
When Mode B has no explicit PRD and no related existing Hybrid Tree in .hybrid/, Main Agent auto-generates a minimal Hybrid Tree before entering the Core Iteration Loop. This replaces the former Simple Iteration Loop path.
Main Agent executes (sole document writer):
- Code Scan: Use Glob/Grep/rg to search project for files related to the requirement
- Generate Parent (
hybrid-template.md):
- Section 0: MCP status from Module 01
- Sections 1-6: Minimal fill from requirement (project goal, boundaries, NFR, DoD)
- Section 7: Routing table with single Child row
- Section 8.1: Shared file index from scan results
- Section 8.2: Knowledge graph skeleton (outlines only)
- Section 8.3: Empty (single Child, no cross-branch dependencies)
- Section 9: Empty aggregation table
- Generate Child (
hybrid-template.md):
- Section 7: Acceptance criteria decomposed from requirement
- Section 8.1: Private file index for relevant files
- Section 9: Empty evaluation report
- Write both documents to
.hybrid/[feature-name]/
- Enter Core Iteration Loop with generated Parent + Child
PRD file path input: When user passes a file path (e.g. /xlocal ./docs/prd.md), read the PRD file and use its content to populate Sections 1-6 and derive AC for Section 7, instead of inferring from the raw requirement.
Requirement Change: Follow the standard Requirement Change Handling (shared by Mode A and Mode B with Hybrid Tree).
Hybrid Tree Routing
Tree Detection
Hybrid Tree exists when:
.hybrid/[feature]/ directory contains multiple *-hybrid.md files
- File marked
Document Type: Parent contains Section 7 routing table
For xlocal without an explicit Hybrid Tree path, discovery is repository-wide:
- Enumerate
.hybrid/*/ directories, ignoring locks and non-directory files
- Identify Parent candidates by
Document Type: Parent plus a Section 7 routing table
- Score relevance against the current requirement using:
- directory name and Parent title
- Parent §1 overview, §3 boundaries/scope, and §6 scope
- Parent §7 Child scope rows
- Child §7 acceptance criteria
- Parent/Child §8.1 file indexes
- Treat a candidate as reusable only when the requirement clearly overlaps an existing Parent scope or file index
- If one candidate matches, reuse and maintain it; if several match, ask the user to choose; if none match, continue to PRD file detection or minimal auto-generation
Routing Logic
- Read Parent Section 7 routing table
- Compare current task/requirement against each Child's Scope column
- Match found -> build a Type 0 Dispatch Payload for coderX, then dispatch coderX and evaluatorX through the standard Bus pipeline
- No match -> execute Requirement Change Handling (Change Type = new_branch)
Child Creation Flow
When Requirement Change Handling determines Change Type = new_branch:
- Analysis results contain: feature description, suggested AC list, suggested file scope
- Main Agent executes:
- Create new Child document using Child template, fill feature description -> Section 7 Description, suggested ACs -> Section 7 AC
- Add new row to Parent Section 7 (append end; dependency order is resolved at runtime by the Core Loop's deferred queue)
- Update Parent Section 8.3 (if new dependencies)
- Build a Type 0 Dispatch Payload with
Dispatch Type=new_branch, then dispatch Agent(coderX)
- Include Execution Brief, Context Manifest, Context Budget, Parent Path, new Child Path, new branch reason, acceptance source, allowed scope, and Output Contract
Requirement Change Handling
Shared by Mode A and Mode B (all paths use Hybrid Tree).
Step 1: Change Detection
Main Agent determines whether user input changed the current Child's requirement scope. Analyze user input, determine change type:
| Change Type | Detection Criteria | Action |
|---|
| Adjustment | Modifying existing AC of current Child | Update current Child |
| Optimization | Refining existing functionality of current Child | Update current Child |
| Scope Expansion | Adding to current Child's scope | Update current Child |
| Scope Reduction | Removing AC from current Child | Update current Child |
| New Branch Feature | Feature does not belong to any existing Child | Create new Child |
Step 2: Major Change Confirmation
| Change Type | Confirmation Required |
|---|
| New Branch Feature | Yes — describe new feature, ask "Confirm creating new sub-module?" |
| Scope Expansion > 50% | Yes — describe expansion, ask "Confirm scope expansion?" |
| Scope Reduction (removing AC) | Yes — list deleted ACs, ask "Confirm deleting these acceptance criteria?" |
| Adjustment / Optimization | No — proceed directly |
If user rejects, discard the change and resume original flow.
Step 3: Document Update
Read change analysis results, execute:
- Update Child Section 7 (AC add/modify/delete)
- Update Parent Section 7 (routing table)
- Update Parent Section 8.3 (dependencies)
- Reset affected Children Status to "Needs Re-evaluation"
Identify affected Children:
- Read Parent Section 8.3 (cross-branch dependencies)
- If updated Child is depended on by other Children: list all dependent Children, mark as "Needs Re-evaluation"
- If updated Child depends on other Children: verify dependency satisfied (Status = PASS), record warning if not
Constraints: traceability (all changes traceable to user description), Parent Sections 0-6 not modified, MECE principle.
Step 4: Resume Workflow
- Modified Child is currently iterating: reset iteration counter, restart from that Child
- Modified Child is already PASS'd: Status reset to "Needs Re-evaluation", re-execute in next loop cycle
- Modified Child is not yet executed: documents updated, loop handles naturally
- Change Type =
new_branch: follow Child Creation Flow
Auto-Routing
Delegated: Full routing logic is in .claude/skills/routeX/SKILL.md. Main Agent receives an explicit mode parameter and does NOT perform routing itself.
Start Rule
- Routing priority: Explicit command > natural language intent > Auto-Routing. When uncertain, require user to specify
/xwhole, /xlocal, /xunit. Parallel execution via /xwhole -parallel.
- State isolation: Stay in current workflow mode until completion. No cross-mode calls.
- Hybrid Tree: whole and local must generate Hybrid Tree (even if skipping planning, create minimal version from
orchestrateX/hybrid-template.md). unit exempt.
- Concurrency protection: Before starting any workflow, check for
.hybrid/.workflow-lock. If lock exists, warn user and abort. Otherwise, create lock file with timestamp and mode. Remove lock on workflow completion or interruption.