AGENT SKILL

x-plan-architecture

Generates a comprehensive architecture plan with component diagrams, sequence diagrams, deployment topology, mini-ADRs, NFRs, and resilience/observability strategies. Use before implementation to document design decisions.

License 许可
MIT
最近更新
2026-10-27
Stars
★ 0
Forks
1

01 前言 Front Matter

name
x-plan-architecture
description
Generates a comprehensive architecture plan with component diagrams, sequence diagrams, deployment topology, mini-ADRs, NFRs, and resilience/observability strategies. Use before implementation to document design decisions.
allowed-tools
Read, Write, Edit, Bash, Grep, Glob
argument-hint
[STORY-ID or feature-name]
context-budget
medium
user-invocable
true
requires-capabilities
[]

02 资源文件 1

03 SKILL.md 正文

Global Output Policy

  • Language: English ONLY.
  • Tone: Technical, Direct, and Concise.
  • Efficiency: Remove all conversational fillers and greetings to save tokens.

Skill: Architecture Plan Generator

Purpose

Generates a comprehensive architecture plan for {{PROJECT_NAME}} with component diagrams, sequence diagrams, deployment topology, mini-ADRs, NFRs, and resilience/observability strategies. Use before implementation to document design decisions.

Triggers

  • /x-plan-architecture STORY-ID — generate architecture plan from story
  • /x-plan-architecture "Feature Name" — generate from feature description
  • /x-plan-architecture ai/epics/epic-XXXX/story-XXXX-YYYY.md — generate from story file path

Parameters

Parameter Type Default Values Description
argument String required story ID, feature name, or file path Source for architecture plan generation

Decision Tree

Evaluate the change scope to determine the plan level:

Condition Plan Level
New service / new integration / contract change / infra change Full
New feature, no contract or infra change Simplified
Bug fix / refactor / docs-only Skip

Full Architecture Plan

Apply when any of these conditions is true:

  • New service or module being created
  • New external integration (database, message broker, third-party API)
  • Change to a public contract (REST API, gRPC proto, GraphQL schema, event schema)
  • Infrastructure topology change (new container, new deployment target, new network policy)

Simplified Architecture Plan

Apply when:

  • New feature in an existing service without contract or infrastructure changes
  • Only affected sections are generated (skip unrelated diagrams)

Skip Architecture Plan

Apply when:

  • Bug fix with no architectural impact
  • Internal refactoring (no public API or contract change)
  • Documentation-only change

Workflow

1. PRE-CHECK  -> Verify idempotency (RULE-002)
2. TEMPLATE   -> Load template or use inline fallback (RULE-007)
3. READ       -> Read story/feature requirements
4. EVALUATE   -> Determine plan level (Full/Simplified/Skip)
5. CONTEXT    -> Read knowledge packs
6. REVIEW     -> Review existing architecture
7. GENERATE   -> Generate architecture plan document
8. VALIDATE   -> Verify section completeness

Step 1 — Idempotency Pre-Check (RULE-002 — Idempotency)

Before generating an architecture plan, check whether one already exists and is still fresh.

Pre-Check Algorithm

1. Resolve the expected output path:
   ai/epics/epic-XXXX/plans/architecture-story-XXXX-YYYY.md

2. IF the file does NOT exist:
   - Log: "Generating architecture plan for {story}"
   - Proceed to generation

3. IF the file EXISTS:
   a. Compare modification times:
      - story_mtime = mtime of the story file
      - plan_mtime  = mtime of the architecture plan file
   b. IF story_mtime <= plan_mtime:
      - Log: "Reusing existing architecture plan from {date}"
      - STOP — do NOT regenerate
   c. IF story_mtime > plan_mtime:
      - Log: "Regenerating stale architecture plan for {story}"
      - Proceed to generation

Staleness Decision Table

Condition Action Log Message
Plan does not exist Generate new Generating architecture plan for {story}
Plan exists, story not modified Reuse existing Reusing existing architecture plan from {date}
Plan exists, story modified after plan Regenerate Regenerating stale architecture plan for {story}

Step 2 — Template Loading (RULE-007 — Template Reference)

