[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M754XTM2SA7YGY6W51877CSM":3,"skill-same:01M754XTM2SA7YGY6W51877CSM":58},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":33,"repositoryHtmlUrl":34,"repositoryHomepageUrl":6,"ownerHtmlUrl":35,"ownerBlogUrl":36,"ownerDescription":37,"updatedAt":38,"install":39,"resources":51},"01M754XTM2SA7YGY6W51877CSM","x-orchestrate-epic",null,"Orchestrates multi-agent planning for all stories in an epic, respecting dependency order, with checkpoint and resume support.","review-bench\u002Federcnj_ia-dev-environment","review-bench","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F286778065?v=4","01M7517F9NTEPDZDAXJBR30FWT","ReviewBench","01M7517FAC9F4P7TGWCNJ8VYVW",0,"MIT","https:\u002F\u002Fgithub.com\u002Freview-bench\u002Federcnj_ia-dev-environment\u002Fblob\u002Fmain\u002Fsrc\u002Ftest\u002Fresources\u002Fgolden\u002Fjava-spring-fintech-pci\u002F.claude\u002Fskills\u002Fx-orchestrate-epic\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: x-orchestrate-epic\nmodel: sonnet\ndescription: \"Orchestrates multi-agent planning for all stories in an epic, respecting dependency order, with checkpoint and resume support.\"\nuser-invocable: true\nallowed-tools: \"Read, Write, Edit, Bash, Grep, Glob, Agent, AskUserQuestion, Skill, TaskCreate, TaskUpdate\"\nargument-hint: \"[EPIC-ID] [--resume] [--story story-XXXX-YYYY] [--dry-run]\"\ncontext-budget: heavy\nrequires-capabilities: []\n---\n\n## Global Output Policy\n\n- **Language**: Use English for orchestration text, status\u002Fcheckpoint messages, and control-flow markers. Use pt-BR for user-facing planning report content when required by later rules (including RULE-006).\n- **Tone**: Technical, Direct, and Concise.\n- **Efficiency**: Remove all conversational fillers and greetings to save tokens.\n\n# Skill: Epic Planning Orchestrator\n\n## Purpose\n\nOrchestrate multi-agent planning for all stories in an epic by invoking `\u002Fx-plan-story` for each story in dependency order. Parse the implementation map to determine phase ordering, dispatch planning in parallel within each phase, track planning status in `execution-state.json`, and support checkpoint\u002Fresume for interrupted runs.\n\n## When to Use\n\n> **⚠️ Esta skill NÃO cria épico nem stories.** Para criar a feature inteira a partir de uma spec markdown, use `\u002Fx-create-feature \u003CSPEC-FILE-PATH> --epic-id \u003CNNNN>`. Esta skill apenas orquestra **planning multi-agente** (Architect + QA + Security + Tech Lead + Product Owner) das stories **já criadas**.\n>\n> Fluxo canônico da Feature Creation Chain (EPIC-0065):\n> 1. `\u002Fx-ideate-feature \"prosa livre\"` → spec.md + PR `docs\u002Ffeature-\u003Cslug>` → develop (manual gate)\n> 2. `\u002Fx-create-feature \u003Cspec> --epic-id \u003CNNNN>` → epic + stories + map + PR `docs\u002F\u003Cid>-\u003Cslug>` → epic\u002FXXXX (auto-merge)\n> 3. `\u002Fx-orchestrate-epic \u003CNNNN>` → 6 artefatos de Phase 1 por story (planning multi-agente)\n\n- Use **depois** de `x-create-feature` ter gerado epic + stories + IMPLEMENTATION-MAP\n- Use para gerar `plan-story-XXXX-YYYY.md` e demais artefatos de Phase 1 em paralelo across stories\n\nInvocation forms:\n\n- `\u002Fx-orchestrate-epic XXXX` -- plan all stories in an epic\n- `\u002Fx-orchestrate-epic XXXX --resume` -- resume planning from last checkpoint\n- `\u002Fx-orchestrate-epic XXXX --story story-XXXX-YYYY` -- plan only a specific story\n\n## CRITICAL EXECUTION RULE\n\n**4 phases (0-3). ALL mandatory. NEVER stop before the final phase.**\n\nAfter each phase 0-2: `>>> Phase N\u002F3 completed. Proceeding to Phase N+1...`\nAfter Phase 3: `>>> Phase 3\u002F3 completed. Epic planning complete.`\n\n## Workflow Overview\n\n```\nPhase 0: PREREQUISITES         -> Parse args, validate epic dir, map, stories (inline)\nPhase 1: DEPENDENCY ORDER      -> Read map, extract phases, order stories (inline)\nPhase 2: PLAN LOOP             -> For each phase, invoke \u002Fx-plan-story per story (subagents)\nPhase 3: REPORT                -> Generate readiness summary, update epic file (inline)\n```\n\n## Input Parsing\n\n### Positional Argument (Required)\n\n| Argument | Format | Required | Description |\n|----------|--------|----------|-------------|\n| `EPIC-ID` | `XXXX` (4-digit zero-padded) | **Mandatory** | The epic identifier, e.g., `0028` |\n\nThe epic ID is a required positional argument. If missing, abort immediately:\n\n```\nERROR: Epic ID is required. Usage: \u002Fx-orchestrate-epic [EPIC-ID] [--resume] [--story story-XXXX-YYYY]\n```\n\n### Optional Flags\n\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--resume` | boolean | `false` | Continue from last checkpoint (skip stories with `planningStatus == \"READY\"`) |\n| `--story story-XXXX-YYYY` | string | (all stories) | Plan only a specific story by ID |\n| `--dry-run` | boolean | `false` | Artifacts written to disk but Steps P1 \u002F P2 \u002F P4 \u002F P5 become no-ops (EPIC-0049 \u002F RULE-007) |\n\n**Mutual exclusivity:** `--resume` and `--story` are mutually exclusive. If both are provided, abort:\n\n```\nERROR: --resume and --story are mutually exclusive. Use only one.\n```\n\n---\n\n## Step P1 — Detect Worktree Context (EPIC-0049 \u002F RULE-001)\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-P1-Worktree-Detect`\n\nInvoke `x-manage-worktrees` in detect-context mode. Result is advisory only — `x-internal-ensure-epic-branch` (Step P2) makes the authoritative decision.\n\n    Skill(skill: \"x-manage-worktrees\", args: \"detect-context\")\n\nContinue on any detect-context failure (fail-open, RULE-006).\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-P1-Worktree-Detect ok`\n\n## Step P2 — Ensure `epic\u002F\u003CID>` Branch (EPIC-0049 \u002F RULE-001)\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-P2-Epic-Branch-Ensure`\n\nUse the resolved `EPIC-ID` argument (`XXXX`).\n\nInvoke `x-internal-ensure-epic-branch` so the canonical `epic\u002F\u003CID>` branch exists locally AND on origin (idempotent):\n\n    Skill(skill: \"x-internal-ensure-epic-branch\", args: \"--epic-id \u003CXXXX>\")\n\nOn failure (non-zero exit), abort with `EPIC_BRANCH_ENSURE_FAILED`. When `--dry-run` is set, skip this step.\n\nThis step runs ONCE at orchestrator entry. Child `\u002Fx-plan-story` invocations in Phase 2 receive `--no-commit` so they do not re-ensure the branch nor issue per-story commits — the wave-level Step P4 below aggregates commits per wave.\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-P2-Epic-Branch-Ensure ok`\n\n---\n\n\u003C!-- phase-no-gate: read-only prerequisite validation; no artifact produced until Phase 1 -->\n## Phase 0 -- Prerequisites (Orchestrator -- Inline)\n\nOpen a phase tracker (close with `TaskUpdate(id: phase0TaskId, status: \"completed\")` after 0.7):\n\n    TaskCreate(subject: \"{epicId} › Phase 0 - Prerequisites\", activeForm: \"Validating epic prerequisites\")\n\n### 0.1 Parse Epic ID\n\nExtract the 4-digit zero-padded epic ID from the positional argument.\n\n- Input: `0028` -> epic ID = `0028`\n- If the argument is not a 4-digit number, abort with format error:\n  ```\n  ERROR: Invalid epic ID format. Expected 4-digit zero-padded number (e.g., 0028).\n  ```\n\n### 0.2 Parse Flags\n\nCheck for `--resume` and `--story` flags. Validate mutual exclusivity.\n\n### 0.3 Resolve Epic Directory\n\nResolve the epic directory using a glob to support suffix variants (e.g., `ai\u002Fepics\u002Fepic-XXXX-title-slug\u002F`):\n\n```bash\n# Resolve epic directory (exact match first, then suffix variant)\nepicDir=$(ls -d ai\u002Fepics\u002Fepic-{epicId}\u002F ai\u002Fepics\u002Fepic-{epicId}-*\u002F 2>\u002Fdev\u002Fnull | head -1)\n```\n\nIf no match is found, abort:\n\n```\nERROR: Directory ai\u002Fepics\u002Fepic-{epicId}\u002F (or suffix variant) not found. Run \u002Fx-epic-decompose first.\n```\n\nUse the resolved `epicDir` path for ALL subsequent reads\u002Fwrites (IMPLEMENTATION-MAP.md, stories, execution-state.json, reports).\n\n### 0.4 Validate Implementation Map\n\nCheck that `IMPLEMENTATION-MAP.md` exists in the epic directory.\n\n```\nERROR: IMPLEMENTATION-MAP.md not found in ai\u002Fepics\u002Fepic-{epicId}\u002F. Run \u002Fx-epic-map first.\n```\n\n### 0.5 Validate Story Files\n\nGlob for `story-XXXX-*.md` files in the epic directory. At least one must exist.\n\n```\nERROR: No story files found matching story-{epicId}-*.md in ai\u002Fepics\u002Fepic-{epicId}\u002F.\n```\n\n### 0.6 Resume Checkpoint Validation (Conditional)\n\nIf `--resume` flag is set, check that `execution-state.json` exists in the epic directory.\n\n```\nERROR: No checkpoint found (execution-state.json missing). Cannot resume. Run without --resume.\n```\n\nIf `--resume` is set and `execution-state.json` exists, load it and apply reclassification:\n\n| Current `planningStatus` | New `planningStatus` | Rationale |\n|--------------------------|----------------------|-----------|\n| `READY` | `READY` | Preserved -- skip this story |\n| `NOT_READY` | `PENDING` | Re-attempt planning |\n| `IN_PROGRESS` | `PENDING` | Interrupted -- reset for retry |\n| `PENDING` | `PENDING` | No change |\n\n### 0.7 Create Plans Directory\n\nCreate `{epicDir}\u002Fplans\u002F` if it does not exist:\n\n```bash\nmkdir -p {epicDir}\u002Fplans\n```\n\nLog: `\"Created plans\u002F directory for EPIC-{epicId}\"` if created. Skip silently if already exists.\n\nPersist interactiveMode to execution-state.json (EPIC-0068 — consumed by Stop hook `enforce-continuous-flow.sh`):\n\n    Skill(skill: \"x-internal-update-status\", args: \"--file {epicDir}\u002Fexecution-state.json --type epic --id \u003CEPIC-ID> --field interactiveMode --value \u003Cinteractive|non-interactive>\")\n\nValue: `\"interactive\"` when `--interactive` passed or `CLAUDE_LEGACY_INTERACTIVE=1`; otherwise `\"non-interactive\"` (Rule 20 default, EPIC-0061).\n\n    TaskUpdate(id: phase0TaskId, status: \"completed\")\n\n>>> Phase 0\u002F3 completed. Proceeding to Phase 1...\n\n---\n\n## Phase 1 -- Dependency Order (Orchestrator -- Inline)\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode pre --skill x-orchestrate-epic --phase Phase-1-Discovery\")\n    TaskCreate(subject: \"{epicId} › Phase 1 - Discovery\", activeForm: \"Resolving story dependency order\")\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-1-Discovery`\n\n### 1.1 Read Implementation Map\n\nRead `{epicDir}\u002FIMPLEMENTATION-MAP.md` and extract phases and dependencies from two sections:\n\n1. **Dependency declarations** from **Section 1 — Dependency Matrix**:\n\n```markdown\n| Story | Título | Chave Jira | Blocked By | Blocks | Status |\n| :--- | :--- | :--- | :--- | :--- | :--- |\n| story-XXXX-0001 | Title | KEY-1 | — | story-XXXX-0002 | Pendente |\n| story-XXXX-0002 | Title | KEY-2 | story-XXXX-0001 | — | Pendente |\n```\n\nParse the `Blocked By` and `Blocks` columns to build the dependency graph.\n\n2. **Phase assignments** from **Section 5 — Resumo por Fase**:\n\n```markdown\n| Fase | Histórias | Camada | Paralelismo | Pré-requisito |\n| :--- | :--- | :--- | :--- | :--- |\n| 0 | story-XXXX-0001 | Domain | 1 paralela | — |\n| 1 | story-XXXX-0002, story-XXXX-0003 | Application | 2 paralelas | Fase 0 concluída |\n| 2 | story-XXXX-0004 | Adapter | 1 paralela | Fase 1 concluída |\n```\n\nParse the `Fase` and `Histórias` columns to determine phase grouping. Extract total phases from the number of distinct `Fase` values.\n\n### 1.2 Order Stories by Phase\n\n1. Group stories by their phase number\n2. Sort phases numerically: Phase 0, Phase 1, Phase 2, ...\n3. Within each phase, stories can be planned in **parallel** (no inter-phase dependencies within the same phase)\n\n### 1.3 Single-Story Mode (Conditional)\n\nIf `--story` flag is provided:\n\n1. Locate the specified story in the implementation map\n2. If not found, abort:\n   ```\n   ERROR: Story {storyId} not found in implementation map.\n   ```\n3. Identify the story's dependencies from the implementation map\n4. Validate that all dependencies have `planningStatus == \"READY\"` in `execution-state.json`:\n   - If `execution-state.json` does not exist, check if dependency story files have existing planning artifacts (tasks file exists at `{epicDir}\u002Fplans\u002Ftasks-story-XXXX-YYYY.md`)\n   - If any dependency is not satisfied, abort:\n     ```\n     ERROR: Dependencies not satisfied for {storyId}: [{unsatisfied deps list}]. Plan dependencies first.\n     ```\n5. If all dependencies are satisfied, set the plan loop to process only this story\n\n### 1.4 Initialize Execution State\n\nIf `execution-state.json` does not exist in `{epicDir}\u002F`, create it using the same top-level schema as `\u002Fx-implement-epic`, adding planning-specific fields under each story entry:\n\n```json\n{\n  \"epicId\": \"XXXX\",\n  \"baseBranch\": \"develop\",\n  \"startedAt\": \"{ISO-8601 timestamp}\",\n  \"totalPhases\": {count},\n  \"stories\": [\n    {\"id\": \"story-XXXX-0001\", \"phase\": 0},\n    {\"id\": \"story-XXXX-0002\", \"phase\": 1}\n  ],\n  \"storyEntries\": {\n    \"story-XXXX-0001\": {\n      \"id\": \"story-XXXX-0001\",\n      \"phase\": 0,\n      \"planningStatus\": \"PENDING\",\n      \"planningStartedAt\": null,\n      \"planningCompletedAt\": null,\n      \"dorVerdict\": null,\n      \"artifacts\": []\n    }\n  }\n}\n```\n\n**Schema compatibility with `\u002Fx-implement-epic`:** The `stories` array and `baseBranch` field match the schema expected by `\u002Fx-implement-epic`. Planning-specific fields (`planningStatus`, `dorVerdict`, `artifacts`) are added under `storyEntries` alongside where `\u002Fx-implement-epic` adds its own fields (`status`, `commitSha`, `prUrl`, etc.). Both skills read\u002Fwrite the same file without conflict.\n\nIf `execution-state.json` already exists (either from `--resume` or prior partial run), preserve existing data and only add `storyEntries` for stories not yet tracked. Never overwrite fields owned by `\u002Fx-implement-epic`.\n\n**Per-story planning fields in `storyEntries`:**\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `id` | String | Yes | Story ID (e.g., `story-0028-0001`) |\n| `phase` | Integer | Yes | Phase number from implementation map |\n| `planningStatus` | String | Yes | `PENDING`, `IN_PROGRESS`, `READY`, `NOT_READY` |\n| `planningStartedAt` | String | When IN_PROGRESS | ISO-8601 timestamp of planning start |\n| `planningCompletedAt` | String | When READY\u002FNOT_READY | ISO-8601 timestamp of planning completion |\n| `dorVerdict` | String | When completed | `READY` or `NOT_READY` from `\u002Fx-plan-story` output |\n| `artifacts` | String[] | When completed | List of generated artifact paths |\n\nLog the execution plan:\n\n```\nEpic Planning -- EPIC-{epicId}\nTotal stories: {count}\nTotal phases: {count}\nMode: {all | resume | single-story}\nExecution order:\n  Phase 0: story-XXXX-0001\n  Phase 1: story-XXXX-0002, story-XXXX-0003\n  Phase 2: story-XXXX-0004\n```\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-1-Discovery ok`\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode post --skill x-orchestrate-epic --phase Phase-1-Discovery --expected-artifacts ai\u002Fepics\u002Fepic-{epicId}\u002Fexecution-state.json\")\n    TaskUpdate(id: phase1TaskId, status: \"completed\")\n\n>>> Phase 1\u002F3 completed. Proceeding to Phase 2...\n\n---\n\n## Phase 2 -- Plan Loop (Orchestrator -- Dispatches Subagents)\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode pre --skill x-orchestrate-epic --phase Phase-2-PlanLoop\")\n    TaskCreate(subject: \"{epicId} › Phase 2 - Plan Loop\", activeForm: \"Orchestrating story planning loop\")\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-2-Story-Orchestration`\n\nExecute planning for each story in dependency order, phase by phase.\n\n### 2.1 Phase-by-Phase Execution\n\nFor each phase (0..N), in order:\n\n```\nFor each phase in (0..totalPhases-1):\n  1. Collect all stories in this phase\n  2. Filter out stories with planningStatus == \"READY\" (already planned)\n  3. For each remaining story in this phase:\n     a. Update execution-state.json: planningStatus = \"IN_PROGRESS\", planningStartedAt = now()\n     b. Dispatch \u002Fx-plan-story via Agent subagent\n     c. Collect DoR verdict from subagent result\n     d. Update execution-state.json with result\n  4. Log phase completion summary\n```\n\n### 2.2 Subagent Dispatch\n\n**CONTEXT ISOLATION: You receive only metadata. Read all files yourself.\nDo NOT expect source code, diffs, or knowledge pack content in this prompt.\nThe subagent reads all story files, KPs, and references independently.**\n\nFor each story to plan, invoke `\u002Fx-plan-story` via the Skill tool.\n\n**Telemetry around per-story dispatch (story-0040-0007 §3.2):** Before each\nsubagent invocation emit a `subagent.start` marker with the story ID as the\nrole; after the subagent returns emit a `subagent.end` marker carrying the\noutcome status. The role value is the full story ID (e.g., `story-0028-0001`)\nso the telemetry analysis can group per-story planning latency:\n\n\u003C!-- TELEMETRY: subagent.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh subagent-start x-orchestrate-epic {storyId}`\n\n**Skill invocation:**\n\n```\nSkill(skill: \"x-plan-story\", args: \"{storyId} --no-commit\")\n```\n\n`--no-commit` is always propagated (EPIC-0049 \u002F RULE-007 batch-commit contract). Each child `x-plan-story` writes artifacts to disk but SKIPS its own P4 commit. The wave-level **Step P4 — Commit Wave Artifacts** (below, added to Phase 2.5) aggregates every story's artifacts + `execution-state.json` + reports into a single commit per wave.\n\n\u003C!-- TELEMETRY: subagent.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh subagent-end x-orchestrate-epic {storyId} ok`\n\nThe skill executes all 6 phases of `\u002Fx-plan-story` (Input Resolution, Context Gathering, Parallel Planning, Consolidation, Artifact Generation, DoR Validation) and returns a result containing the DoR verdict.\n\nIf `\u002Fx-plan-story` is unavailable via the Skill tool, fall back to the Agent tool:\n```\nAgent(prompt: \"\u002Fx-plan-story {storyId} --no-commit\")\n```\n\n**Parallel dispatch within a phase:**\n\nStories within the same phase have no inter-dependencies, so they CAN be dispatched in parallel using multiple Agent calls in a single message. However, to manage context window and memory pressure:\n\n- If the phase contains \u003C= 3 stories: dispatch all in parallel (single message with multiple Agent calls)\n- If the phase contains > 3 stories: dispatch in batches of 3\n\n### 2.3 Collect Results\n\nAfter each subagent completes, extract the DoR verdict from the output:\n\n1. Search the subagent output for the DoR verdict line: `Verdict: **READY**` or `Verdict: **NOT_READY**`\n2. If the verdict cannot be extracted, check for the existence of the DoR file at `{epicDir}\u002Fplans\u002Fdor-story-XXXX-YYYY.md` and read the verdict from it\n3. If neither source provides a verdict, set `planningStatus = \"NOT_READY\"` and log a warning:\n   ```\n   WARNING: Could not extract DoR verdict for {storyId}. Marking as NOT_READY.\n   ```\n\n### 2.4 Update Execution State\n\nAfter each story planning completes, update the story's entry in `storyEntries`:\n\n```json\n{\n  \"id\": \"story-XXXX-YYYY\",\n  \"phase\": N,\n  \"planningStatus\": \"READY\",\n  \"planningStartedAt\": \"2026-04-07T10:00:00Z\",\n  \"planningCompletedAt\": \"2026-04-07T10:05:00Z\",\n  \"dorVerdict\": \"READY\",\n  \"artifacts\": [\n    \"{epicDir}\u002Fplans\u002Ftasks-story-XXXX-YYYY.md\",\n    \"{epicDir}\u002Fplans\u002Fplanning-report-story-XXXX-YYYY.md\",\n    \"{epicDir}\u002Fplans\u002Fdor-story-XXXX-YYYY.md\"\n  ]\n}\n```\n\nMap DoR verdict to planningStatus:\n\n| DoR Verdict | planningStatus |\n|-------------|----------------|\n| `READY` | `READY` |\n| `NOT_READY` | `NOT_READY` |\n| Error\u002Ftimeout | `NOT_READY` |\n\nWrite `execution-state.json` atomically after each story update. This ensures checkpoint consistency even if the process is interrupted.\n\n### 2.5 Phase Completion Log\n\nAfter all stories in a phase are planned:\n\n```\nPhase {N} planning complete:\n  story-XXXX-0001: READY\n  story-XXXX-0002: NOT_READY (3 blockers)\n  Phase {N} result: {passed}\u002F{total} stories READY\n```\n\n### 2.5b Step P4 — Commit Wave Planning Artifacts (EPIC-0049 \u002F RULE-007)\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-P4-Wave-Commit`\n\nIf `--dry-run` is set, log `\"dry-run, skipping commit\"` and skip this step.\n\nAfter all stories in the current wave (phase) have completed planning and `execution-state.json` has been updated, issue a **single consolidated commit** covering:\n\n1. `execution-state.json` (wave-level checkpoint update)\n2. Every story file touched during the wave (Section 8 updates via status flip)\n3. Every planning artifact produced by the wave's stories:\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Ftasks-story-XXXX-YYYY.md`\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Fplanning-report-story-XXXX-YYYY.md`\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Fdor-story-XXXX-YYYY.md`\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Fplan-story-XXXX-YYYY.md` (if present)\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Ftask-TASK-*.md` (v2)\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Fplan-task-TASK-*.md` (v2)\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Ftask-implementation-map-STORY-*.md` (v2)\n4. Any reports written during the wave (`ai\u002Fepics\u002Fepic-XXXX\u002Freports\u002F**` — added in Phase 3 but may accumulate incrementally).\n\nDelegate to `x-commit-planning`:\n\n    Skill(skill: \"x-commit-planning\",\n          args: \"--scope chore --epic-id \u003CXXXX> --paths ai\u002Fepics\u002Fepic-\u003CXXXX>\u002Fexecution-state.json ai\u002Fepics\u002Fepic-\u003CXXXX>\u002Fstory-\u003CXXXX>-*.md ai\u002Fepics\u002Fepic-\u003CXXXX>\u002Fplans\u002F ai\u002Fepics\u002Fepic-\u003CXXXX>\u002Freports\u002F --subject \\\"planning orchestration cycle (wave \u003CN>)\\\"\")\n\nWhere `\u003CN>` is the current phase number (0-based per Phase 1 — or the wave sequence number when a multi-wave orchestration runs phase-by-phase).\n\nCenario enforced (story-0049-0022): `\"1 commit 'chore(epic-\u003CXXXX>): planning orchestration cycle (wave \u003CN>)' é criado\"` per completed wave.\n\nIdempotency: re-executing with identical inputs produces `commitSha=null` (silent no-op). On `COMMIT_FAILED` (exit 4), abort with the same code.\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-P4-Wave-Commit ok`\n\n### 2.6 Error Handling\n\nIf a subagent fails (throws error, times out, or returns no output):\n\n1. Set `planningStatus = \"NOT_READY\"` for the story\n2. Set `dorVerdict = null`\n3. Log the error:\n   ```\n   ERROR: Planning failed for {storyId}: {error message}\n   ```\n4. Continue with the next story (do NOT abort the entire epic planning)\n\nStories in subsequent phases that depend on a `NOT_READY` story are still planned (planning is about generating artifacts, not about runtime dependencies). The `NOT_READY` status is informational -- it indicates the story may need attention before implementation begins.\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-2-Story-Orchestration ok`\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode post --skill x-orchestrate-epic --phase Phase-2-PlanLoop --expected-artifacts ai\u002Fepics\u002Fepic-{epicId}\u002Fexecution-state.json\")\n    TaskUpdate(id: phase2TaskId, status: \"completed\")\n\n>>> Phase 2\u002F3 completed. Proceeding to Phase 3...\n\n---\n\n## Phase 3 -- Report (Orchestrator -- Inline)\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode pre --skill x-orchestrate-epic --phase Phase-3-Report\")\n    TaskCreate(subject: \"{epicId} › Phase 3 - Report\", activeForm: \"Generating epic planning report\")\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-3-Consolidation`\n\n### 3.1 Generate Readiness Summary\n\nRead the final `execution-state.json` and compute:\n\n| Metric | Calculation |\n|--------|-------------|\n| `stories_planned` | Count of stories with `planningStatus != \"PENDING\"` |\n| `stories_total` | Total number of stories in the epic |\n| `stories_ready` | Count of stories with `planningStatus == \"READY\"` |\n| `stories_not_ready` | Count of stories with `planningStatus == \"NOT_READY\"` |\n| `stories_pending` | Count of stories with `planningStatus == \"PENDING\"` |\n| `overall_status` | See determination table below |\n\n**Overall status determination:**\n\n| Condition | `overall_status` |\n|-----------|------------------|\n| All stories have `planningStatus == \"READY\"` | `READY` |\n| At least one story is `READY` and at least one is `NOT_READY` or `PENDING` | `PARTIALLY_READY` |\n| No stories are `READY` | `NOT_READY` |\n\n### 3.2 Update Epic File\n\nRead the epic file at `{epicDir}\u002FEPIC-XXXX.md` (or `{epicDir}\u002Fepic-XXXX.md` -- case-insensitive glob).\n\nLocate the story index table in Section 5 (or the main story listing). Add or update a `Planning` column:\n\n```markdown\n| # | Story ID | Title | Status | Planning |\n|---|----------|-------|--------|----------|\n| 1 | story-XXXX-0001 | Title | Draft | READY |\n| 2 | story-XXXX-0002 | Title | Draft | NOT_READY |\n| 3 | story-XXXX-0003 | Title | Draft | PENDING |\n```\n\n**Rules for updating the table:**\n\n1. If a `Planning` column already exists, update the values\n2. If no `Planning` column exists, add it as the last column\n3. Preserve all existing columns and data\n4. Only update rows for stories that were planned in this run (preserve existing values for stories not in scope)\n\n### 3.3 Generate Planning Report\n\nWrite a planning summary to `{epicDir}\u002Freports\u002Fepic-planning-report-XXXX.md`:\n\n```markdown\n# Epic Planning Report -- EPIC-{epicId}\n\n> **Epic ID:** EPIC-{epicId}\n> **Date:** {currentDate}\n> **Total Stories:** {stories_total}\n> **Stories Planned:** {stories_planned}\n> **Overall Status:** {overall_status}\n\n## Readiness Summary\n\n| Metric | Count |\n|--------|-------|\n| Stories Total | {stories_total} |\n| Stories Planned | {stories_planned} |\n| Stories Ready (DoR READY) | {stories_ready} |\n| Stories Not Ready (DoR NOT_READY) | {stories_not_ready} |\n| Stories Pending | {stories_pending} |\n\n## Per-Story Results\n\n| # | Story ID | Phase | Planning Status | DoR Verdict | Duration |\n|---|----------|-------|-----------------|-------------|----------|\n| 1 | story-XXXX-0001 | 0 | READY | READY | 45s |\n| 2 | story-XXXX-0002 | 1 | NOT_READY | NOT_READY | 38s |\n| ... | ... | ... | ... | ... | ... |\n\n## Blockers (if any)\n\n{List stories with NOT_READY verdict and their failing DoR checks, if available from the DoR checklist files}\n\n## Generated Artifacts\n\n{List all artifact files generated during this planning run}\n```\n\n### 3.4 Staleness Check for Report (RULE-002)\n\nBefore generating the planning report:\n\n1. Compute report path: `{epicDir}\u002Freports\u002Fepic-planning-report-XXXX.md`\n2. Check if the report file exists:\n   - If NOT found: generate new. Log: `\"Generating planning report for EPIC-{epicId}\"`\n   - If found, compare modification times:\n     - `mtime(execution-state.json) \u003C= mtime(report)` -> reuse existing report. Log: `\"Reusing existing planning report from {date}\"`\n     - `mtime(execution-state.json) > mtime(report)` -> regenerate. Log: `\"Regenerating planning report (execution state modified)\"`\n\n### 3.5 Console Summary\n\nLog the final summary to console:\n\n```\n=== Epic Planning Complete ===\n\nEPIC-{epicId}: {overall_status}\n\n  Stories: {stories_planned}\u002F{stories_total} planned\n  Ready:   {stories_ready}\n  Not Ready: {stories_not_ready}\n  Pending: {stories_pending}\n\n  Report: ai\u002Fepics\u002Fepic-{epicId}\u002Freports\u002Fepic-planning-report-{epicId}.md\n  State:  ai\u002Fepics\u002Fepic-{epicId}\u002Fexecution-state.json\n```\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-3-Consolidation ok`\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode final --skill x-orchestrate-epic --phase Phase-3-Report --expected-artifacts ai\u002Fepics\u002Fepic-{epicId}\u002Freports\u002Fepic-planning-report-{epicId}.md,ai\u002Fepics\u002Fepic-{epicId}\u002Fexecution-state.json\")\n    TaskUpdate(id: phase3TaskId, status: \"completed\")\n\n## Step P5 — Push Epic Branch to Origin (optional, EPIC-0049)\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-P5-Push`\n\nIf `--dry-run` is set, log `\"dry-run, skipping push\"` and skip.\n\nDelegate the push of the canonical `epic\u002F\u003CXXXX>` branch to origin:\n\n    Skill(skill: \"x-push-branch\", args: \"--branch epic\u002F\u003CXXXX>\")\n\nOn push failure (remote rejection, no connectivity), log a WARNING and continue — wave commits are preserved locally. Do NOT abort.\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-P5-Push ok`\n\n>>> Phase 3\u002F3 completed. Epic planning complete.\n\n---\n\n## Checkpoint\u002FResume Protocol\n\n### Checkpoint Mechanism\n\n`execution-state.json` in `{epicDir}\u002F` serves as the checkpoint file. It is updated atomically after each story completes planning.\n\n### Resume Behavior (`--resume`)\n\nWhen `--resume` is set:\n\n1. Load `execution-state.json` from `{epicDir}\u002F`\n2. Apply reclassification (see Phase 0.6)\n3. Stories with `planningStatus == \"READY\"` are **skipped** (artifacts already generated)\n4. Stories with `planningStatus == \"IN_PROGRESS\"` are **reset to PENDING** (interrupted work)\n5. Stories with `planningStatus == \"NOT_READY\"` are **reset to PENDING** (re-attempt)\n6. Stories with `planningStatus == \"PENDING\"` proceed normally\n7. Enter Phase 2 plan loop with the filtered story set\n\n### Idempotency\n\n- Running `\u002Fx-orchestrate-epic XXXX` twice without `--resume` regenerates all artifacts (full run)\n- Running `\u002Fx-orchestrate-epic XXXX --resume` after a partial run only plans stories not yet `READY`\n- `\u002Fx-plan-story` itself has a staleness check (RULE-002): if source files have not changed, it reuses existing artifacts\n\n---\n\n## Output Artifacts\n\n| Artifact | Path | Produced By |\n|----------|------|-------------|\n| Execution state (checkpoint) | `{epicDir}\u002Fexecution-state.json` | x-orchestrate-epic (this skill) |\n| Epic planning report | `{epicDir}\u002Freports\u002Fepic-planning-report-XXXX.md` | x-orchestrate-epic Phase 3 |\n| Epic file update (Planning column) | `{epicDir}\u002FEPIC-XXXX.md` | x-orchestrate-epic Phase 3 |\n| Task breakdown (per story) | `{epicDir}\u002Fplans\u002Ftasks-story-XXXX-YYYY.md` | x-plan-story (subagent) |\n| Task plans (per task per story) | `{epicDir}\u002Fplans\u002Ftask-plan-TASK-NNN-story-XXXX-YYYY.md` | x-plan-story (subagent) |\n| Planning report (per story) | `{epicDir}\u002Fplans\u002Fplanning-report-story-XXXX-YYYY.md` | x-plan-story (subagent) |\n| DoR checklist (per story) | `{epicDir}\u002Fplans\u002Fdor-story-XXXX-YYYY.md` | x-plan-story (subagent) |\n| Story file update (Section 8) | `{epicDir}\u002Fstory-XXXX-YYYY.md` | x-plan-story (subagent) |\n\n---\n\n## Flat File Naming Convention (RULE-004)\n\nAll output files follow the flat naming convention under `{epicDir}\u002Fplans\u002F`:\n\n```\n{epicDir}\u002F\n  EPIC-XXXX.md\n  IMPLEMENTATION-MAP.md\n  story-XXXX-0001.md\n  story-XXXX-0002.md\n  execution-state.json\n  plans\u002F\n    tasks-story-XXXX-0001.md\n    tasks-story-XXXX-0002.md\n    planning-report-story-XXXX-0001.md\n    planning-report-story-XXXX-0002.md\n    dor-story-XXXX-0001.md\n    dor-story-XXXX-0002.md\n    task-plan-TASK-001-story-XXXX-0001.md\n    task-plan-TASK-002-story-XXXX-0001.md\n  reports\u002F\n    epic-planning-report-XXXX.md\n```\n\n---\n\n## Error Handling\n\n| Error | Action | Recovery |\n|-------|--------|----------|\n| Epic directory not found | Abort with error message | Run `\u002Fx-epic-decompose` first |\n| Implementation map not found | Abort with error message | Run `\u002Fx-epic-map` first |\n| No story files found | Abort with error message | Run `\u002Fx-story-create` first |\n| `execution-state.json` missing on `--resume` | Abort with error message | Run without `--resume` |\n| `--resume` and `--story` both set | Abort with error message | Use only one flag |\n| Story not in implementation map (`--story`) | Abort with error message | Check story ID |\n| Dependencies not satisfied (`--story`) | Abort with error message | Plan dependencies first |\n| Subagent fails for a story | Mark `NOT_READY`, continue | Fix issues, re-run with `--resume` |\n| DoR verdict cannot be extracted | Mark `NOT_READY`, log warning | Check subagent output manually |\n| `x-internal-ensure-epic-branch` fails (Step P2) | Abort with `EPIC_BRANCH_ENSURE_FAILED` | Repair remote state; re-run |\n| `x-commit-planning` exit 4 (Step P4 wave commit) | Abort wave with `COMMIT_FAILED` | Inspect conflict; re-run with `--resume` |\n| `x-commit-planning` exit 0 + `noOp=true` (Step P4) | Silent no-op — continue to next wave | — |\n| `x-push-branch` fails (Step P5) | WARN only; local commits preserved | Operator `git push` manually |\n| `--dry-run` set | Steps P1 \u002F P2 \u002F P4 \u002F P5 become no-ops | Re-run without `--dry-run` to version |\n\n---\n\n## Integration with x-implement-epic\n\nThe `execution-state.json` produced by `\u002Fx-orchestrate-epic` uses the same top-level schema as `\u002Fx-implement-epic` (including `baseBranch`, `stories` array, and `totalPhases`). Planning-specific fields are stored under `storyEntries` alongside implementation fields:\n\n| Field | Used By | Values |\n|-------|---------|--------|\n| `status` | x-implement-epic | `PENDING`, `IN_PROGRESS`, `SUCCESS`, `FAILED`, `PARTIAL`, `BLOCKED` |\n| `planningStatus` | x-orchestrate-epic | `PENDING`, `IN_PROGRESS`, `READY`, `NOT_READY` |\n\nBoth fields coexist on the same story entry in `storyEntries`. `\u002Fx-implement-epic` can use `planningStatus == \"READY\"` as a pre-condition gate before dispatching a story for implementation. Neither skill overwrites fields owned by the other.\n\n---\n\n## Skills Dependency Graph\n\n```\n\u002Fx-orchestrate-epic (this skill)\n  |\n  |-- Step P1: x-manage-worktrees detect-context          (advisory)\n  |-- Step P2: x-internal-ensure-epic-branch           (canonical branch)\n  |-- reads: IMPLEMENTATION-MAP.md (phase\u002Fdependency graph)\n  |-- reads: EPIC-XXXX.md (epic context)\n  |-- reads: story-XXXX-*.md (story files)\n  |-- reads\u002Fwrites: execution-state.json (checkpoint)\n  |\n  +-- per story (subagent): \u002Fx-plan-story --no-commit\n  |     |\n  |     +-- 5 parallel subagents: Architect, QA, Security, Tech Lead, PO\n  |\n  |-- Step P4 (per wave): x-commit-planning            (batch commit per wave)\n  +-- Step P5 (end):      x-push-branch                   (push epic branch)\n```\n\n---\n\n## Constraints\n\n- **Memory management**: Limit parallel subagent dispatch to 3 stories per batch to avoid OOM (each `\u002Fx-plan-story` spawns 5 internal subagents)\n- **Checkpoint atomicity**: Always write `execution-state.json` after each story completes, never batch-update\n- **Staleness check (RULE-002)**: `\u002Fx-plan-story` handles its own staleness check; `\u002Fx-orchestrate-epic` only checks for the planning report\n- **Content language (RULE-006)**: User-facing planning report content in pt-BR; technical fields and log messages in English\n","## Global Output Policy\n\n- **Language**: Use English for orchestration text, status\u002Fcheckpoint messages, and control-flow markers. Use pt-BR for user-facing planning report content when required by later rules (including RULE-006).\n- **Tone**: Technical, Direct, and Concise.\n- **Efficiency**: Remove all conversational fillers and greetings to save tokens.\n\n# Skill: Epic Planning Orchestrator\n\n## Purpose\n\nOrchestrate multi-agent planning for all stories in an epic by invoking `\u002Fx-plan-story` for each story in dependency order. Parse the implementation map to determine phase ordering, dispatch planning in parallel within each phase, track planning status in `execution-state.json`, and support checkpoint\u002Fresume for interrupted runs.\n\n## When to Use\n\n> **⚠️ Esta skill NÃO cria épico nem stories.** Para criar a feature inteira a partir de uma spec markdown, use `\u002Fx-create-feature \u003CSPEC-FILE-PATH> --epic-id \u003CNNNN>`. Esta skill apenas orquestra **planning multi-agente** (Architect + QA + Security + Tech Lead + Product Owner) das stories **já criadas**.\n>\n> Fluxo canônico da Feature Creation Chain (EPIC-0065):\n> 1. `\u002Fx-ideate-feature \"prosa livre\"` → spec.md + PR `docs\u002Ffeature-\u003Cslug>` → develop (manual gate)\n> 2. `\u002Fx-create-feature \u003Cspec> --epic-id \u003CNNNN>` → epic + stories + map + PR `docs\u002F\u003Cid>-\u003Cslug>` → epic\u002FXXXX (auto-merge)\n> 3. `\u002Fx-orchestrate-epic \u003CNNNN>` → 6 artefatos de Phase 1 por story (planning multi-agente)\n\n- Use **depois** de `x-create-feature` ter gerado epic + stories + IMPLEMENTATION-MAP\n- Use para gerar `plan-story-XXXX-YYYY.md` e demais artefatos de Phase 1 em paralelo across stories\n\nInvocation forms:\n\n- `\u002Fx-orchestrate-epic XXXX` -- plan all stories in an epic\n- `\u002Fx-orchestrate-epic XXXX --resume` -- resume planning from last checkpoint\n- `\u002Fx-orchestrate-epic XXXX --story story-XXXX-YYYY` -- plan only a specific story\n\n## CRITICAL EXECUTION RULE\n\n**4 phases (0-3). ALL mandatory. NEVER stop before the final phase.**\n\nAfter each phase 0-2: `>>> Phase N\u002F3 completed. Proceeding to Phase N+1...`\nAfter Phase 3: `>>> Phase 3\u002F3 completed. Epic planning complete.`\n\n## Workflow Overview\n\n```\nPhase 0: PREREQUISITES         -> Parse args, validate epic dir, map, stories (inline)\nPhase 1: DEPENDENCY ORDER      -> Read map, extract phases, order stories (inline)\nPhase 2: PLAN LOOP             -> For each phase, invoke \u002Fx-plan-story per story (subagents)\nPhase 3: REPORT                -> Generate readiness summary, update epic file (inline)\n```\n\n## Input Parsing\n\n### Positional Argument (Required)\n\n| Argument | Format | Required | Description |\n|----------|--------|----------|-------------|\n| `EPIC-ID` | `XXXX` (4-digit zero-padded) | **Mandatory** | The epic identifier, e.g., `0028` |\n\nThe epic ID is a required positional argument. If missing, abort immediately:\n\n```\nERROR: Epic ID is required. Usage: \u002Fx-orchestrate-epic [EPIC-ID] [--resume] [--story story-XXXX-YYYY]\n```\n\n### Optional Flags\n\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--resume` | boolean | `false` | Continue from last checkpoint (skip stories with `planningStatus == \"READY\"`) |\n| `--story story-XXXX-YYYY` | string | (all stories) | Plan only a specific story by ID |\n| `--dry-run` | boolean | `false` | Artifacts written to disk but Steps P1 \u002F P2 \u002F P4 \u002F P5 become no-ops (EPIC-0049 \u002F RULE-007) |\n\n**Mutual exclusivity:** `--resume` and `--story` are mutually exclusive. If both are provided, abort:\n\n```\nERROR: --resume and --story are mutually exclusive. Use only one.\n```\n\n---\n\n## Step P1 — Detect Worktree Context (EPIC-0049 \u002F RULE-001)\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-P1-Worktree-Detect`\n\nInvoke `x-manage-worktrees` in detect-context mode. Result is advisory only — `x-internal-ensure-epic-branch` (Step P2) makes the authoritative decision.\n\n    Skill(skill: \"x-manage-worktrees\", args: \"detect-context\")\n\nContinue on any detect-context failure (fail-open, RULE-006).\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-P1-Worktree-Detect ok`\n\n## Step P2 — Ensure `epic\u002F\u003CID>` Branch (EPIC-0049 \u002F RULE-001)\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-P2-Epic-Branch-Ensure`\n\nUse the resolved `EPIC-ID` argument (`XXXX`).\n\nInvoke `x-internal-ensure-epic-branch` so the canonical `epic\u002F\u003CID>` branch exists locally AND on origin (idempotent):\n\n    Skill(skill: \"x-internal-ensure-epic-branch\", args: \"--epic-id \u003CXXXX>\")\n\nOn failure (non-zero exit), abort with `EPIC_BRANCH_ENSURE_FAILED`. When `--dry-run` is set, skip this step.\n\nThis step runs ONCE at orchestrator entry. Child `\u002Fx-plan-story` invocations in Phase 2 receive `--no-commit` so they do not re-ensure the branch nor issue per-story commits — the wave-level Step P4 below aggregates commits per wave.\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-P2-Epic-Branch-Ensure ok`\n\n---\n\n\u003C!-- phase-no-gate: read-only prerequisite validation; no artifact produced until Phase 1 -->\n## Phase 0 -- Prerequisites (Orchestrator -- Inline)\n\nOpen a phase tracker (close with `TaskUpdate(id: phase0TaskId, status: \"completed\")` after 0.7):\n\n    TaskCreate(subject: \"{epicId} › Phase 0 - Prerequisites\", activeForm: \"Validating epic prerequisites\")\n\n### 0.1 Parse Epic ID\n\nExtract the 4-digit zero-padded epic ID from the positional argument.\n\n- Input: `0028` -> epic ID = `0028`\n- If the argument is not a 4-digit number, abort with format error:\n  ```\n  ERROR: Invalid epic ID format. Expected 4-digit zero-padded number (e.g., 0028).\n  ```\n\n### 0.2 Parse Flags\n\nCheck for `--resume` and `--story` flags. Validate mutual exclusivity.\n\n### 0.3 Resolve Epic Directory\n\nResolve the epic directory using a glob to support suffix variants (e.g., `ai\u002Fepics\u002Fepic-XXXX-title-slug\u002F`):\n\n```bash\n# Resolve epic directory (exact match first, then suffix variant)\nepicDir=$(ls -d ai\u002Fepics\u002Fepic-{epicId}\u002F ai\u002Fepics\u002Fepic-{epicId}-*\u002F 2>\u002Fdev\u002Fnull | head -1)\n```\n\nIf no match is found, abort:\n\n```\nERROR: Directory ai\u002Fepics\u002Fepic-{epicId}\u002F (or suffix variant) not found. Run \u002Fx-epic-decompose first.\n```\n\nUse the resolved `epicDir` path for ALL subsequent reads\u002Fwrites (IMPLEMENTATION-MAP.md, stories, execution-state.json, reports).\n\n### 0.4 Validate Implementation Map\n\nCheck that `IMPLEMENTATION-MAP.md` exists in the epic directory.\n\n```\nERROR: IMPLEMENTATION-MAP.md not found in ai\u002Fepics\u002Fepic-{epicId}\u002F. Run \u002Fx-epic-map first.\n```\n\n### 0.5 Validate Story Files\n\nGlob for `story-XXXX-*.md` files in the epic directory. At least one must exist.\n\n```\nERROR: No story files found matching story-{epicId}-*.md in ai\u002Fepics\u002Fepic-{epicId}\u002F.\n```\n\n### 0.6 Resume Checkpoint Validation (Conditional)\n\nIf `--resume` flag is set, check that `execution-state.json` exists in the epic directory.\n\n```\nERROR: No checkpoint found (execution-state.json missing). Cannot resume. Run without --resume.\n```\n\nIf `--resume` is set and `execution-state.json` exists, load it and apply reclassification:\n\n| Current `planningStatus` | New `planningStatus` | Rationale |\n|--------------------------|----------------------|-----------|\n| `READY` | `READY` | Preserved -- skip this story |\n| `NOT_READY` | `PENDING` | Re-attempt planning |\n| `IN_PROGRESS` | `PENDING` | Interrupted -- reset for retry |\n| `PENDING` | `PENDING` | No change |\n\n### 0.7 Create Plans Directory\n\nCreate `{epicDir}\u002Fplans\u002F` if it does not exist:\n\n```bash\nmkdir -p {epicDir}\u002Fplans\n```\n\nLog: `\"Created plans\u002F directory for EPIC-{epicId}\"` if created. Skip silently if already exists.\n\nPersist interactiveMode to execution-state.json (EPIC-0068 — consumed by Stop hook `enforce-continuous-flow.sh`):\n\n    Skill(skill: \"x-internal-update-status\", args: \"--file {epicDir}\u002Fexecution-state.json --type epic --id \u003CEPIC-ID> --field interactiveMode --value \u003Cinteractive|non-interactive>\")\n\nValue: `\"interactive\"` when `--interactive` passed or `CLAUDE_LEGACY_INTERACTIVE=1`; otherwise `\"non-interactive\"` (Rule 20 default, EPIC-0061).\n\n    TaskUpdate(id: phase0TaskId, status: \"completed\")\n\n>>> Phase 0\u002F3 completed. Proceeding to Phase 1...\n\n---\n\n## Phase 1 -- Dependency Order (Orchestrator -- Inline)\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode pre --skill x-orchestrate-epic --phase Phase-1-Discovery\")\n    TaskCreate(subject: \"{epicId} › Phase 1 - Discovery\", activeForm: \"Resolving story dependency order\")\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-1-Discovery`\n\n### 1.1 Read Implementation Map\n\nRead `{epicDir}\u002FIMPLEMENTATION-MAP.md` and extract phases and dependencies from two sections:\n\n1. **Dependency declarations** from **Section 1 — Dependency Matrix**:\n\n```markdown\n| Story | Título | Chave Jira | Blocked By | Blocks | Status |\n| :--- | :--- | :--- | :--- | :--- | :--- |\n| story-XXXX-0001 | Title | KEY-1 | — | story-XXXX-0002 | Pendente |\n| story-XXXX-0002 | Title | KEY-2 | story-XXXX-0001 | — | Pendente |\n```\n\nParse the `Blocked By` and `Blocks` columns to build the dependency graph.\n\n2. **Phase assignments** from **Section 5 — Resumo por Fase**:\n\n```markdown\n| Fase | Histórias | Camada | Paralelismo | Pré-requisito |\n| :--- | :--- | :--- | :--- | :--- |\n| 0 | story-XXXX-0001 | Domain | 1 paralela | — |\n| 1 | story-XXXX-0002, story-XXXX-0003 | Application | 2 paralelas | Fase 0 concluída |\n| 2 | story-XXXX-0004 | Adapter | 1 paralela | Fase 1 concluída |\n```\n\nParse the `Fase` and `Histórias` columns to determine phase grouping. Extract total phases from the number of distinct `Fase` values.\n\n### 1.2 Order Stories by Phase\n\n1. Group stories by their phase number\n2. Sort phases numerically: Phase 0, Phase 1, Phase 2, ...\n3. Within each phase, stories can be planned in **parallel** (no inter-phase dependencies within the same phase)\n\n### 1.3 Single-Story Mode (Conditional)\n\nIf `--story` flag is provided:\n\n1. Locate the specified story in the implementation map\n2. If not found, abort:\n   ```\n   ERROR: Story {storyId} not found in implementation map.\n   ```\n3. Identify the story's dependencies from the implementation map\n4. Validate that all dependencies have `planningStatus == \"READY\"` in `execution-state.json`:\n   - If `execution-state.json` does not exist, check if dependency story files have existing planning artifacts (tasks file exists at `{epicDir}\u002Fplans\u002Ftasks-story-XXXX-YYYY.md`)\n   - If any dependency is not satisfied, abort:\n     ```\n     ERROR: Dependencies not satisfied for {storyId}: [{unsatisfied deps list}]. Plan dependencies first.\n     ```\n5. If all dependencies are satisfied, set the plan loop to process only this story\n\n### 1.4 Initialize Execution State\n\nIf `execution-state.json` does not exist in `{epicDir}\u002F`, create it using the same top-level schema as `\u002Fx-implement-epic`, adding planning-specific fields under each story entry:\n\n```json\n{\n  \"epicId\": \"XXXX\",\n  \"baseBranch\": \"develop\",\n  \"startedAt\": \"{ISO-8601 timestamp}\",\n  \"totalPhases\": {count},\n  \"stories\": [\n    {\"id\": \"story-XXXX-0001\", \"phase\": 0},\n    {\"id\": \"story-XXXX-0002\", \"phase\": 1}\n  ],\n  \"storyEntries\": {\n    \"story-XXXX-0001\": {\n      \"id\": \"story-XXXX-0001\",\n      \"phase\": 0,\n      \"planningStatus\": \"PENDING\",\n      \"planningStartedAt\": null,\n      \"planningCompletedAt\": null,\n      \"dorVerdict\": null,\n      \"artifacts\": []\n    }\n  }\n}\n```\n\n**Schema compatibility with `\u002Fx-implement-epic`:** The `stories` array and `baseBranch` field match the schema expected by `\u002Fx-implement-epic`. Planning-specific fields (`planningStatus`, `dorVerdict`, `artifacts`) are added under `storyEntries` alongside where `\u002Fx-implement-epic` adds its own fields (`status`, `commitSha`, `prUrl`, etc.). Both skills read\u002Fwrite the same file without conflict.\n\nIf `execution-state.json` already exists (either from `--resume` or prior partial run), preserve existing data and only add `storyEntries` for stories not yet tracked. Never overwrite fields owned by `\u002Fx-implement-epic`.\n\n**Per-story planning fields in `storyEntries`:**\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `id` | String | Yes | Story ID (e.g., `story-0028-0001`) |\n| `phase` | Integer | Yes | Phase number from implementation map |\n| `planningStatus` | String | Yes | `PENDING`, `IN_PROGRESS`, `READY`, `NOT_READY` |\n| `planningStartedAt` | String | When IN_PROGRESS | ISO-8601 timestamp of planning start |\n| `planningCompletedAt` | String | When READY\u002FNOT_READY | ISO-8601 timestamp of planning completion |\n| `dorVerdict` | String | When completed | `READY` or `NOT_READY` from `\u002Fx-plan-story` output |\n| `artifacts` | String[] | When completed | List of generated artifact paths |\n\nLog the execution plan:\n\n```\nEpic Planning -- EPIC-{epicId}\nTotal stories: {count}\nTotal phases: {count}\nMode: {all | resume | single-story}\nExecution order:\n  Phase 0: story-XXXX-0001\n  Phase 1: story-XXXX-0002, story-XXXX-0003\n  Phase 2: story-XXXX-0004\n```\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-1-Discovery ok`\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode post --skill x-orchestrate-epic --phase Phase-1-Discovery --expected-artifacts ai\u002Fepics\u002Fepic-{epicId}\u002Fexecution-state.json\")\n    TaskUpdate(id: phase1TaskId, status: \"completed\")\n\n>>> Phase 1\u002F3 completed. Proceeding to Phase 2...\n\n---\n\n## Phase 2 -- Plan Loop (Orchestrator -- Dispatches Subagents)\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode pre --skill x-orchestrate-epic --phase Phase-2-PlanLoop\")\n    TaskCreate(subject: \"{epicId} › Phase 2 - Plan Loop\", activeForm: \"Orchestrating story planning loop\")\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-2-Story-Orchestration`\n\nExecute planning for each story in dependency order, phase by phase.\n\n### 2.1 Phase-by-Phase Execution\n\nFor each phase (0..N), in order:\n\n```\nFor each phase in (0..totalPhases-1):\n  1. Collect all stories in this phase\n  2. Filter out stories with planningStatus == \"READY\" (already planned)\n  3. For each remaining story in this phase:\n     a. Update execution-state.json: planningStatus = \"IN_PROGRESS\", planningStartedAt = now()\n     b. Dispatch \u002Fx-plan-story via Agent subagent\n     c. Collect DoR verdict from subagent result\n     d. Update execution-state.json with result\n  4. Log phase completion summary\n```\n\n### 2.2 Subagent Dispatch\n\n**CONTEXT ISOLATION: You receive only metadata. Read all files yourself.\nDo NOT expect source code, diffs, or knowledge pack content in this prompt.\nThe subagent reads all story files, KPs, and references independently.**\n\nFor each story to plan, invoke `\u002Fx-plan-story` via the Skill tool.\n\n**Telemetry around per-story dispatch (story-0040-0007 §3.2):** Before each\nsubagent invocation emit a `subagent.start` marker with the story ID as the\nrole; after the subagent returns emit a `subagent.end` marker carrying the\noutcome status. The role value is the full story ID (e.g., `story-0028-0001`)\nso the telemetry analysis can group per-story planning latency:\n\n\u003C!-- TELEMETRY: subagent.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh subagent-start x-orchestrate-epic {storyId}`\n\n**Skill invocation:**\n\n```\nSkill(skill: \"x-plan-story\", args: \"{storyId} --no-commit\")\n```\n\n`--no-commit` is always propagated (EPIC-0049 \u002F RULE-007 batch-commit contract). Each child `x-plan-story` writes artifacts to disk but SKIPS its own P4 commit. The wave-level **Step P4 — Commit Wave Artifacts** (below, added to Phase 2.5) aggregates every story's artifacts + `execution-state.json` + reports into a single commit per wave.\n\n\u003C!-- TELEMETRY: subagent.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh subagent-end x-orchestrate-epic {storyId} ok`\n\nThe skill executes all 6 phases of `\u002Fx-plan-story` (Input Resolution, Context Gathering, Parallel Planning, Consolidation, Artifact Generation, DoR Validation) and returns a result containing the DoR verdict.\n\nIf `\u002Fx-plan-story` is unavailable via the Skill tool, fall back to the Agent tool:\n```\nAgent(prompt: \"\u002Fx-plan-story {storyId} --no-commit\")\n```\n\n**Parallel dispatch within a phase:**\n\nStories within the same phase have no inter-dependencies, so they CAN be dispatched in parallel using multiple Agent calls in a single message. However, to manage context window and memory pressure:\n\n- If the phase contains \u003C= 3 stories: dispatch all in parallel (single message with multiple Agent calls)\n- If the phase contains > 3 stories: dispatch in batches of 3\n\n### 2.3 Collect Results\n\nAfter each subagent completes, extract the DoR verdict from the output:\n\n1. Search the subagent output for the DoR verdict line: `Verdict: **READY**` or `Verdict: **NOT_READY**`\n2. If the verdict cannot be extracted, check for the existence of the DoR file at `{epicDir}\u002Fplans\u002Fdor-story-XXXX-YYYY.md` and read the verdict from it\n3. If neither source provides a verdict, set `planningStatus = \"NOT_READY\"` and log a warning:\n   ```\n   WARNING: Could not extract DoR verdict for {storyId}. Marking as NOT_READY.\n   ```\n\n### 2.4 Update Execution State\n\nAfter each story planning completes, update the story's entry in `storyEntries`:\n\n```json\n{\n  \"id\": \"story-XXXX-YYYY\",\n  \"phase\": N,\n  \"planningStatus\": \"READY\",\n  \"planningStartedAt\": \"2026-04-07T10:00:00Z\",\n  \"planningCompletedAt\": \"2026-04-07T10:05:00Z\",\n  \"dorVerdict\": \"READY\",\n  \"artifacts\": [\n    \"{epicDir}\u002Fplans\u002Ftasks-story-XXXX-YYYY.md\",\n    \"{epicDir}\u002Fplans\u002Fplanning-report-story-XXXX-YYYY.md\",\n    \"{epicDir}\u002Fplans\u002Fdor-story-XXXX-YYYY.md\"\n  ]\n}\n```\n\nMap DoR verdict to planningStatus:\n\n| DoR Verdict | planningStatus |\n|-------------|----------------|\n| `READY` | `READY` |\n| `NOT_READY` | `NOT_READY` |\n| Error\u002Ftimeout | `NOT_READY` |\n\nWrite `execution-state.json` atomically after each story update. This ensures checkpoint consistency even if the process is interrupted.\n\n### 2.5 Phase Completion Log\n\nAfter all stories in a phase are planned:\n\n```\nPhase {N} planning complete:\n  story-XXXX-0001: READY\n  story-XXXX-0002: NOT_READY (3 blockers)\n  Phase {N} result: {passed}\u002F{total} stories READY\n```\n\n### 2.5b Step P4 — Commit Wave Planning Artifacts (EPIC-0049 \u002F RULE-007)\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-P4-Wave-Commit`\n\nIf `--dry-run` is set, log `\"dry-run, skipping commit\"` and skip this step.\n\nAfter all stories in the current wave (phase) have completed planning and `execution-state.json` has been updated, issue a **single consolidated commit** covering:\n\n1. `execution-state.json` (wave-level checkpoint update)\n2. Every story file touched during the wave (Section 8 updates via status flip)\n3. Every planning artifact produced by the wave's stories:\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Ftasks-story-XXXX-YYYY.md`\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Fplanning-report-story-XXXX-YYYY.md`\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Fdor-story-XXXX-YYYY.md`\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Fplan-story-XXXX-YYYY.md` (if present)\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Ftask-TASK-*.md` (v2)\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Fplan-task-TASK-*.md` (v2)\n   - `ai\u002Fepics\u002Fepic-XXXX\u002Fplans\u002Ftask-implementation-map-STORY-*.md` (v2)\n4. Any reports written during the wave (`ai\u002Fepics\u002Fepic-XXXX\u002Freports\u002F**` — added in Phase 3 but may accumulate incrementally).\n\nDelegate to `x-commit-planning`:\n\n    Skill(skill: \"x-commit-planning\",\n          args: \"--scope chore --epic-id \u003CXXXX> --paths ai\u002Fepics\u002Fepic-\u003CXXXX>\u002Fexecution-state.json ai\u002Fepics\u002Fepic-\u003CXXXX>\u002Fstory-\u003CXXXX>-*.md ai\u002Fepics\u002Fepic-\u003CXXXX>\u002Fplans\u002F ai\u002Fepics\u002Fepic-\u003CXXXX>\u002Freports\u002F --subject \\\"planning orchestration cycle (wave \u003CN>)\\\"\")\n\nWhere `\u003CN>` is the current phase number (0-based per Phase 1 — or the wave sequence number when a multi-wave orchestration runs phase-by-phase).\n\nCenario enforced (story-0049-0022): `\"1 commit 'chore(epic-\u003CXXXX>): planning orchestration cycle (wave \u003CN>)' é criado\"` per completed wave.\n\nIdempotency: re-executing with identical inputs produces `commitSha=null` (silent no-op). On `COMMIT_FAILED` (exit 4), abort with the same code.\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-P4-Wave-Commit ok`\n\n### 2.6 Error Handling\n\nIf a subagent fails (throws error, times out, or returns no output):\n\n1. Set `planningStatus = \"NOT_READY\"` for the story\n2. Set `dorVerdict = null`\n3. Log the error:\n   ```\n   ERROR: Planning failed for {storyId}: {error message}\n   ```\n4. Continue with the next story (do NOT abort the entire epic planning)\n\nStories in subsequent phases that depend on a `NOT_READY` story are still planned (planning is about generating artifacts, not about runtime dependencies). The `NOT_READY` status is informational -- it indicates the story may need attention before implementation begins.\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-2-Story-Orchestration ok`\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode post --skill x-orchestrate-epic --phase Phase-2-PlanLoop --expected-artifacts ai\u002Fepics\u002Fepic-{epicId}\u002Fexecution-state.json\")\n    TaskUpdate(id: phase2TaskId, status: \"completed\")\n\n>>> Phase 2\u002F3 completed. Proceeding to Phase 3...\n\n---\n\n## Phase 3 -- Report (Orchestrator -- Inline)\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode pre --skill x-orchestrate-epic --phase Phase-3-Report\")\n    TaskCreate(subject: \"{epicId} › Phase 3 - Report\", activeForm: \"Generating epic planning report\")\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-3-Consolidation`\n\n### 3.1 Generate Readiness Summary\n\nRead the final `execution-state.json` and compute:\n\n| Metric | Calculation |\n|--------|-------------|\n| `stories_planned` | Count of stories with `planningStatus != \"PENDING\"` |\n| `stories_total` | Total number of stories in the epic |\n| `stories_ready` | Count of stories with `planningStatus == \"READY\"` |\n| `stories_not_ready` | Count of stories with `planningStatus == \"NOT_READY\"` |\n| `stories_pending` | Count of stories with `planningStatus == \"PENDING\"` |\n| `overall_status` | See determination table below |\n\n**Overall status determination:**\n\n| Condition | `overall_status` |\n|-----------|------------------|\n| All stories have `planningStatus == \"READY\"` | `READY` |\n| At least one story is `READY` and at least one is `NOT_READY` or `PENDING` | `PARTIALLY_READY` |\n| No stories are `READY` | `NOT_READY` |\n\n### 3.2 Update Epic File\n\nRead the epic file at `{epicDir}\u002FEPIC-XXXX.md` (or `{epicDir}\u002Fepic-XXXX.md` -- case-insensitive glob).\n\nLocate the story index table in Section 5 (or the main story listing). Add or update a `Planning` column:\n\n```markdown\n| # | Story ID | Title | Status | Planning |\n|---|----------|-------|--------|----------|\n| 1 | story-XXXX-0001 | Title | Draft | READY |\n| 2 | story-XXXX-0002 | Title | Draft | NOT_READY |\n| 3 | story-XXXX-0003 | Title | Draft | PENDING |\n```\n\n**Rules for updating the table:**\n\n1. If a `Planning` column already exists, update the values\n2. If no `Planning` column exists, add it as the last column\n3. Preserve all existing columns and data\n4. Only update rows for stories that were planned in this run (preserve existing values for stories not in scope)\n\n### 3.3 Generate Planning Report\n\nWrite a planning summary to `{epicDir}\u002Freports\u002Fepic-planning-report-XXXX.md`:\n\n```markdown\n# Epic Planning Report -- EPIC-{epicId}\n\n> **Epic ID:** EPIC-{epicId}\n> **Date:** {currentDate}\n> **Total Stories:** {stories_total}\n> **Stories Planned:** {stories_planned}\n> **Overall Status:** {overall_status}\n\n## Readiness Summary\n\n| Metric | Count |\n|--------|-------|\n| Stories Total | {stories_total} |\n| Stories Planned | {stories_planned} |\n| Stories Ready (DoR READY) | {stories_ready} |\n| Stories Not Ready (DoR NOT_READY) | {stories_not_ready} |\n| Stories Pending | {stories_pending} |\n\n## Per-Story Results\n\n| # | Story ID | Phase | Planning Status | DoR Verdict | Duration |\n|---|----------|-------|-----------------|-------------|----------|\n| 1 | story-XXXX-0001 | 0 | READY | READY | 45s |\n| 2 | story-XXXX-0002 | 1 | NOT_READY | NOT_READY | 38s |\n| ... | ... | ... | ... | ... | ... |\n\n## Blockers (if any)\n\n{List stories with NOT_READY verdict and their failing DoR checks, if available from the DoR checklist files}\n\n## Generated Artifacts\n\n{List all artifact files generated during this planning run}\n```\n\n### 3.4 Staleness Check for Report (RULE-002)\n\nBefore generating the planning report:\n\n1. Compute report path: `{epicDir}\u002Freports\u002Fepic-planning-report-XXXX.md`\n2. Check if the report file exists:\n   - If NOT found: generate new. Log: `\"Generating planning report for EPIC-{epicId}\"`\n   - If found, compare modification times:\n     - `mtime(execution-state.json) \u003C= mtime(report)` -> reuse existing report. Log: `\"Reusing existing planning report from {date}\"`\n     - `mtime(execution-state.json) > mtime(report)` -> regenerate. Log: `\"Regenerating planning report (execution state modified)\"`\n\n### 3.5 Console Summary\n\nLog the final summary to console:\n\n```\n=== Epic Planning Complete ===\n\nEPIC-{epicId}: {overall_status}\n\n  Stories: {stories_planned}\u002F{stories_total} planned\n  Ready:   {stories_ready}\n  Not Ready: {stories_not_ready}\n  Pending: {stories_pending}\n\n  Report: ai\u002Fepics\u002Fepic-{epicId}\u002Freports\u002Fepic-planning-report-{epicId}.md\n  State:  ai\u002Fepics\u002Fepic-{epicId}\u002Fexecution-state.json\n```\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-3-Consolidation ok`\n\n    Skill(skill: \"x-internal-verify-phase-gates\", model: \"haiku\", args: \"--mode final --skill x-orchestrate-epic --phase Phase-3-Report --expected-artifacts ai\u002Fepics\u002Fepic-{epicId}\u002Freports\u002Fepic-planning-report-{epicId}.md,ai\u002Fepics\u002Fepic-{epicId}\u002Fexecution-state.json\")\n    TaskUpdate(id: phase3TaskId, status: \"completed\")\n\n## Step P5 — Push Epic Branch to Origin (optional, EPIC-0049)\n\n\u003C!-- TELEMETRY: phase.start -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh start x-orchestrate-epic Phase-P5-Push`\n\nIf `--dry-run` is set, log `\"dry-run, skipping push\"` and skip.\n\nDelegate the push of the canonical `epic\u002F\u003CXXXX>` branch to origin:\n\n    Skill(skill: \"x-push-branch\", args: \"--branch epic\u002F\u003CXXXX>\")\n\nOn push failure (remote rejection, no connectivity), log a WARNING and continue — wave commits are preserved locally. Do NOT abort.\n\n\u003C!-- TELEMETRY: phase.end -->\nBash command: `$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Ftelemetry-phase.sh end x-orchestrate-epic Phase-P5-Push ok`\n\n>>> Phase 3\u002F3 completed. Epic planning complete.\n\n---\n\n## Checkpoint\u002FResume Protocol\n\n### Checkpoint Mechanism\n\n`execution-state.json` in `{epicDir}\u002F` serves as the checkpoint file. It is updated atomically after each story completes planning.\n\n### Resume Behavior (`--resume`)\n\nWhen `--resume` is set:\n\n1. Load `execution-state.json` from `{epicDir}\u002F`\n2. Apply reclassification (see Phase 0.6)\n3. Stories with `planningStatus == \"READY\"` are **skipped** (artifacts already generated)\n4. Stories with `planningStatus == \"IN_PROGRESS\"` are **reset to PENDING** (interrupted work)\n5. Stories with `planningStatus == \"NOT_READY\"` are **reset to PENDING** (re-attempt)\n6. Stories with `planningStatus == \"PENDING\"` proceed normally\n7. Enter Phase 2 plan loop with the filtered story set\n\n### Idempotency\n\n- Running `\u002Fx-orchestrate-epic XXXX` twice without `--resume` regenerates all artifacts (full run)\n- Running `\u002Fx-orchestrate-epic XXXX --resume` after a partial run only plans stories not yet `READY`\n- `\u002Fx-plan-story` itself has a staleness check (RULE-002): if source files have not changed, it reuses existing artifacts\n\n---\n\n## Output Artifacts\n\n| Artifact | Path | Produced By |\n|----------|------|-------------|\n| Execution state (checkpoint) | `{epicDir}\u002Fexecution-state.json` | x-orchestrate-epic (this skill) |\n| Epic planning report | `{epicDir}\u002Freports\u002Fepic-planning-report-XXXX.md` | x-orchestrate-epic Phase 3 |\n| Epic file update (Planning column) | `{epicDir}\u002FEPIC-XXXX.md` | x-orchestrate-epic Phase 3 |\n| Task breakdown (per story) | `{epicDir}\u002Fplans\u002Ftasks-story-XXXX-YYYY.md` | x-plan-story (subagent) |\n| Task plans (per task per story) | `{epicDir}\u002Fplans\u002Ftask-plan-TASK-NNN-story-XXXX-YYYY.md` | x-plan-story (subagent) |\n| Planning report (per story) | `{epicDir}\u002Fplans\u002Fplanning-report-story-XXXX-YYYY.md` | x-plan-story (subagent) |\n| DoR checklist (per story) | `{epicDir}\u002Fplans\u002Fdor-story-XXXX-YYYY.md` | x-plan-story (subagent) |\n| Story file update (Section 8) | `{epicDir}\u002Fstory-XXXX-YYYY.md` | x-plan-story (subagent) |\n\n---\n\n## Flat File Naming Convention (RULE-004)\n\nAll output files follow the flat naming convention under `{epicDir}\u002Fplans\u002F`:\n\n```\n{epicDir}\u002F\n  EPIC-XXXX.md\n  IMPLEMENTATION-MAP.md\n  story-XXXX-0001.md\n  story-XXXX-0002.md\n  execution-state.json\n  plans\u002F\n    tasks-story-XXXX-0001.md\n    tasks-story-XXXX-0002.md\n    planning-report-story-XXXX-0001.md\n    planning-report-story-XXXX-0002.md\n    dor-story-XXXX-0001.md\n    dor-story-XXXX-0002.md\n    task-plan-TASK-001-story-XXXX-0001.md\n    task-plan-TASK-002-story-XXXX-0001.md\n  reports\u002F\n    epic-planning-report-XXXX.md\n```\n\n---\n\n## Error Handling\n\n| Error | Action | Recovery |\n|-------|--------|----------|\n| Epic directory not found | Abort with error message | Run `\u002Fx-epic-decompose` first |\n| Implementation map not found | Abort with error message | Run `\u002Fx-epic-map` first |\n| No story files found | Abort with error message | Run `\u002Fx-story-create` first |\n| `execution-state.json` missing on `--resume` | Abort with error message | Run without `--resume` |\n| `--resume` and `--story` both set | Abort with error message | Use only one flag |\n| Story not in implementation map (`--story`) | Abort with error message | Check story ID |\n| Dependencies not satisfied (`--story`) | Abort with error message | Plan dependencies first |\n| Subagent fails for a story | Mark `NOT_READY`, continue | Fix issues, re-run with `--resume` |\n| DoR verdict cannot be extracted | Mark `NOT_READY`, log warning | Check subagent output manually |\n| `x-internal-ensure-epic-branch` fails (Step P2) | Abort with `EPIC_BRANCH_ENSURE_FAILED` | Repair remote state; re-run |\n| `x-commit-planning` exit 4 (Step P4 wave commit) | Abort wave with `COMMIT_FAILED` | Inspect conflict; re-run with `--resume` |\n| `x-commit-planning` exit 0 + `noOp=true` (Step P4) | Silent no-op — continue to next wave | — |\n| `x-push-branch` fails (Step P5) | WARN only; local commits preserved | Operator `git push` manually |\n| `--dry-run` set | Steps P1 \u002F P2 \u002F P4 \u002F P5 become no-ops | Re-run without `--dry-run` to version |\n\n---\n\n## Integration with x-implement-epic\n\nThe `execution-state.json` produced by `\u002Fx-orchestrate-epic` uses the same top-level schema as `\u002Fx-implement-epic` (including `baseBranch`, `stories` array, and `totalPhases`). Planning-specific fields are stored under `storyEntries` alongside implementation fields:\n\n| Field | Used By | Values |\n|-------|---------|--------|\n| `status` | x-implement-epic | `PENDING`, `IN_PROGRESS`, `SUCCESS`, `FAILED`, `PARTIAL`, `BLOCKED` |\n| `planningStatus` | x-orchestrate-epic | `PENDING`, `IN_PROGRESS`, `READY`, `NOT_READY` |\n\nBoth fields coexist on the same story entry in `storyEntries`. `\u002Fx-implement-epic` can use `planningStatus == \"READY\"` as a pre-condition gate before dispatching a story for implementation. Neither skill overwrites fields owned by the other.\n\n---\n\n## Skills Dependency Graph\n\n```\n\u002Fx-orchestrate-epic (this skill)\n  |\n  |-- Step P1: x-manage-worktrees detect-context          (advisory)\n  |-- Step P2: x-internal-ensure-epic-branch           (canonical branch)\n  |-- reads: IMPLEMENTATION-MAP.md (phase\u002Fdependency graph)\n  |-- reads: EPIC-XXXX.md (epic context)\n  |-- reads: story-XXXX-*.md (story files)\n  |-- reads\u002Fwrites: execution-state.json (checkpoint)\n  |\n  +-- per story (subagent): \u002Fx-plan-story --no-commit\n  |     |\n  |     +-- 5 parallel subagents: Architect, QA, Security, Tech Lead, PO\n  |\n  |-- Step P4 (per wave): x-commit-planning            (batch commit per wave)\n  +-- Step P5 (end):      x-push-branch                   (push epic branch)\n```\n\n---\n\n## Constraints\n\n- **Memory management**: Limit parallel subagent dispatch to 3 stories per batch to avoid OOM (each `\u002Fx-plan-story` spawns 5 internal subagents)\n- **Checkpoint atomicity**: Always write `execution-state.json` after each story completes, never batch-update\n- **Staleness check (RULE-002)**: `\u002Fx-plan-story` handles its own staleness check; `\u002Fx-orchestrate-epic` only checks for the planning report\n- **Content language (RULE-006)**: User-facing planning report content in pt-BR; technical fields and log messages in English\n",{"name":5,"model":24,"description":7,"allowed-tools":25,"argument-hint":26,"context-budget":27,"user-invocable":28,"requires-capabilities":29},"sonnet","Read, Write, Edit, Bash, Grep, Glob, Agent, AskUserQuestion, Skill, TaskCreate, TaskUpdate","[EPIC-ID] [--resume] [--story story-XXXX-YYYY] [--dry-run]","heavy",true,[],"main","952a630c6f38d193a349d86fa18db1de8843e837","src\u002Ftest\u002Fresources\u002Fgolden\u002Fjava-spring-fintech-pci\u002F.claude\u002Fskills\u002Fx-orchestrate-epic",1,"https:\u002F\u002Fgithub.com\u002Freview-bench\u002Federcnj_ia-dev-environment","https:\u002F\u002Fgithub.com\u002Freview-bench","https:\u002F\u002Freview-bench.ai","An open benchmark for AI code review.","2026-10-27 06:56:37",{"source":8,"skillName":5,"commands":40,"prompt":50,"zipAvailable":28},[41,44,47],{"tool":42,"command":43},"npx","npx skills add review-bench\u002Federcnj_ia-dev-environment --skill x-orchestrate-epic",{"tool":45,"command":46},"bunx","bunx skills add review-bench\u002Federcnj_ia-dev-environment --skill x-orchestrate-epic",{"tool":48,"command":49},"pnpm","pnpm dlx skills add review-bench\u002Federcnj_ia-dev-environment --skill x-orchestrate-epic","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Freview-bench\u002Federcnj_ia-dev-environment\u002Fblob\u002Fmain\u002Fsrc\u002Ftest\u002Fresources\u002Fgolden\u002Fjava-spring-fintech-pci\u002F.claude\u002Fskills\u002Fx-orchestrate-epic\u002FSKILL.md",[52],{"path":53,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":56,"sourceHtmlUrl":57},"README.md","REFERENCE","参考文档",4666,"https:\u002F\u002Fgithub.com\u002Freview-bench\u002Federcnj_ia-dev-environment\u002Fblob\u002Fmain\u002Fsrc\u002Ftest\u002Fresources\u002Fgolden\u002Fjava-spring-fintech-pci\u002F.claude\u002Fskills\u002Fx-orchestrate-epic\u002FREADME.md",[59,66,73,80,87,94],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M757M8J48TQ1Y3X25GSJBXAS","x-parallel-eval","Detects and classifies file-collision risks between work units (tasks, stories, or epic phases) before parallel execution. Reads ## File Footprint blocks produced by x-task-plan \u002F x-story-plan, applies the parallelism-heuristics knowledge pack (hard \u002F regen \u002F soft categories + hotspot overrides), and emits a collision matrix + serialization recommendation in Markdown (default) or JSON.","https:\u002F\u002Fgithub.com\u002Freview-bench\u002Federcnj_ia-dev-environment\u002Fblob\u002Fmain\u002Fsrc\u002Ftest\u002Fresources\u002Fgolden\u002Fx-parallel-eval\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M757M57XMR9546S69466HDWT","parallelism-heuristics","Canonical catalog of file-collision heuristics for parallel task, story, and epic execution. Defines the File Footprint block format, the three Conflict Categories (hard \u002F regen \u002F soft), a hotspot list of high-contention paths, and the degrade-with-warning policy. Consumed by x-task-plan, x-story-plan, x-epic-map, x-parallel-eval, and x-dev-*-implement.","https:\u002F\u002Fgithub.com\u002Freview-bench\u002Federcnj_ia-dev-environment\u002Fblob\u002Fmain\u002Fsrc\u002Ftest\u002Fresources\u002Fgolden\u002Fparallelism-heuristics\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M757M11SZ8P1VCQABT08QVYA","x-watch-pr-ci","Polls a PR's CI checks and Copilot review status, blocking until checks complete or timeout. Returns one of 8 stable exit codes (SUCCESS=0, CI_PENDING_PROCEED=10, CI_FAILED=20, TIMEOUT=30, PR_ALREADY_MERGED=40, NO_CI_CONFIGURED=50, PR_CLOSED=60, PR_NOT_FOUND=70). Writes a versioned state-file for session resume.","https:\u002F\u002Fgithub.com\u002Freview-bench\u002Federcnj_ia-dev-environment\u002Fblob\u002Fmain\u002Fsrc\u002Ftest\u002Fresources\u002Fgolden\u002Fjava-spring\u002Fplatform-claude-code\u002F.claude\u002Fskills\u002Fx-watch-pr-ci\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M757KW53K8KFPGADFB4PH949","x-validate-docs","Documentation freshness gate: validates 6 dimensions (readme, api-specs, grpc-proto, adr, skill-docs, system-architecture) against code changes in a PR. Stack-aware — only validates targets declared\u002Fauto-detected from ProjectConfig.documentation.targets. Returns exit non-zero on staleness; produces structured report.","https:\u002F\u002Fgithub.com\u002Freview-bench\u002Federcnj_ia-dev-environment\u002Fblob\u002Fmain\u002Fsrc\u002Ftest\u002Fresources\u002Fgolden\u002Fjava-spring\u002Fplatform-claude-code\u002F.claude\u002Fskills\u002Fx-validate-docs\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M757KQZHSA10MKC0CR571D60","x-update-system-architecture","Incrementally updates docs\u002Farchitecture\u002Fsystem.md after an epic completes. Appends new entries to the Decision Log (§11) using x-internal-write-report --append (dedup by ## ID: marker) and surgically inserts component\u002Fintegration changes into sections 1-10 via Edit. Idempotent: re-running with the same epic produces a byte-identical system.md.","https:\u002F\u002Fgithub.com\u002Freview-bench\u002Federcnj_ia-dev-environment\u002Fblob\u002Fmain\u002Fsrc\u002Ftest\u002Fresources\u002Fgolden\u002Fjava-spring\u002Fplatform-claude-code\u002F.claude\u002Fskills\u002Fx-update-system-architecture\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":19},"01M757KKBT5Q1SVF8DMJBVF46M","x-update-architecture","Incrementally updates the service architecture document with changes from architecture plans. Adds new components, integrations, flows, and ADR references without rewriting existing content. Use after implementation to keep architecture documentation current.","https:\u002F\u002Fgithub.com\u002Freview-bench\u002Federcnj_ia-dev-environment\u002Fblob\u002Fmain\u002Fsrc\u002Ftest\u002Fresources\u002Fgolden\u002Fjava-spring\u002Fplatform-claude-code\u002F.claude\u002Fskills\u002Fx-update-architecture\u002FSKILL.md",[],[]]