src/skills/x-plan-story/SKILL.md
Multi-agent story planning: 7 specialized agents produce task breakdown and plans.
npx skillsauth add edercnj/ia-dev-environment x-plan-storyInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
/x-plan-story STORY-ID — plan story with 7 parallel agents
/x-plan-story STORY-ID --force — regenerate even if artifacts are fresh
/x-plan-story STORY-ID --skip-dor — skip Phase 5 DoR validation
/x-plan-story STORY-ID --dry-run — write artifacts but skip subagent/commit steps
/x-plan-story STORY-ID --no-commit — skip commit step (for orchestrators batch-committing)
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| STORY-ID | positional | (required) | story-XXXX-YYYY format |
| --force | boolean | false | Regenerate all artifacts even if fresh |
| --skip-dor | boolean | false | Skip Phase 5 DoR validation |
| --dry-run | boolean | false | Artifacts written but Steps P1/P2/P4/P5 become no-ops |
| --no-commit | boolean | false | Skip commit step; used by orchestrators batching commits at parent level |
CRITICAL: 6 phases (0-5) all mandatory (unless --skip-dor skips Phase 5). Never stop before Phase 5. Print >>> Phase N/5 completed. Proceeding to Phase N+1... after each phase.
Schema dispatch:
| planningSchemaVersion | Phases run |
|--------------------------|------------|
| "2.0" | Phases 0-5 + 4a-4c (v2: task-TASK-NNN.md + plan-task-TASK-NNN.md per task + task-implementation-map-STORY-*.md) |
Artifacts produced:
| Artifact | Path |
|----------|------|
| Story Plan (PRIMARY — v2) | .aikittools/features/feature-XXXX/plans/plan-story-XXXX-YYYY.md |
| Task breakdown | .aikittools/features/feature-XXXX/plans/tasks-story-XXXX-YYYY.md |
| Planning report | .aikittools/features/feature-XXXX/plans/planning-report-story-XXXX-YYYY.md |
| DoR checklist | .aikittools/features/feature-XXXX/plans/dor-story-XXXX-YYYY.md |
| Task files (v2) | .aikittools/features/feature-XXXX/plans/task-TASK-XXXX-YYYY-NNN.md per task |
| Task plans (v2) | .aikittools/features/feature-XXXX/plans/plan-task-TASK-XXXX-YYYY-NNN.md per task |
| Task map (v2) | .aikittools/features/feature-XXXX/plans/task-implementation-map-STORY-XXXX-YYYY.md |
Phase execution with telemetry:
Step P1 (Worktree Detect): Skill(skill: "x-manage-worktrees", args: "detect-context") — advisory, fail-open. Skip when --no-commit.
Step P2 (Feature Branch Ensure): Skill(skill: "x-internal-ensure-feature-branch", args: "--feature-id <XXXX>") — idempotent. Abort on failure with FEATURE_BRANCH_ENSURE_FAILED. Skip when --no-commit or --dry-run.
Phase 1 (Context Gathering): Read story, feature, implementation map, and existing plan artifacts inline. Also read the knowledge pack planning-standards-ra9 (src/knowledge/shared/governance-baselines/planning-standards-ra9/knowledge.md) (RA9 contract: 9 sections, Packages format, Decision Rationale micro-template). Resolve canonical packs with a story-scoped capability set (anti-inflation):
Start from architecture,security.
Add runtime/language capability only when evidenced by repository/story scope (for example: java).
Add api,database,events,devops,observability,performance,compliance only when the story/feature explicitly requires those domains.
Never widen capabilities "just in case".
Skill(skill: "x-internal-select-context-packs", args: "--phase plan --capabilities <story-scoped-capabilities>") Skill(skill: "x-internal-select-knowledge", args: "--kind technical --phase plan --capabilities <story-scoped-capabilities>")
Treat x-internal-select-context-packs (patterns) and x-internal-select-knowledge (technical knowledge) as the canonical sources — union their required/recommended buckets. Read every required path returned by both selectors and append only scope-relevant recommended packs. Do not maintain parallel hardcoded pack lists. See staleness check and context-combination matrix in references.
Tech Context Extraction (story-scoped — anti-inflation):
After x-internal-select-context-packs, extract the technology context filtered for this story's capabilities:
Skill(skill: "x-internal-evaluate-tech-context",
args: "--phase plan --capabilities <story-scoped-capabilities>")
From the response, build a STORY_TECH_SNIPPET to inject into the Architect subagent:
techProfile.technology fields to only those relevant to the resolved story-scoped-capabilities:
java capability active → include: backend, architectureStyledatabase capability active → include: database, dataOwnership, cache, cacheInteractionapi capability active → include: apiProtocol, integrationProfile, auth, authz, rateLimitingevents capability active → include: messageBroker, asyncJobs, sagaPatternsecurity capability active → include: auth, authz, secretsProvider, compliance, auditTrailobservability capability active → include: observability, observabilityDepthdevops capability active → include: cicd, rollout, resilienceStrategyreferences/full-protocol.md §Layer Tech Guidance.selectedAssets.required paths as STORY_PATTERN_REFS.techProfile.inputsUsed.config = false → log WARNING: tech-context.config.json not found and set STORY_TECH_SNIPPET = null.STORY_TECH_SNIPPET format (injected verbatim into Architect subagent prompt):
## TECH_CONTEXT_SNIPPET (use to populate Section 1.5 of plan-story-*.md):
Active stack: {backend}
Architecture style: {architectureStyle}
Active technology decisions for this story scope:
{filtered_fields as key: value list}
Layer conventions (from canonical table in full-protocol.md §Layer Tech Guidance):
{LAYER_CONVENTIONS as Camada | Stack | Convenção Principal table}
Canonical assets (populate Section 1.5 §Assets Canônicos):
{STORY_PATTERN_REFS as bullet list}
RA9 guidance (knowledge pack
planning-standards-ra9): When producing the consolidated plan, the Architect subagent MUST fill:
- Section 2 (Packages Hexagonal): Feature-level packages in each hexagonal layer from the story analysis.
- Section 8 (Decision Rationale): At least 1 feature-level decision using the 4-line micro-template.
Phase 2 (Parallel Planning): Dispatch 7 subagents in a single message (Rule 13 Pattern 2 — SUBAGENT-GENERAL) for true parallelism.
TASK_PROPOSAL mandatory metadata fields (v2):
Each TASK_PROPOSAL entry MUST include these new fields alongside the standard ones:
| Field | Values | Description |
|-------|--------|-------------|
| layer | domain | adapter-inbound | adapter-outbound | infrastructure | testing | cross-cutting | Hexagonal layer this task belongs to |
| parallel-group | string (e.g. "domain", "adapters", "testing") | Tasks in the same parallel-group with no deps between them CAN be executed in parallel |
| expects-reviews | list of specialist roles (e.g. ["java-developer", "security-engineer"]) | Specialists that must review this task's implementation before code-review gate |
These fields are used by:
x-implement-story to group tasks by layer for wave-based executionx-evaluate-parallelism to detect collision risks between parallel tasksx-review-specialist to load the right reviewer based on expects-reviewsDispatch all 7 in ONE assistant message:
Agent(subagent_type: "architect", model: "opus", description: "Architect planning for story {STORY_ID}", prompt: "Read context files. If `docs/architecture/architecture-decisions-backend.md` exists, read it and extract the full 'Patterns e Knowledge Obrigatórios' section — use every pattern/knowledge path listed there as mandatory references when proposing architectural decisions and task breakdowns; reference them explicitly in TASK_PROPOSAL entries. Analyze story {STORY_ID}. Produce TASK_PROPOSAL entries (architecture, layers, dependencies). Follow TASK_PROPOSAL format in references/full-protocol.md. Additionally produce five extra blocks used by Phase 4d: (1) NARRATIVE_OVERVIEW: 3-6 paragraphs in plain language describing WHAT will be built, WHY, and HOW, referencing concrete file paths; (2) ARTIFACT_IMPACT: for each file in the story scope list the path, action (CREATE/MODIFY/DELETE), current state (if modifying), description of the change, and reason; (3) COMPONENT_DIAGRAM: a Mermaid classDiagram or flowchart marking each component as NEW, MOD, or DEL with their relationships; (4) INTERFACE_CONTRACTS: for each interface, port, use case, or controller being created or modified — organized by hexagonal layer (Domain, Application, Adapter Inbound, Adapter Outbound, Infrastructure) — provide the full method signature(s), parameter types, return type, and declared exceptions as a Markdown table; (5) SEQUENCE_DIAGRAM: a Mermaid sequenceDiagram showing the primary happy-path flow between layers (e.g. Controller → UseCase → Port → Adapter), including method calls, messages, and return values — this diagram is used to populate Section 2.6.3 of the story plan. Additionally, (6) TECH_CONTEXT_SECTION: using the STORY_TECH_SNIPPET provided below, populate Section 1.5 of plan-story-*.md — the section has three subsections: (a) Decisões Ativas para este Escopo table (filter and list only the active tech decisions for this story scope, one row per domain); (b) Convenções de Camada table (use the layer conventions from STORY_TECH_SNIPPET to populate each hexagonal layer row); (c) Assets Canônicos Ativos (bullet list of STORY_PATTERN_REFS from STORY_TECH_SNIPPET). If STORY_TECH_SNIPPET is null, write 'N/A — tech-context.config.json não encontrado.' for all three subsections.\n\n{STORY_TECH_SNIPPET}")
Agent(subagent_type: "qa-engineer", model: "sonnet", description: "QA planning for story {STORY_ID}", prompt: "Read context files. Produce TASK_PROPOSAL entries (tests, coverage, acceptance criteria). Follow TASK_PROPOSAL format in references/full-protocol.md. Additionally produce: (1) GHERKIN_SCENARIOS: full Gherkin scenarios covering at minimum Degenerate, Happy Path, Error/Boundary, and Security categories; (2) TDD_CYCLES: for each cycle in TPP order (nil → constant → scalar → conditional → collection → complex) describe in plain language the test to write (RED), why it fails, the minimum implementation (GREEN), and what to refactor — each cycle MUST include a 'Spec ref' annotation pointing to the interface/method from INTERFACE_CONTRACTS that the cycle verifies; (3) EXISTING_TESTS_IMPACT: scan the existing test files and list ALL tests that cover components being modified or deleted — for each: file path, method name, reason for change, and what assertion changes.")
Agent(subagent_type: "security-engineer", model: "sonnet", description: "Security planning for story {STORY_ID}", prompt: "Read required/recommended security assets selected by `x-internal-select-context-packs` for phase `plan`, plus context files. Produce TASK_PROPOSAL entries (security, OWASP, threat model). Follow TASK_PROPOSAL format in references/full-protocol.md.")
Agent(subagent_type: "pentest-engineer", model: "sonnet", description: "Pentest planning for story {STORY_ID}", prompt: "Read capabilities/quality/pentest/pentest-always-on.yaml and context files. Produce TASK_PROPOSAL entries (pentest scenarios, CVSS-rated vulnerabilities, exploitation paths). Follow TASK_PROPOSAL format in references/full-protocol.md.")
Agent(subagent_type: "tech-lead", model: "sonnet", description: "Tech Lead planning for story {STORY_ID}", prompt: "Read context files. Produce TASK_PROPOSAL entries (code quality, SOLID, complexity). Follow TASK_PROPOSAL format in references/full-protocol.md.")
Agent(subagent_type: "product-owner", model: "sonnet", description: "PO planning for story {STORY_ID}", prompt: "Read compliance assets selected by `x-internal-select-context-packs` for phase `plan`, plus context files. Produce TASK_PROPOSAL entries (business value, acceptance, DoD, compliance). Follow TASK_PROPOSAL format in references/full-protocol.md.")
Agent(subagent_type: "performance-engineer", model: "sonnet", description: "Performance planning for story {STORY_ID}", prompt: "Read context files. Produce TASK_PROPOSAL entries (latency SLAs, throughput targets, load testing scenarios). Follow TASK_PROPOSAL format in references/full-protocol.md.")
Phase 3 (Consolidation): Merge all TASK_PROPOSAL entries using deterministic rules (majority-vote, duplicate elimination, dependency ordering). See consolidation algorithm in references.
Phase 4 (Artifact Generation): Write tasks-story-*.md and planning-report-*.md. v2 only: Phases 4a-4c emit per-task artifacts and task map (see references).
Phase 4b (v2 only — batch task-plan dispatch): For each TASK-XXXX-YYYY-NNN, invoke x-plan-task in parallel (batch ≤ 4) with --no-commit so the caller aggregates into a single Step P4 commit:
Skill(skill: "x-plan-task",
args: "--task-file .aikittools/features/feature-XXXX/plans/task-TASK-XXXX-YYYY-NNN.md --no-commit")
Phase 4d (v2 only — Story Plan — PRIMARY artifact): Using Architect and QA subagent outputs from Phase 2 (NARRATIVE_OVERVIEW, ARTIFACT_IMPACT, COMPONENT_DIAGRAM, INTERFACE_CONTRACTS, SEQUENCE_DIAGRAM, GHERKIN_SCENARIOS, TDD_CYCLES, EXISTING_TESTS_IMPACT, TECH_CONTEXT_SECTION) plus the consolidated task list from Phase 3, generate plan-story-XXXX-YYYY.md using _TEMPLATE-STORY-PLAN.md.
Idempotency: reuse if mtime(story) <= mtime(plan-story) and --force is absent. Log: "Reusing existing story plan". Regenerate if stale or --force.
The plan MUST include:
Section 1 (Visão Geral): Architect NARRATIVE_OVERVIEW verbatim — plain-language description readable by humans without other documents.
Section 1.5 (Contexto Tecnológico da Story): Architect TECH_CONTEXT_SECTION — three subsections: (a) Decisões Ativas para este Escopo, (b) Convenções de Camada, (c) Assets Canônicos Ativos. If STORY_TECH_SNIPPET was null, all subsections contain "N/A — tech-context.config.json não encontrado."
Section 2 (Escopo da Mudança): Architect ARTIFACT_IMPACT per file (verbal description of current state, change, reason) + COMPONENT_DIAGRAM (Mermaid classDiagram or flowchart with NEW/MOD/DEL markers).
Section 2.6 (Especificação Formal de Interfaces): Architect INTERFACE_CONTRACTS as table per hexagonal layer (2.6.1) + data schema derived from ARTIFACT_IMPACT (2.6.2) + SEQUENCE_DIAGRAM (2.6.3) + pre/postconditions per operation derived from story Section 4 ACs (2.6.4). If story has no structural interfaces, write "N/A" in each sub-section with justification.
Section 3.1 (Gherkin): QA GHERKIN_SCENARIOS — minimum 4 categories (Degenerate, Happy, Error, Security).
Section 3.2 (Testes Impactados): QA EXISTING_TESTS_IMPACT — tables for tests to modify, delete, and new regression tests needed. If none: write explicitly "Nenhum teste existente é impactado".
Section 3.3 (TDD Cycles): QA TDD_CYCLES in TPP order with plain-language RED/GREEN/REFACTOR descriptions. Each cycle MUST include the Spec ref annotation pointing to the interface/method from Section 2.6.1.
Section 4 (Tasks): CODE_TASKS from Phase 3, organized by hexagonal layer using the layer field from TASK_PROPOSAL entries, plus mandatory code-review task (always last) + mandatory documentation task. The code-review task MUST always be present — never omit.
Task organization by layer (Section 4 structure):
Group tasks under layer headings: ### Domain Layer, ### Adapter Inbound Layer, ### Adapter Outbound Layer, ### Infrastructure Layer, ### Testing, ### Cross-Cutting. Only emit headings for layers with tasks. Each task entry includes parallel-group and expects-reviews metadata in its frontmatter block.
parallel-group annotation format:
> ⚡ parallel-group: {parallel-group} | expects-reviews: {expects-reviews}
This annotation appears after the task title so x-evaluate-parallelism can parse it.
mandatory code-review task format (always the LAST task in Section 4):
**TASK-XXXX-YYYY-{LAST_N} | Revisão de Código por Especialistas e Tech Lead**
- **task-type:** code-review
- **Status:** Pendente
- **Descrição:** Revisão holística de toda a implementação da história.
Especialistas revisam contra `docs/architecture/application-patterns.md` (quando disponível),
identificando quebras de pattern em toda a base de código impactada.
Tech Lead emite relatório consolidado com verdict GO/NO-GO/GO-WITH-RESERVATIONS,
incluindo seção "Cobertura de Patterns" e "Reservas Permitidas" (se aplicável).
- **DoD:** `review-tech-lead-story-XXXX-YYYY.md` existe com `decision: GO` ou `decision: GO-WITH-RESERVATIONS`.
- **Note:** This task is dispatched by `x-implement-story` as Phase 2.R — it invokes
`x-review-specialist` + `x-review-tech-lead` in sequence. Do NOT implement via `x-implement-task`.
Application patterns context (MANDATORY when
docs/architecture/application-patterns.mdexists): Check fordocs/architecture/application-patterns.mdbefore generating Section 4. If the file exists, reference it explicitly in the code-review task description: "Reviewers MUST cross-check all patterns listed indocs/architecture/application-patterns.md." If absent: omit the reference (no mention of a missing file in task descriptions).
Section 5 (Critérios de Conclusão): verbatim from template — how executor marks tasks and story as Concluída.
Section 6 (Riscos): consolidated risk matrix from all agents.
Stage plan-story-XXXX-YYYY.md for inclusion in the Step P4 batch commit.
Phase 5 (DoR Validation): Run 13 checks; v2 adds per-task READY checks. Skipped with --skip-dor.
Check 13 (v2 only): plan-story-XXXX-YYYY.md exists and all 7 sections are populated (no empty placeholders in Sections 1-6).
Check 14 (v2 only): Section 2.6 is populated — at minimum, Section 2.6.1 has at least one interface entry OR contains an explicit "N/A" justification. Empty Section 2.6 (placeholder-only) fails this check with RA9_SPEC_NOT_ECHOED.
Check 15 (v2 only): Section 1.5 is populated — at minimum contains the "Decisões Ativas" table with at least one non-placeholder row, OR contains explicit "N/A — tech-context.config.json não encontrado." text. Placeholder-only Section 1.5 fails with RA9_TECH_CONTEXT_NOT_PROPAGATED.
If --dry-run is set, log "dry-run, skipping commit" and skip this step. If --no-commit is set, skip as well — the caller owns the commit boundary and aggregates planning commits.
Otherwise, issue ONE consolidated commit covering every planning artifact produced by this story (task breakdown, planning report, DoR checklist, plan-story, all task files, all plan-task files, task map, and the updated execution-state.json):
Skill(skill: "x-commit-planning",
args: "--scope docs --feature-id <XXXX> --paths .aikittools/features/feature-<XXXX>/plans/ .aikittools/features/feature-<XXXX>/execution-state.json --subject \"docs(story-<XXXX>-<YYYY>): add planning artifacts\"")
Idempotency: re-executing with identical inputs returns commitSha=null (silent no-op). On COMMIT_FAILED (exit 4), abort with the same code.
If --dry-run or --no-commit is set, log "dry-run, skipping push" and skip this step.
Otherwise, delegate the push to x-push-branch so the canonical feature/<XXXX> branch is synchronized with origin:
Skill(skill: "x-push-branch", args: "--branch feature/<XXXX>")
On push failure (remote rejection, no connectivity), log a WARNING and continue — the local commit is preserved; the operator can re-run Step P5 or git push manually. Do NOT abort.
| Code | Condition |
|------|-----------|
| STORY_NOT_FOUND | Story file absent at .aikittools/features/feature-XXXX/story-XXXX-YYYY.md |
| FEATURE_BRANCH_ENSURE_FAILED | Step P2 x-internal-ensure-feature-branch non-zero |
| CONSOLIDATION_FAILED | No TASK_PROPOSAL entries returned by any subagent |
| WRITE_FAILED | Unable to write output artifact to .aikittools/features/feature-XXXX/plans/ |
| DOR_NOT_MET | DoR validation returns < 13/13 checks passed (v2) or < 12/12 (v1) |
Complete per-phase detail (Phase 0 input resolution, staleness check, context-combination table, TASK_PROPOSAL format, consolidation algorithm with deterministic merge rules, Phase 3 conflict resolution, Phase 4 artifact templates, v2 Phases 4a–4c task-file-first execution, x-plan-task delegation per task, Phase 5 12-check DoR validation, commit conventions) and planning-guide reference in
references/full-protocol.md. Existingreferences/planning-guide.mdpreserved per story-0054-0003 audit.
development
Documentation freshness gate: validates 6 dimensions (readme, api, adr, etc.) per PR.
testing
Conditional dep-policy gate: CVEs, licenses, versions, freshness; SARIF + report.
documentation
Incrementally updates the service or system architecture document; never regenerative.
development
Scans code and git history for leaked credentials, API keys, and tokens; SARIF output.