1. Check if `.claude/templates/_TEMPLATE-ARCHITECTURE-PLAN.md` exists
2. IF template exists:
   - Read the template
   - Use its 13 sections as the required output structure
   - Log: "Using architecture plan template v1.0.0"
3. IF template does NOT exist (RULE-012 fallback):
   - Log WARNING: "Template not found, using inline format"
   - Fall back to the inline Output Structure defined below
   - Execution continues normally — no interruption

Template Fallback: When the template file is missing, the skill degrades gracefully to the inline Output Structure. No interruption occurs. A WARNING is logged.

Step 3 — Read Story/Feature Requirements

Read the story file or feature description provided as argument. Extract: scope, acceptance criteria, integrations, NFRs, constraints.

Step 4 — Evaluate Decision Tree

Determine if this requires a Full Plan, Simplified Plan, or Skip:

  • If Skip: report "Architecture plan not needed for this change" and stop
  • If Full or Simplified: proceed to knowledge pack reading

Step 5 — Read Knowledge Packs

<!-- TELEMETRY: phase.start --> Bash command: $CLAUDE_PROJECT_DIR/.claude/hooks/telemetry-phase.sh start x-plan-architecture Phase-1-KP-Read

Read knowledge packs in order before generating the architecture plan. For Simplified Plan, read only Architecture KP + KPs relevant to affected sections.

<!-- TELEMETRY: phase.end --> Bash command: $CLAUDE_PROJECT_DIR/.claude/hooks/telemetry-phase.sh end x-plan-architecture Phase-1-KP-Read ok

Step 6 — Review Existing Architecture

<!-- TELEMETRY: phase.start --> Bash command: $CLAUDE_PROJECT_DIR/.claude/hooks/telemetry-phase.sh start x-plan-architecture Phase-2-Component-Diagram

  • Check for existing architecture documents in steering/
  • Review current codebase structure to understand the baseline
  • Identify what is new vs. what is changing

<!-- TELEMETRY: phase.end --> Bash command: $CLAUDE_PROJECT_DIR/.claude/hooks/telemetry-phase.sh end x-plan-architecture Phase-2-Component-Diagram ok

Step 7 — Generate Architecture Plan

<!-- TELEMETRY: phase.start --> Bash command: $CLAUDE_PROJECT_DIR/.claude/hooks/telemetry-phase.sh start x-plan-architecture Phase-3-Sequence-Diagrams

Launch a single general-purpose subagent with explicit model: "opus" (Rule 23 RULE-002 — deep architectural reasoning justifies Opus). Generate ALL mandatory sections.

Agent(
  subagent_type: "general-purpose",
  model: "opus",
  description: "Architect generates mandatory sections for architecture plan",
  prompt: "Generate all mandatory sections of the architecture plan per the template loaded above"
)

<!-- TELEMETRY: phase.end --> Bash command: $CLAUDE_PROJECT_DIR/.claude/hooks/telemetry-phase.sh end x-plan-architecture Phase-3-Sequence-Diagrams ok

Step 8 — Validate Sections Post-Generation

<!-- TELEMETRY: phase.start --> Bash command: $CLAUDE_PROJECT_DIR/.claude/hooks/telemetry-phase.sh start x-plan-architecture Phase-4-ADR-Mini

1. Parse the generated document for H2 headings (## Section Name)
2. Count sections found vs. sections expected
3. For each conditional section:
   - IF capability is enabled AND section is missing -> WARNING
   - IF capability is disabled AND section is absent -> OK (conditional skip)
4. For each mandatory section:
   - IF section is missing -> WARNING with instruction to complete
5. Log checklist:
   - All present: "Architecture plan: 13/13 sections present"
   - Some missing: "Architecture plan: X/Y applicable sections present, Z conditional skipped"

<!-- TELEMETRY: phase.end --> Bash command: $CLAUDE_PROJECT_DIR/.claude/hooks/telemetry-phase.sh end x-plan-architecture Phase-4-ADR-Mini ok

Mandatory Sections (13)

# Section Mandatory Conditional
1 Header Yes --
2 Executive Summary Yes --
3 Component Diagram Yes --
4 Sequence Diagrams Yes --
5 Deployment Diagram Yes orchestrator != none
6 External Connections Yes --
7 Architecture Decisions Yes --
8 Technology Stack Yes --
9 Non-Functional Requirements Yes --
10 Data Model Yes database != none
11 Observability Strategy Yes --
12 Resilience Strategy Yes --
13 Impact Analysis Yes --

Conditional Section Rules

  • Deployment Diagram: Include when orchestrator != none. When not applicable, write N/A - capability not enabled.
  • Data Model: Include when database != none. When not applicable, write N/A - capability not enabled.
  • Event Schema: Include when eventDriven: true. When not applicable, write N/A - capability not enabled.

Output Structure

# Section Type Format Description
1 # Architecture Plan — {title} M Markdown H1 Title with story ID or feature name
2 ## Executive Summary M Paragraph One-paragraph overview of the architecture
3 ## Component Diagram M Mermaid graph TD Components, layers, and dependency arrows
4 ## Sequence Diagrams M Mermaid sequenceDiagram Main flows (happy path + primary error path)
5 ## Deployment Diagram M Mermaid graph TD Infrastructure nodes, networking, load balancers
6 ## External Connections M Markdown table System, Protocol, Purpose, SLO columns
7 ## Architecture Decisions M Mini-ADR format Key decisions with Context/Decision/Rationale
8 ## Technology Stack M Markdown table Component, Technology, Version, Rationale columns
9 ## Non-Functional Requirements M Markdown table Metric, Target, Measurement columns
10 ## Data Model O Mermaid erDiagram or table Entities and relationships (if applicable)
11 ## Observability Strategy M Markdown section Key metrics, trace spans, log patterns, alerts
12 ## Resilience Strategy M Markdown section Circuit breakers, retries, fallbacks, degradation
13 ## Impact Analysis M Markdown section Affected services, migration plan, rollback strategy

Minimum mandatory sections: 12 (all M sections).

Output Path

ai/epics/epic-XXXX/plans/arch-story-XXXX-YYYY.md

Where XXXX is the epic ID and YYYY is the story sequence number extracted from the story ID.

Origin Marker (EPIC-0059 — mandatory)

Every generated architecture plan MUST start with a YAML frontmatter block:

---
generated-by: x-plan-architecture@<40-char-git-sha>
generated-at: <ISO-8601-UTC>
story-id: <story-id>
---

Capture the SHA and timestamp at write time:

  • SHA: git rev-parse HEAD 2>/dev/null || echo "unknown"
  • Timestamp: date -u +%Y-%m-%dT%H:%M:%SZ

This frontmatter is required by audit-execution-integrity.sh Phase-1 validation (EPIC-0059, Rule 24). Artifacts without this block fail the CI audit with EIE_EVIDENCE_MISSING.

Mini-ADR Format

Each architectural decision is documented inline using this simplified format:

### ADR-NNN: {Decision Title}

**Status:** Proposed | Accepted | Deprecated | Superseded

**Context:**
{What is the issue or force motivating this decision? 2-3 sentences.}

**Decision:**
{What is the change being proposed or adopted? 1-2 sentences.}

**Rationale:**
{Why was this option chosen over alternatives? List key trade-offs.}

**Consequences:**
- Positive: {benefits}
- Negative: {trade-offs or risks}

**Story Reference:** {STORY-ID}

Rules:

  • Number ADRs sequentially within the document (ADR-001, ADR-002, ...)
  • Each ADR must have a Story Reference linking back to the originating story
  • Status must be one of: Proposed, Accepted, Deprecated, Superseded
  • Context and Decision are mandatory; Consequences may be brief for simple decisions

Subagent Prompt

Launch a single general-purpose subagent with explicit model: "opus" (Rule 23 RULE-002 — deep architectural reasoning justifies Opus):

Agent(
  subagent_type: "general-purpose",
  model: "opus",
  description: "Senior Architect generates architecture plan for project",
  prompt: "<see the blockquote below>"
)

You are a Senior Architect generating a comprehensive architecture plan for {{PROJECT_NAME}}.

Step 1 — Read the template (RULE-007):

  • Read template at .claude/templates/_TEMPLATE-ARCHITECTURE-PLAN.md for required output format
  • If the template file does not exist, use the inline Output Structure defined in this skill as fallback (RULE-012)
  • Log which format source is being used

Step 2 — Read the story/feature requirements:

  • Read the story file or feature description provided as argument
  • Extract: scope, acceptance criteria, integrations, NFRs, constraints

Step 3 — Evaluate the decision tree:

  • Determine if this requires a Full Plan, Simplified Plan, or Skip
  • If Skip: report "Architecture plan not needed for this change" and stop

Step 4 — Read knowledge packs (in order):

  • knowledge/architecture/architecture-principles.md — layer structure, dependency direction
  • knowledge/architecture/architecture-patterns.md — design patterns
  • knowledge/protocols.md — protocol conventions for the project's interfaces
  • knowledge/security/references/ — OWASP, headers, secrets
  • knowledge/observability/references/ — tracing, metrics, logging
  • knowledge/infrastructure.md — Docker, K8s, 12-factor
  • knowledge/resilience/references/ — circuit breaker, retry, fallback
  • knowledge/compliance.md — only if compliance frameworks are active

For Simplified Plan: read only Architecture KP + KPs relevant to affected sections.

Step 5 — Review existing architecture:

  • Check for existing architecture documents in steering/
  • Review current codebase structure to understand the baseline
  • Identify what is new vs. what is changing

Step 6 — Generate the architecture plan with ALL mandatory sections:

  1. Executive Summary — one paragraph overview
  2. Component Diagram — Mermaid graph TD showing layers and dependencies
  3. Sequence Diagrams — Mermaid sequenceDiagram for main flows
  4. Deployment Diagram — Mermaid graph TD with infrastructure nodes
  5. External Connections — table: System | Protocol | Purpose | SLO
  6. Architecture Decisions — mini-ADRs (Context/Decision/Rationale per decision)
  7. Technology Stack — table: Component | Technology | Version | Rationale
  8. Non-Functional Requirements — table: Metric | Target | Measurement
  9. Data Model — erDiagram or table (if applicable, skip if no data changes)
  10. Observability Strategy — key metrics, trace spans, structured log fields, alerts
  11. Resilience Strategy — circuit breakers, retry policies, fallback chains, graceful degradation
  12. Impact Analysis — affected services, migration steps, rollback strategy, risk assessment

Step 7 — Emit origin marker and save the document (EPIC-0059 — mandatory):

Before writing the artifact, prepend the YAML frontmatter block at the very top:

---
generated-by: x-plan-architecture@$(git rev-parse HEAD 2>/dev/null || echo "unknown")
generated-at: $(date -u +%Y-%m-%dT%H:%M:%SZ)
story-id: ${STORY_ID}
---

Then write the full document content after the closing ---. The frontmatter is required by audit-execution-integrity.sh Phase-1 validation (EPIC-0059, Rule 24). Output path:

ai/epics/epic-XXXX/plans/arch-story-XXXX-YYYY.md

Step 8 — Validate sections post-generation:

  • Parse the generated document for all 13 expected sections
  • For conditional sections (Deployment Diagram, Data Model, Event Schema): check project capabilities and mark as "N/A - capability not enabled" if not applicable
  • Log section checklist: "Architecture plan: X/Y sections present"
  • If any mandatory section is missing, log a WARNING with instruction to complete

Conventions:

  • All diagrams MUST use Mermaid syntax
  • All text MUST be in English
  • Mini-ADRs follow the inline format (Context/Decision/Rationale/Consequences/Story Reference)
  • Tables use GitHub-flavored Markdown
  • NFR targets must be measurable (e.g., "p99 latency < 200ms", not "fast")

Knowledge Pack References

# Knowledge Pack Path Purpose
1 Architecture knowledge/architecture/architecture-principles.md Layer structure, dependency direction, package conventions
2 Architecture Patterns knowledge/architecture/architecture-patterns.md Design patterns, CQRS, event sourcing, saga
3 Protocols knowledge/protocols.md REST, gRPC, GraphQL, WebSocket, event-driven conventions
4 Security knowledge/security/references/ OWASP Top 10, security headers, secrets management
5 Observability knowledge/observability/references/ Tracing, metrics, logging, health checks
6 Infrastructure knowledge/infrastructure.md Docker, Kubernetes, 12-factor app
7 Resilience knowledge/resilience/references/ Circuit breaker, retry, fallback, bulkhead
8 Compliance knowledge/compliance.md GDPR, HIPAA, LGPD (if compliance is active)

Minimum KPs for Full Plan: 7 (all except Compliance, which is conditional). Minimum KPs for Simplified Plan: 1 (Architecture only; add others as relevant).

Error Handling

Scenario Action
Story file not found Abort with "Story file not found: {path}"
Template not found Log WARNING, fall back to inline Output Structure (RULE-012)
Knowledge pack not found Log WARNING, continue with available KPs
Subagent fails Abort with error details, suggest manual generation
Post-validation finds missing mandatory section Log WARNING with instruction to complete the section

Integration Notes

Skill Relationship Context
x-implement-story Called by Invoked during Phase 1 for architecture planning; pre-check ensures idempotency
x-model-threats Complements Architecture plan feeds threat model generation
x-implement-task Consumed by Implementation phase reads architecture plan alongside implementation plan
x-update-architecture Followed by After implementation, architecture document is updated incrementally

Detailed References

For in-depth guidance on architecture patterns, consult:

  • knowledge/architecture.md — full architecture reference
  • knowledge/protocols.md — protocol conventions
  • knowledge/security/index.md — security standards
  • knowledge/observability/index.md — observability patterns
  • knowledge/resilience/index.md — resilience patterns
  • knowledge/infrastructure.md — infrastructure patterns

Planning Status Propagation (Rule 22 / EPIC-0046)

V2-gated: only runs when SchemaVersionResolver.resolve(ai/epics/epic-XXXX/execution-state.json) == V2. v1 epics: skip silently (Rule 19).

After writing arch-story-XXXX-YYYY.md, this skill checks the associated story's lifecycle status. The architecture plan does NOT itself drive the Pendente → Planejada transition — that is owned by x-plan-story (Rule 22 single-writer invariant). If the story is still Pendente when the architecture plan is generated standalone (i.e. x-plan-architecture invoked directly without x-plan-story), transition it to Planejada here (idempotent if already Planejada).

Steps (end of architecture-plan generation, BEFORE the final commit):

  1. Detect v2 via SchemaVersionResolver on the epic's execution-state.json. If v1: skip.

  2. Read the story's current status via the CLI:

    CURRENT=$(java -cp $CLAUDE_PROJECT_DIR/java/target/classes \
        dev.iadev.adapter.inbound.cli.StatusFieldParserCli \
        read ai/epics/epic-XXXX/story-XXXX-YYYY.md)
    
  3. If CURRENT == "Pendente", write Planejada:

    java -cp $CLAUDE_PROJECT_DIR/java/target/classes \
        dev.iadev.adapter.inbound.cli.StatusFieldParserCli \
        write ai/epics/epic-XXXX/story-XXXX-YYYY.md Planejada
    

    If CURRENT == "Planejada": idempotent no-op.

  4. Stage both files and commit via x-commit-changes:

    git add ai/epics/epic-XXXX/story-XXXX-YYYY.md ai/epics/epic-XXXX/plans/arch-story-XXXX-YYYY.md
    

    Then:

    Skill(skill: "x-commit-changes", args: "docs(story-XXXX-YYYY): add architecture plan + update status to Planejada")
    

Fail-loud: non-zero exit from CLI → abort skill (RULE-046-08).

04 同仓库更多 Skills

review-bench
review-bench/edercnj_ia-dev-environment

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 / x-story-plan, applies the parallelism-heuristics knowledge pack (hard / regen / soft categories + hotspot overrides), and emits a collision matrix + serialization recommendation in Markdown (default) or JSON.

★ 0
review-bench
review-bench/edercnj_ia-dev-environment

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 / regen / 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.

★ 0
review-bench
review-bench/edercnj_ia-dev-environment

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.

★ 0
review-bench
review-bench/edercnj_ia-dev-environment

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/auto-detected from ProjectConfig.documentation.targets. Returns exit non-zero on staleness; produces structured report.

★ 0
review-bench
review-bench/edercnj_ia-dev-environment

x-update-system-architecture

Incrementally updates docs/architecture/system.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/integration changes into sections 1-10 via Edit. Idempotent: re-running with the same epic produces a byte-identical system.md.

★ 0
review-bench
review-bench/edercnj_ia-dev-environment

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.

★ 0