Agent Skills › shinpr/claude-code-workflows

shinpr/claude-code-workflows

GitHub

提供AI开发技术决策准则、反模式检测及调试技巧。用于识别代码与设计反模式,执行严格的质量检查,并指导基于Fail-Fast原则的错误处理与回退设计,确保系统可靠性。

115 skills 554

Install All Skills

npx skills add shinpr/claude-code-workflows --all -g -y
More Options

List skills in collection

npx skills add shinpr/claude-code-workflows --list

Skills in Collection (115)

提供AI开发技术决策准则、反模式检测及调试技巧。用于识别代码与设计反模式,执行严格的质量检查,并指导基于Fail-Fast原则的错误处理与回退设计,确保系统可靠性。
进行技术架构或代码决策时 检测代码异味或反模式时 执行代码质量保证审查时 设计错误处理与回退机制时
dev-skills/skills/ai-development-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill ai-development-guide -g -y
SKILL.md
Frontmatter
{
    "name": "ai-development-guide",
    "description": "Technical decision criteria, anti-pattern detection, debugging techniques, and quality check workflow. Use when making technical decisions, detecting code smells, or performing quality assurance."
}

AI Developer Guide - Technical Decision Criteria and Anti-pattern Collection

Technical Anti-patterns (Red Flag Patterns)

Immediately stop and reconsider design when detecting the following patterns:

Code Quality Anti-patterns

  1. Writing similar code 3 or more times - Violates Rule of Three
  2. Multiple responsibilities mixed in a single file - Violates Single Responsibility Principle (SRP)
  3. Defining same content in multiple files - Violates DRY principle
  4. Making changes without checking dependencies - Potential for unexpected impacts
  5. Disabling code with comments - Should use version control
  6. Error suppression - Hiding problems creates technical debt
  7. Bypassing safety mechanisms (type systems, validation, contracts) - Circumventing language's correctness guarantees

Design Anti-patterns

  • "Make it work for now" thinking - Accumulation of technical debt
  • Patchwork implementation - Unplanned additions to existing code
  • Optimistic implementation of uncertain technology - Designing unknown elements assuming "it'll probably work"
  • Symptomatic fixes - Surface-level fixes that don't solve root causes
  • Unplanned large-scale changes - Lack of incremental approach

Fail-Fast Fallback Design Principles

Core Principle

Make all errors visible and traceable with full context. Prioritize primary code reliability over fallback implementations. Excessive fallback mechanisms mask errors and make debugging difficult.

Implementation Guidelines

Default Approach

  • Propagate all errors explicitly unless a Design Doc specifies a fallback
  • Make failures explicit: Errors should be visible and traceable
  • Preserve error context: Include original error information when re-throwing

When Fallbacks Are Acceptable

  • Only with explicit Design Doc approval: Document why fallback is necessary
  • Business-critical continuity: When partial functionality is better than none
  • Graceful degradation paths: Clearly defined degraded service levels

Layer Responsibilities

  • Infrastructure Layer:

    • Always throw errors upward
    • No business logic decisions
    • Provide detailed error context
  • Application Layer:

    • Make business-driven error handling decisions
    • Implement fallbacks only when specified in requirements
    • Log all fallback activations for monitoring

Error Masking Detection

Review Triggers (require design review):

  • Writing 3rd error handler in the same feature
  • Multiple error handling blocks in single function/method
  • Nested error handling structures
  • Error handlers that return default values without logging

Before Implementing Any Fallback:

  1. Verify Design Doc explicitly defines this fallback
  2. Document the business justification
  3. Ensure error is logged with full context
  4. Add monitoring/alerting for fallback activation

Implementation Pattern

AVOID: Silent fallback that hides errors
    <handle error>:
        return DEFAULT_VALUE  // Error hidden, debugging impossible

PREFERRED: Explicit failure with context
    <handle error>:
        log_error('Operation failed', context, error)
        <propagate error>  // Re-throw exception, return Error, return error tuple

Adaptation: Use language-appropriate error handling (exceptions, Result types, error tuples, etc.)

Rule of Three - Criteria for Code Duplication

How to handle duplicate code based on Martin Fowler's "Refactoring":

Duplication Count Action Reason
1st time Inline implementation Cannot predict future changes
2nd time Consider future consolidation Pattern beginning to emerge
3rd time Implement commonalization Pattern established

Criteria for Commonalization

Cases for Commonalization

  • Business logic duplication
  • Complex processing algorithms
  • Areas likely requiring bulk changes
  • Validation rules

Cases to Avoid Commonalization

  • Accidental matches (coincidentally same code)
  • Possibility of evolving in different directions
  • Significant readability decrease from commonalization
  • Simple helpers in test code

Common Failure Patterns and Avoidance Methods

Pattern 1: Error Fix Chain

Symptom: Fixing one error causes new errors Cause: Surface-level fixes without understanding root cause Avoidance: Identify root cause with 5 Whys before fixing

Pattern 2: Circumventing Correctness Guarantees

Symptom: Bypassing safety mechanisms (type systems, validation, contracts) Cause: Impulse to avoid correctness errors Avoidance: Use language-appropriate safety mechanisms (static checking, runtime validation, contracts, assertions)

Pattern 3: Implementation Without Sufficient Testing

Symptom: Many bugs after implementation Cause: Ignoring Red-Green-Refactor process Avoidance: Always start with failing tests

Pattern 4: Ignoring Technical Uncertainty

Symptom: Frequent unexpected errors when introducing new technology Cause: Assuming "it should work according to official documentation" without prior investigation Avoidance:

  • Record certainty evaluation at the beginning of task files
    Certainty: low (Reason: no working examples found for this integration)
    Exploratory implementation: true
    Fallback: use established alternative approach
    
  • For low certainty cases, create minimal verification code first

Pattern 5: Insufficient Existing Code Investigation

Symptom: Duplicate implementations, architecture inconsistency, integration failures, adopting outdated patterns Cause: Insufficient understanding of existing code before implementation; referencing only nearby files without verifying representativeness Avoidance Methods:

  • Before implementation, always search for similar functionality (using domain, responsibility, configuration patterns as keywords)
  • Similar functionality found → Use that implementation (do not create new implementation)
  • Similar functionality is technical debt → Create ADR improvement proposal before implementation
  • No similar functionality exists → Implement new functionality following existing design philosophy
  • Record all decisions and rationale in "Existing Codebase Analysis" section of Design Doc
  • Reference representativeness check: When adopting a pattern or dependency from nearby code, verify it is representative across the repository before adopting — nearby files alone are an insufficient basis

Debugging Techniques

1. Error Analysis Procedure

  1. Read error message (first line) accurately
  2. Focus on first and last of stack trace
  3. Identify first line where your code appears

2. 5 Whys - Root Cause Analysis

Trace the failure through repeated "why" questions until the root cause is actionable.

3. Minimal Reproduction Code

To isolate problems, attempt reproduction with minimal code:

  • Remove unrelated parts
  • Replace external dependencies with mocks
  • Create minimal configuration that reproduces problem

4. Debug Log Output

Include operation context, relevant input data, current state, and timestamp.

Quality Assurance Mechanism Awareness

Before executing quality checks, identify what quality mechanisms exist for the change area:

  • Primary detection: inspect the change area's file types, project manifest, and configuration to identify applicable quality tools
    • Check CI pipeline definitions for checks that cover the affected paths
    • Check for domain-specific linter or validator configurations (e.g., schema validators, API spec validators, configuration file linters)
    • Check for domain-specific constraints in project configuration (naming rules, length limits, format requirements)
  • Supplementary hint: IF task file specifies Quality Assurance Mechanisms → use them as additional hints for which domain-specific checks to look for
  • Include discovered domain-specific checks alongside standard quality phases below

Quality Check Workflow

Universal quality assurance phases applicable to all languages:

Phase 1: Static Analysis

  1. Code Style Checking: Verify adherence to style guidelines
  2. Code Formatting: Ensure consistent formatting
  3. Unused Code Detection: Identify dead code and unused imports/variables
  4. Static Type Checking: Verify type correctness (for statically typed languages)
  5. Static Analysis: Detect potential bugs, security issues, code smells

Phase 2: Build Verification

  1. Compilation/Build: Verify code builds successfully (for compiled languages)
  2. Dependency Resolution: Ensure all dependencies are available and compatible
  3. Resource Validation: Check configuration files, assets are valid

Phase 3: Testing

  1. Unit Tests: Run all unit tests
  2. Integration Tests: Run integration tests
  3. Test Coverage: Measure and verify coverage meets standards
  4. E2E Tests: Run end-to-end tests

Phase 4: Final Quality Gate

All checks must pass before proceeding:

  • Zero static analysis errors
  • Build succeeds
  • All tests pass
  • Coverage meets project-configured threshold

Quality Check Pattern (Language-Agnostic)

Workflow:
1. Format check → 2. Lint/Style → 3. Static analysis →
4. Build/Compile → 5. Unit tests → 6. Coverage check →
7. Integration tests → 8. Final gate

Auto-fix capabilities (when available):
- Format auto-fix
- Lint auto-fix
- Dependency/import organization
- Simple code smell corrections

Situations Requiring Technical Decisions

Timing of Abstraction

  • Extract patterns after writing concrete implementation 3 times
  • Be conscious of YAGNI, implement only currently needed features
  • Prioritize current simplicity over future extensibility

Performance vs Readability

  • Prioritize readability unless profiling identifies a measurable bottleneck (e.g., response time exceeding SLA, memory exceeding allocation)
  • Measure before optimizing
  • Document reason with comments when optimizing

Granularity of Contracts and Interfaces

  • Overly detailed contracts reduce maintainability
  • Design interfaces where each method maps to a single domain operation and parameter types use domain vocabulary
  • Use abstraction mechanisms to reduce duplication

Scope Expansion

  • Apply implementation/edit instructions to the user's or task's specified scope. Escalate before expanding it.
  • Treat explicit quantities and targets ("one", "this file", "only X") as boundaries
  • Copy/move/mirror requests preserve content verbatim; edit content only when requested
  • Port/translation requests preserve intent and behavior; adapt only what the destination context requires
  • Before changing related files, symmetric locations, adjacent behavior, or adding helpful extras, escalate with the proposed expansion

Implementation Completeness Assurance

Impact Analysis: Mandatory 3-Stage Process

Complete these stages sequentially before any implementation:

1. Discovery - Identify all affected code:

  • Implementation references (imports, calls, instantiations)
  • Interface dependencies (contracts, types, data structures)
  • Test coverage
  • Configuration (build configs, env settings, feature flags)
  • Documentation (comments, docs, diagrams)

2. Understanding - Analyze each discovered location:

  • Role and purpose in the system
  • Dependency direction (consumer or provider)
  • Data flow (origin → transformations → destination)
  • Coupling strength

3. Identification - Produce structured report:

## Impact Analysis
### Direct Impact
- [Unit]: [Reason and modification needed]

### Indirect Impact
- [System]: [Integration path → reason]

### Data Flow
[Source] → [Transformation] → [Consumer]

### Risk Assessment
- High: [Complex dependencies, fragile areas]
- Medium: [Moderate coupling, test gaps]
- Low: [Isolated, well-tested areas]

### Implementation Order
1. [Start with lowest risk or deepest dependency]
2. [...]

Critical: Do not implement until all 3 stages are documented

Unused Code Deletion

When unused code is detected:

  • Will it be used in this work? Yes → Implement now | No → Delete now (Git preserves)
  • Applies to: Code, tests, docs, configs, assets

Existing Code Modification

In use? No → Delete
       Yes → Working? No → Delete + Reimplement
                     Yes → Fix/Extend

Principle: Prefer clean implementation over patching broken code

提供语言无关的编码原则,涵盖可维护性、简洁性及最小设计面。指导功能实现、重构及代码审查,强调优先长期健康、简化逻辑、明确意图及删除无用代码,以提升代码质量与可读性。
实现新功能时参考编码规范 进行代码重构以优化结构 执行代码质量审查 设计函数参数或错误处理逻辑
dev-skills/skills/coding-principles/SKILL.md
npx skills add shinpr/claude-code-workflows --skill coding-principles -g -y
SKILL.md
Frontmatter
{
    "name": "coding-principles",
    "description": "Language-agnostic coding principles for maintainability, readability, and quality. Use when implementing features, refactoring code, or reviewing code quality."
}

Language-Agnostic Coding Principles

Core Philosophy

  1. Maintainability over Speed: Prioritize long-term code health over initial development velocity
  2. Simplicity First: Choose the simplest solution that meets requirements (YAGNI principle)
  3. Minimum Surface for Required Coverage: When introducing maintenance-surface-bearing elements (persistent state, public-contract or cross-boundary fields/props, behavioral modes/flags/variants, reusable abstractions, or component splits), select the smallest design surface that covers the current user-visible requirements and accepted technical constraints (audit, data integrity, compatibility, security, performance, accessibility). Adoption is justified by naming a current requirement or constraint that smaller alternatives fail to cover; value-based arguments serve as tiebreakers. Distinct from YAGNI (time-axis judgment of present vs. future need), this principle governs surface-area minimization at a fixed coverage point.
  4. Explicit over Implicit: Make intentions clear through code structure and naming
  5. Delete over Comment: Remove unused code instead of commenting it out

Code Quality

Continuous Improvement

  • Refactor related code within each change set — address style, naming, or structure issues in the files being modified
  • Improve code structure incrementally
  • Keep the codebase lean and focused
  • Delete unused code immediately

Readability

  • Use meaningful, descriptive names drawn from the problem domain
  • Use full words in names; abbreviations are acceptable only when widely recognized in the domain
  • Use descriptive names; single-letter names are acceptable only for loop counters or well-known conventions (i, j, x, y)
  • Extract magic numbers and strings into named constants
  • Keep code self-documenting where possible

Function Design

Parameter Management

  • Recommended: 0-2 parameters per function
  • For 3+ parameters: Use objects, structs, or dictionaries to group related parameters
  • Example (conceptual):
    // Instead of: createUser(name, email, age, city, country)
    // Use: createUser(userData)
    

Single Responsibility

  • Each function should do one thing well
  • Keep functions small and focused (typically < 50 lines)
  • Extract complex logic into separate, well-named functions
  • Functions should have a single level of abstraction

Function Organization

  • Pure functions when possible (no side effects)
  • Separate data transformation from side effects
  • Use early returns to reduce nesting
  • Keep nesting to a maximum of 3 levels; use early returns or extracted functions to flatten deeper nesting

Error Handling

Error Management Principles

  • Always handle errors: Log with context or propagate explicitly
  • Log appropriately: Include context for debugging
  • Protect sensitive data: Mask or exclude passwords, tokens, PII from logs
  • Fail fast: Detect and report errors as early as possible

Error Propagation

  • Use language-appropriate error handling mechanisms
  • Propagate errors to appropriate handling levels
  • Provide meaningful error messages
  • Include error context when re-throwing

Dependency Management

Loose Coupling via Parameterized Dependencies

  • Inject external dependencies as parameters (constructor injection for classes, function parameters for procedural/functional code)
  • Depend on abstractions, not concrete implementations
  • Minimize inter-module dependencies
  • Facilitate testing through mockable dependencies

Reference Representativeness

Verifying References Before Adoption

When adopting patterns, APIs, or dependencies from existing code:

  • IF referencing only 2-3 nearby files → THEN confirm the pattern is representative by checking usage across the repository before adopting
  • IF multiple approaches coexist in the repository → THEN identify the majority pattern and make a deliberate choice — selecting whichever is nearest is insufficient
  • IF adopting an external dependency (library, plugin, SDK) → THEN verify repository-wide usage distribution for the same dependency; if the appropriate version cannot be determined from repository state alone, escalate
  • IF following an existing pattern → THEN state the reason for following it when an alternative exists (e.g., consistency with surrounding code, avoiding breaking changes, pending coordinated update)

Principle

Nearby code is a starting point for investigation, not a sufficient basis for adoption. Verify that what you reference is representative of the repository's conventions and current best practices before using it as a model.

Performance Considerations

Optimization Approach

  • Measure first: Profile before optimizing
  • Focus on algorithms: Algorithmic complexity > micro-optimizations
  • Use appropriate data structures: Choose based on access patterns
  • Resource management: Handle memory, connections, and files properly

When to Optimize

  • After identifying actual bottlenecks through profiling
  • When performance issues are measurable
  • Optimize only after measurable bottlenecks are identified, not during initial development

Code Organization

Structural Principles

  • Group related functionality: Keep related code together
  • Separate concerns: Domain logic, data access, presentation
  • Consistent naming: Follow project conventions
  • Module cohesion: High cohesion within modules, low coupling between

File Organization

  • One primary responsibility per file
  • Logical grouping of related functions/classes
  • Clear folder structure reflecting architecture
  • Avoid "god files" (files > 500 lines)

Commenting Principles

Default: code first

Names, types, and structure are the primary medium. A comment earns its place only by carrying information the code itself cannot express. When in doubt, improve the name instead of adding a comment.

The test for every comment

A comment is justified only if it answers one of these:

  • Why: reasoning, trade-off, or constraint behind a non-obvious decision
  • Limitation / edge case: a boundary a reader cannot infer from the code
  • Public API contract: behavior, inputs, outputs of an exported interface

One comment per decision. If a comment restates what the names and control flow already show, delete it and rename instead.

Comment Scope

  • Comment the why, limits, and public contracts (per the test above); let names and structure carry everything else, including the "how"
  • Record historical context in version control commit messages, not in comments
  • Delete commented-out code (retrieve from git history when needed)

Comment Quality

  • Write comments that remain accurate regardless of future code changes; avoid references to dates, versions, or temporary state
  • Update comments when changing code
  • Use proper grammar and formatting
  • Write for future maintainers

Refactoring Approach

Safe Refactoring

  • Small steps: Make one change at a time
  • Maintain working state: Keep tests passing
  • Verify behavior: Run tests after each change
  • Incremental improvement: Don't aim for perfection immediately

Refactoring Triggers

  • Code duplication (DRY principle)
  • Functions > 50 lines
  • Complex conditional logic
  • Unclear naming or structure

Testing Considerations

Testability

  • Write testable code from the start
  • Avoid hidden dependencies
  • Keep side effects explicit
  • Design for parameterized dependencies

Test-Driven Development

  • Write tests before implementation when appropriate
  • Keep tests simple and focused
  • Test behavior, not implementation
  • Maintain test quality equal to production code

Security Principles

Secure Defaults

  • Store credentials and secrets through environment variables or dedicated secret managers
  • Use parameterized queries (prepared statements) for all database access
  • Use established cryptographic libraries provided by the language or framework
  • Generate security-critical values (tokens, IDs, nonces) with cryptographically secure random generators
  • Encrypt sensitive data at rest and in transit using standard protocols

Input and Output Boundaries

  • Validate all external input at system entry points for expected format, type, and length
  • Encode output appropriately for its rendering context (HTML, SQL, shell, URL)
  • Return only information necessary for the caller in error responses; log detailed diagnostics server-side

Access Control

  • Apply authentication to all entry points that handle user data or trigger state changes
  • Verify authorization for each resource access, not only at the entry point
  • Grant only the permissions required for the operation (files, database connections, API scopes)

Knowledge Cutoff Supplement (2026-03)

  • OWASP Top 10:2025 shifted from symptoms to root causes; added "Software Supply Chain Failures" (A03) and "Mishandling of Exceptional Conditions" (A10)
  • Recent research indicates AI-generated code shows elevated rates of access control gaps — treat authentication and authorization as high-priority review targets
  • OpenSSF published "Security-Focused Guide for AI Code Assistant Instructions" — recommends language-specific, actionable constraints over generic advice
  • For detailed detection patterns, see references/security-checks.md

Documentation

Code Documentation

  • Document public APIs and interfaces
  • Include usage examples for complex functionality
  • Maintain README files for modules
  • Update documentation in the same commit that changes the corresponding behavior

Architecture Documentation

  • Document high-level design decisions
  • Explain integration points
  • Clarify data flows and boundaries
  • Record trade-offs and alternatives considered

Version Control Practices

Commit Practices

  • Make atomic, focused commits
  • Write clear, descriptive commit messages
  • Commit working code (passes tests)
  • Commit only production-ready code; store secrets in environment variables or secret managers

Code Review Readiness

  • Self-review before requesting review
  • Keep changes focused and reviewable
  • Provide context in pull request descriptions
  • Respond to feedback constructively

Language-Specific Adaptations

While these principles are language-agnostic, adapt them to your specific programming language:

  • Static typing: Use strong types when available
  • Dynamic typing: Add runtime validation
  • OOP languages: Apply SOLID principles
  • Functional languages: Prefer pure functions and immutability
  • Concurrency: Follow language-specific patterns for thread safety
提供PRD、ADR等文档模板及创建决策矩阵,指导技术文档生成与审查。根据项目规模、功能类型及变更复杂度(如架构、数据流变化)自动判定所需文档种类及顺序,规范研发流程。
创建或审查PRD、ADR、设计文档等工作计划 确定新项目或变更所需的文档类型和顺序
dev-skills/skills/documentation-criteria/SKILL.md
npx skills add shinpr/claude-code-workflows --skill documentation-criteria -g -y
SKILL.md
Frontmatter
{
    "name": "documentation-criteria",
    "description": "Documentation creation criteria including PRD, ADR, Design Doc, and Work Plan requirements with templates. Use when creating or reviewing technical documents, or determining which documents are required."
}

Documentation Creation Criteria

Templates

Creation Decision Matrix

Condition Required Documents Creation Order
New Feature Addition (backend) PRD → [ADR] → Design Doc → Work Plan After PRD approval
New Feature Addition (frontend/fullstack) PRD → UI Spec → [ADR] → Design Doc → Work Plan UI Spec before Design Doc
ADR Conditions Met (see below) ADR → Design Doc → Work Plan Start immediately
6+ Files [ADR if conditions apply] → Design Doc → Work Plan (Design Doc + Work Plan required) Start immediately
3-5 Files Design Doc → Work Plan (Required) Start immediately
1-2 Files None Direct implementation

ADR Creation Conditions (Required if Any Apply)

1. Contract System Changes

  • Adding nested contracts with 3+ levels: Contract A { Contract B { Contract C { field: T } } }
    • Rationale: Deep nesting has high complexity and wide impact scope
  • Changing/deleting contracts used in 3+ locations
    • Rationale: Multiple location impacts require careful consideration
  • Contract responsibility changes (e.g., DTO→Entity, Request→Domain)
    • Rationale: Conceptual model changes affect design philosophy

2. Data Flow Changes

  • Storage location changes (DB→File, Memory→Cache)
  • Processing order changes with 3+ steps
    • Example: "Input→Validation→Save" to "Input→Save→Async Validation"
  • Data passing method changes (parameter passing→shared state, direct reference→event-based communication)

3. Architecture Changes

  • Layer addition, responsibility changes, component relocation

4. External Dependency Changes

  • Library/framework/external API introduction or replacement

5. Complex Implementation Logic (Regardless of Scale)

  • Managing 3+ states
  • Coordinating 5+ asynchronous processes

Detailed Document Definitions

PRD (Product Requirements Document)

Purpose: Define business requirements and user value

Includes:

  • Business requirements and user value
  • Success metrics and KPIs (each metric specifies a numeric target and measurement method)
  • User stories and use cases
  • MoSCoW prioritization (Must/Should/Could/Won't)
  • Acceptance criteria with sequential IDs (AC-001, AC-002, ...) for downstream traceability
  • MVP and Future phase separation
  • User journey diagram (required)
  • Scope boundary diagram (required)

Scope: Business requirements, user value, success metrics, user stories, and prioritization only. Implementation details belong in Design Doc, technical selection rationale in ADR, phases and task breakdown in Work Plan.

ADR (Architecture Decision Record)

Purpose: Record technical decision rationale and background

Includes:

  • Decision (what was selected)
  • Rationale (why that selection was made)
  • Option comparison (minimum 3 options) and trade-offs
  • Architecture impact
  • Principled implementation guidelines (e.g., "Use dependency injection")

Scope: Decision, rationale, option comparison, architecture impact, and principled guidelines only. Implementation procedures and code examples belong in Design Doc, schedule and resource assignments in Work Plan.

UI Specification

Purpose: Define UI structure, screen transitions, component decomposition, and interaction design for frontend features

Includes:

  • Screen list and transition conditions
  • Component decomposition with state x display matrix (default/loading/empty/error/partial)
  • Interaction definitions linked to PRD acceptance criteria (EARS format)
  • Prototype management (code-based prototypes as attachments, not source of truth)
  • AC traceability from PRD to screens/components
  • Existing component reuse map and design tokens
  • Visual acceptance criteria (golden states, layout constraints)
  • Accessibility requirements (keyboard, screen reader, contrast)

Scope: Screen structure, transitions, component decomposition, interaction design, and visual acceptance criteria only. Technical implementation and API contracts belong in Design Doc, test implementation in test skeleton generation output, schedule in Work Plan.

Required Structural Elements:

  • At least one component with state x display matrix and interaction table
  • AC traceability table mapping PRD ACs to screens/states
  • Screen list with transition conditions
  • Existing component reuse map (reuse/extend/new decisions)

Prototype Code Handling:

  • Prototype code provided by user is placed in docs/ui-spec/assets/{feature-name}/
  • Prototype is an attachment to UI Spec, never the source of truth
  • UI Spec + Design Doc are the canonical specifications

Design Document

Purpose: Define technical implementation methods in detail

Includes:

  • Existing codebase analysis (required)
    • Implementation path mapping (both existing and new)
    • Integration point clarification (connection points with existing code even for new implementations)
  • Technical implementation approach (vertical/horizontal/hybrid)
  • Technical dependencies and implementation constraints (required implementation order)
  • Interface and contract definitions
  • Data flow and component design
  • Acceptance criteria (each criterion specifies a verifiable condition with pass/fail threshold)
  • Change impact map (clearly specify direct impact/indirect impact/no ripple effect)
  • Complete enumeration of integration points
  • Data contract clarification
  • Agreement checklist (agreements with stakeholders)
  • Code inspection evidence (inspected files/functions during investigation)
  • Field propagation map (when fields cross component boundaries)
  • Data representation decision (when introducing new structures)
  • Applicable standards (explicit/implicit classification)
  • Prerequisite ADRs (including common ADRs)
  • Verification Strategy (required)
    • Correctness proof method (what "correct" means for this change, how it's verified, when)
    • Early verification point (first target to prove the approach works, success criteria, failure response)

Required Structural Elements:

Change Impact Map:
  Change Target: [Component/Feature]
  Direct Impact: [Files/Functions]
  Indirect Impact: [Data format/Processing time]
  No Ripple Effect: [Unaffected features]

Interface Change Matrix:
  Existing: [Function/method/operation name]
  New: [Function/method/operation name]
  Conversion Required: [Yes/No]
  Compatibility Method: [Approach]

Scope: Technical implementation methods, interfaces, data flow, acceptance criteria, and verification strategy only. Technology selection rationale belongs in ADR, schedule and assignments in Work Plan.

Work Plan

Purpose: Implementation task management and progress tracking

Includes:

  • Task breakdown and dependencies (maximum 2 levels)
  • Schedule and duration estimates
  • Include test skeleton file paths produced for this work plan (integration and E2E)
  • Verification Strategy summary (extracted from Design Doc)
  • Final Quality Assurance Phase (required)
  • Progress records (checkbox format)

Scope: Task breakdown, dependencies, schedule, verification strategy summary, and progress tracking only. Technical rationale belongs in ADR, design details in Design Doc.

Phase Division Criteria (adapt to implementation approach from Design Doc):

When Vertical Slice selected:

  • Each phase = one value unit (feature, component, or migration target)
  • Each phase includes its own implementation + verification per Verification Strategy

When Horizontal Slice selected:

  1. Phase 1: Foundation Implementation - Contract definitions, interfaces/signatures, test preparation
  2. Phase 2: Core Feature Implementation - Business logic, unit tests
  3. Phase 3: Integration Implementation - External connections, presentation layer

When Hybrid selected:

  • Combine vertical and horizontal as defined in Design Doc implementation approach

All approaches: Final phase is always Quality Assurance (acceptance criteria achievement, all tests passing, quality checks). Each phase's verification method follows Verification Strategy from Design Doc.

Three Elements of Task Completion Definition:

  1. Implementation Complete: Code is functional
  2. Quality Complete: Tests, static checks, linting pass
  3. Integration Complete: Verified connection with other components

Creation Process

  1. Problem Analysis: Change scale assessment, ADR condition check
    • Identify explicit and implicit project standards before investigation
  2. ADR Option Consideration (ADR only): Compare 3+ options, specify trade-offs
  3. Creation: Use templates, include measurable conditions
  4. Approval: "Accepted" after review enables implementation

Storage Locations

Document Path Naming Convention Template
PRD docs/prd/ [feature-name]-prd.md prd-template.md
ADR docs/adr/ ADR-[4-digits]-[title].md adr-template.md
UI Spec docs/ui-spec/ [feature-name]-ui-spec.md ui-spec-template.md
UI Spec Assets docs/ui-spec/assets/{feature-name}/ Prototype code files -
Design Doc docs/design/ [feature-name]-design.md design-template.md
Work Plan docs/plans/ YYYYMMDD-{type}-{description}.md plan-template.md
Task File docs/plans/tasks/ {plan-name}-task-{number}.md task-template.md

*Note: Work plans are excluded by .gitignore

ADR Status

ProposedAcceptedDeprecated/Superseded/Rejected

AI Automation Rules

  • 6+ files: Suggest ADR creation
  • Contract/data flow change detected: ADR mandatory
  • Check existing ADRs before implementation

Diagram Requirements

Required diagrams for each document (using mermaid notation):

Document Required Diagrams Purpose
PRD User journey diagram, Scope boundary diagram Clarify user experience and scope
ADR Option comparison diagram (when needed) Visualize trade-offs
UI Spec Screen transition diagram, Component tree diagram Clarify screen flow and component structure
Design Doc Architecture diagram, Data flow diagram Understand technical structure
Work Plan Phase structure diagram, Task dependency diagram Clarify implementation order

Common ADR Relationships

  1. At creation: Identify common technical areas (logging, error handling, async processing, etc.), reference existing common ADRs
  2. When missing: Consider creating necessary common ADRs
  3. Design Doc: Specify common ADRs in "Prerequisite ADRs" section
  4. Compliance check: Verify design aligns with common ADR decisions
捕获并持久化仓库外资源(如设计源、API、密钥等)的访问方法,供下游工作确定性使用。通过两级存储管理事实,定义听取协议以更新信息,确保下游任务能准确获取外部依赖。
工作依赖于外部资源 用户提及设计源、设计系统、API模式、IaC源或密钥库
dev-skills/skills/external-resource-context/SKILL.md
npx skills add shinpr/claude-code-workflows --skill external-resource-context -g -y
SKILL.md
Frontmatter
{
    "name": "external-resource-context",
    "description": "Captures and persists access methods for resources outside the repository (design source, design system, API schema, IaC source, secret store) so downstream work can reach them deterministically. Use when work depends on external resources, or when the user mentions design source, design system, API schema, IaC source, secret store, or canonical source."
}

External Resource Context

Purpose

AI agents understand the codebase but not the external resources surrounding it. This skill captures, in a deterministic location, the access methods to resources outside the repository so downstream work (design, planning, implementation, review) can reach them without re-asking the user.

Resources covered: design origin (where the canonical visual specification lives), design system (component library and tokens), guidelines (usage docs, accessibility rules), visual verification environment (how to confirm rendering), database schema source, migration history, secret store location, API schema source (OpenAPI / proto / GraphQL SDL), mock environment, IaC source, environment configuration.

Scope Boundaries

In scope: hearing protocol, storage location, single-source-of-truth ownership rule, reference protocol for downstream consumers.

Out of scope: enforcing that captured resources are correct or current — verification belongs to the agent that consumes the resource. Generating the resources themselves (e.g., creating a DESIGN.md from scratch).

Storage Locations (Two-Tier)

Tier Location Holds Update Frequency
Project docs/project-context/external-resources.md Environment-stable facts: which resources exist for this project and how to access them (URL, MCP name, file path, command) Rare — only when the project's environment changes
Feature ## External Resources Used section inside the relevant UI Spec or Design Doc The subset of project-tier resources actually used by this feature, plus feature-specific identifiers (e.g., a specific node id within the design tool, a specific endpoint path) Per feature

Single Source of Truth Rule

The project tier owns environment facts. Feature-tier sections list only feature-specific identifiers (node id within the design source, specific endpoint path within the API, specific IaC module name) and reference project-tier entries by label; URLs, MCP names, and access commands remain in the project-tier file. When the environment changes, only the project-tier file is updated.

Example feature-tier entry uses the table format defined in references/template.md: a row with the project-tier label in the first column and the feature-specific identifier in the second column.

Hearing Protocol

When to Hear

Condition Action
docs/project-context/external-resources.md does not exist Run full hearing for the relevant domain(s)
File exists Ask the user via AskUserQuestion: "Update external-resources.md? (no / yes-full / yes-diff-only)". On yes-full run full hearing. On yes-diff-only ask the user which axes changed, hear only those. On no skip hearing

Domain Routing

Load the domain reference matching the current task:

Task type References to load
Frontend (UI work) references/frontend.md
Backend (server / data work) references/backend.md
API contract work references/api.md
Infrastructure / deployment references/infra.md
Fullstack All of the above; per-axis "Not applicable" answers are expected

Each domain reference defines the axes and the question template.

Two-Phase Hearing

  1. Structured hearing — for each axis defined in the domain reference, present the user with AskUserQuestion using the choices listed there (always include "Not applicable" as an option). For each non-N/A axis, follow up with an access-method question (URL / MCP name / file path / command).

  2. Self-declaration — after the structured axes, present a single AskUserQuestion: "Are there any other external resources for this work that the structured questions did not cover? If yes, describe them in your next message." If the user describes additional resources, append them to the storage file under an "Additional resources" subsection.

The two phases are sequential. Self-declaration runs even if the user answered "Not applicable" to every structured axis.

Storage Protocol

After hearing completes:

  1. Build the project-tier content from the answers. Use references/template.md as the structure.
  2. Write to docs/project-context/external-resources.md. Create the directory if absent.
  3. When the calling workflow has a target UI Spec or Design Doc, also append or update the document's ## External Resources Used section with the feature-tier subset (label references + feature-specific identifiers only).
  4. Report the file paths back to the calling workflow.

Reference Protocol (For Downstream Consumers)

Agents that load this skill consult resources in this order:

  1. Read docs/project-context/external-resources.md first (if present) to learn what is available and how to access it.
  2. Read the target UI Spec or Design Doc's ## External Resources Used section for feature-specific identifiers.
  3. Use the access method declared in the project tier (e.g., the named MCP, the URL, the file path) to fetch the actual resource content.

Agents that only need to consult the saved file as input data (not actively hear) can read it directly without loading this skill — frontmatter declaration is reserved for agents that may need to trigger hearing or interpret the protocol semantics.

Output Format

The project-tier file follows the structure in references/template.md. The project-tier file's heading levels and section names are fixed so downstream agents can locate sections deterministically.

For feature-tier sections inside UI Spec or Design Doc, the heading text "External Resources Used" is fixed; the heading level matches the parent document's natural structure (h2 in UI Spec where it is a sibling of other top-level sections, h3 in Design Doc where it sits under Background and Context).

Quality Checklist

  • Each axis answered has both a presence indicator and an access method, or is marked "Not applicable"
  • Self-declaration phase ran even when all structured axes were "Not applicable"
  • Project-tier file does not contain feature-specific identifiers
  • Feature-tier sections reference project-tier entries by label, not by duplicating URLs / MCP names
  • When the project file already existed, the update decision (no / yes-full / yes-diff-only) was confirmed before any write

References

前端技术决策指南,提供反模式识别、代码重复处理(Rule of Three)、降级设计原则及质量检查流程。用于指导前端开发中的架构设计、重构决策及质量保证,避免常见陷阱并提升代码可维护性。
进行前端技术架构决策时 执行前端代码审查或质量保证 发现代码重复需重构时 设计错误处理或降级方案时
dev-skills/skills/frontend-ai-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill frontend-ai-guide -g -y
SKILL.md
Frontmatter
{
    "name": "frontend-ai-guide",
    "description": "Frontend-specific technical decision criteria, anti-patterns, debugging techniques, and quality check workflow. Use when making frontend technical decisions or performing quality assurance."
}

AI Developer Guide - Technical Decision Criteria and Anti-pattern Collection (Frontend)

Technical Anti-patterns (Red Flag Patterns)

Immediately stop and reconsider design when detecting the following patterns:

Code Quality Anti-patterns

  1. Writing similar code 3 or more times - Violates Rule of Three
  2. Multiple responsibilities mixed in a single component - Violates Single Responsibility Principle (SRP)
  3. Defining same content in multiple components - Violates DRY principle
  4. Making changes without checking dependencies - Potential for unexpected impacts
  5. Disabling code with comments - Should use version control
  6. Error suppression - Hiding problems creates technical debt
  7. Excessive use of type assertions (as) - Abandoning type safety
  8. Prop drilling through 3+ levels - Should use Context API or state management
  9. Massive components (300+ lines) - Split into smaller components

Design Anti-patterns

  • "Make it work for now" thinking - Accumulation of technical debt
  • Patchwork implementation - Unplanned additions to existing components
  • Optimistic implementation of uncertain technology - Designing unknown elements assuming "it'll probably work"
  • Symptomatic fixes - Surface-level fixes that don't solve root causes
  • Unplanned large-scale changes - Lack of incremental approach

Fallback Design Principles

Core Principle: Fail-Fast

Design philosophy that prioritizes improving primary code reliability over fallback implementations.

Criteria for Fallback Implementation

  • Fallback rule: Implement fallbacks only when explicitly defined in Design Doc
  • Layer Responsibilities:
    • Component Layer: Use Error Boundary for error handling
    • Hook Layer: Implement decisions based on business requirements

Detection of Excessive Fallbacks

  • Require design review when writing the 3rd catch statement in the same feature
  • Verify Design Doc definition before implementing fallbacks
  • Properly log errors and make failures explicit

Rule of Three - Criteria for Code Duplication

How to handle duplicate code based on Martin Fowler's "Refactoring":

Duplication Count Action Reason
1st time Inline implementation Cannot predict future changes
2nd time Consider future consolidation Pattern beginning to emerge
3rd time Implement commonalization Pattern established

Criteria for Commonalization

Cases for Commonalization

  • Business logic duplication
  • Complex processing algorithms
  • Component patterns (form fields, cards, etc.)
  • Custom hooks
  • Validation rules

Cases to Avoid Commonalization

  • Accidental matches (coincidentally same code)
  • Possibility of evolving in different directions
  • Significant readability decrease from commonalization
  • Simple helpers in test code

Implementation Example

// 1st-2nd occurrence: keep separate, no commonalization yet
function UserEmailInput() { /* ... */ }
function ContactEmailInput() { /* ... */ }

// Commonalize on 3rd occurrence
function EmailInput({ context }: { context: 'user' | 'contact' | 'admin' }) { /* ... */ }

Common Failure Patterns and Avoidance Methods

Pattern 1: Error Fix Chain

Symptom: Fixing one error causes new errors Cause: Surface-level fixes without understanding root cause Avoidance: Identify root cause with 5 Whys before fixing

Pattern 2: Abandoning Type Safety

Symptom: Excessive use of any type or as Cause: Impulse to avoid type errors Avoidance: Handle safely with unknown type and type guards

Pattern 3: Implementation Without Sufficient Testing

Symptom: Many bugs after implementation Cause: Ignoring Red-Green-Refactor process Avoidance: Always start with failing tests

Pattern 4: Ignoring Technical Uncertainty

Symptom: Frequent unexpected errors when introducing new technology Cause: Assuming "it should work according to official documentation" without prior investigation Avoidance:

  • Record certainty evaluation at the beginning of task files
    Certainty: low (Reason: new experimental feature with limited production examples)
    Exploratory implementation: true
    Fallback: use established patterns
    
  • For low certainty cases, create minimal verification code first

Pattern 5: Insufficient Existing Code Investigation

Symptom: Duplicate implementations, architecture inconsistency, integration failures Cause: Insufficient understanding of existing code before implementation Avoidance Methods:

  • Before implementation, always search for similar functionality (using domain, responsibility, component patterns as keywords)
  • Similar functionality found → Use that implementation (do not create new implementation)
  • Similar functionality is technical debt → Create ADR improvement proposal before implementation
  • No similar functionality exists → Implement new functionality following existing design philosophy
  • Record all decisions and rationale in "Existing Codebase Analysis" section of Design Doc

Debugging Techniques

1. Error Analysis Procedure

  1. Read error message (first line) accurately
  2. Focus on first and last of stack trace
  3. Identify first line where your code appears
  4. Check React DevTools for component hierarchy

2. 5 Whys - Root Cause Analysis

Symptom: Component not rendering
Why1: Props are undefined → Why2: Parent component didn't pass props
Why3: Parent using old prop names → Why4: Component interface was updated
Why5: No update to parent after refactoring
Root cause: Incomplete refactoring, missing call-site updates

3. Minimal Reproduction Code

To isolate problems, attempt reproduction with minimal code:

  • Remove unrelated components
  • Replace API calls with mocks
  • Create minimal configuration that reproduces problem
  • Use React DevTools to inspect component tree

4. Debug Log Output (temporary)

Add structured debug logs to isolate the issue, then remove them before commit (per "Delete debug console.log()" in typescript-rules):

console.log('DEBUG:', {
  context: 'user-form-submission',
  props: { email, name },
  state: currentState,
  timestamp: new Date().toISOString()
})

Quality Check Workflow

Read package.json scripts and run them with the project's package manager (packageManager field). Map the project's actual script names to the phases below — do not assume fixed names.

Phases (run in order)

  1. Lint/format — the project's formatter + linter (e.g., Biome, or ESLint + Prettier)
  2. Type check — type check without emit
  3. Build — production build
  4. Test — unit/integration tests
  5. Coverage — coverage run when the task added or changed behavior

Troubleshooting

  • Port already in use — stop the stale dev/preview/test process holding the port
  • Stale cache — re-run with the project's fresh/clean-cache option
  • Dependency errors — clean reinstall dependencies

Situations Requiring Technical Decisions

Timing of Abstraction

  • Extract patterns after writing concrete implementation 3 times
  • Be conscious of YAGNI, implement only currently needed features
  • Prioritize current simplicity over future extensibility

Performance vs Readability

  • Prioritize readability unless React DevTools Profiler identifies a measurable bottleneck (e.g., render time exceeding 16ms, unnecessary re-renders)
  • Measure before optimizing with React DevTools Profiler
  • Document reason with comments when optimizing

Granularity of Component/Type Definitions

  • Overly detailed components/types reduce maintainability
  • Design components that appropriately express UI patterns
  • Use composition over inheritance

Implementation Completeness Assurance

Required Procedure for Impact Analysis

Completion Criteria: Complete all 3 stages

1. Discovery

Grep -n "ComponentName\|hookName" -o content
Grep -n "importedFunction" -o content
Grep -n "propsType\|StateType" -o content

2. Understanding

Mandatory: Read all discovered files and include necessary parts in context:

  • Caller's purpose and context
  • Component hierarchy
  • Data flow: Props → State → Event handlers → Callbacks

3. Identification

Structured impact report (mandatory):

## Impact Analysis
### Direct Impact: ComponentA, ComponentB (with reasons)
### Indirect Impact: FeatureX, PageY (with integration paths)
### Processing Flow: Props → Render → Events → Callbacks

Important: Execute all 3 stages to completion

Unused Code Deletion Rule

When unused code is detected → Will it be used?

  • Yes → Implement immediately (no deferral allowed)
  • No → Delete immediately (remains in Git history)

Target: Components, hooks, utilities, documentation, configuration files

Existing Code Deletion Decision Flow

In use? No → Delete immediately (remains in Git history)
       Yes → Working? No → Delete + Reimplement
                     Yes → Fix
用于制定实施策略的元认知框架。涵盖现状分析、策略探索(如绞杀者模式)、风险评估及约束验证,旨在通过系统性思考选择最优开发方案并控制风险。
规划实施策略 选择开发方法 定义验证标准
dev-skills/skills/implementation-approach/SKILL.md
npx skills add shinpr/claude-code-workflows --skill implementation-approach -g -y
SKILL.md
Frontmatter
{
    "name": "implementation-approach",
    "description": "Implementation strategy selection framework. Use when planning implementation strategy, selecting development approach, or defining verification criteria."
}

Implementation Strategy Selection Framework (Meta-cognitive Approach)

Meta-cognitive Strategy Selection Process

Phase 1: Comprehensive Current State Analysis

Core Question: "What does the existing implementation look like?"

Analysis Framework

Architecture Analysis: Responsibility separation, data flow, dependencies, technical debt
Implementation Quality Assessment: Code quality, test coverage, performance, security
Historical Context Understanding: Current form rationale, past decision validity, constraint changes, requirement evolution

Meta-cognitive Question List

  • What is the true responsibility of this implementation?
  • Which parts are business essence and which derive from technical constraints?
  • What dependencies or implicit preconditions are unclear from the code?
  • What benefits and constraints does the current design bring?

Phase 2: Strategy Exploration and Creation

Core Question: "When determining before → after, what implementation patterns or strategies should be referenced?"

Strategy Discovery Process

Research and Exploration: Tech stack examples (WebSearch), similar projects, OSS references, literature/blogs
Creative Thinking: Strategy combinations, constraint-based design, phase division, extension point design

Reference Strategy Patterns (Creative Combinations Encouraged)

Legacy Handling Strategies:

  • Strangler Pattern: Gradual migration through phased replacement
  • Facade Pattern: Complexity hiding through unified interface
  • Adapter Pattern: Bridge with existing systems

New Development Strategies:

  • Feature-driven Development: Vertical implementation prioritizing user value
  • Foundation-driven Development: Foundation-first construction prioritizing stability
  • Risk-driven Development: Prioritize addressing maximum risk elements

Integration/Migration Strategies:

  • Proxy Pattern: Transparent feature extension
  • Decorator Pattern: Phased enhancement of existing features
  • Bridge Pattern: Flexibility through abstraction

Important: The optimal solution is discovered through creative thinking according to each project's context.

Phase 3: Risk Assessment and Control

Core Question: "What risks arise when applying this to existing implementation, and what's the best way to control them?"

Risk Analysis Matrix

Technical Risks: System impact, data consistency, performance degradation, integration complexity
Operational Risks: Service availability, deployment downtime, process changes, rollback procedures
Project Risks: Schedule delays, learning costs, quality achievement, team coordination

Risk Control Strategies

Preventive Measures: Phased migration, parallel operation verification, integration/regression tests, monitoring setup
Incident Response: Rollback procedures, log/metrics preparation, communication system, service continuation procedures

Phase 4: Constraint Compatibility Verification

Core Question: "What are this project's constraints?"

Constraint Checklist

Technical Constraints: Library compatibility, resource capacity, mandatory requirements, numerical targets
Temporal Constraints: Deadlines/priorities, dependencies, milestones, learning periods
Resource Constraints: Team/skills, work hours/systems, budget, external contracts
Business Constraints: Market launch timing, customer impact, regulatory compliance

Phase 5: Implementation Approach Decision

Select optimal solution from basic implementation approaches (creative combinations encouraged):

Vertical Slice (Feature-driven)

Characteristics: Vertical implementation across all layers by feature unit Application Conditions: Features share fewer than 2 data models, each feature is independently deliverable, changes touch 3+ architecture layers Verification Method: End-user value delivery at each feature completion

Horizontal Slice (Foundation-driven)

Characteristics: Phased construction by architecture layer Application Conditions: 3+ features depend on a common foundation layer, foundation changes require stability verification before consumers can proceed Verification Method: Integrated operation verification when all foundation layers complete

Hybrid (Creative Combination)

Characteristics: Flexible combination according to project characteristics Application Conditions: Unclear requirements, need to change approach per phase, transition from prototyping to full implementation Verification Method: Verify at appropriate L1/L2/L3 levels according to each phase's goals

Phase 6: Decision Rationale Documentation

Design Doc Documentation: Record in the Design Doc's implementation approach section:

  1. Selected strategy name and characteristics
  2. Alternatives considered and reason for rejection
  3. Risk mitigation plan (from Phase 3)
  4. Constraint compliance summary (from Phase 4)
  5. Verification level (L1/L2/L3) and integration point definition

Verification Level Definitions

Priority for completion verification of each task:

  • L1: Functional Operation Verification - Operates as end-user feature (e.g., search executable)
  • L2: Test Operation Verification - New tests added and passing
  • L3: Build Success Verification - Code builds/runs without errors

Priority: L1 > L2 > L3 in order of verifiability importance

Integration Point Definitions

Define integration points according to selected strategy:

  • Strangler-based: When switching between old and new systems for each feature
  • Feature-driven: When users can actually use the feature
  • Foundation-driven: When all architecture layers are ready and E2E tests pass
  • Hybrid: When individual goals defined for each phase are achieved

Quality Checks

  1. Verify at least one strategy combination beyond listed patterns was considered
  2. Confirm Phase 1 analysis framework is complete before selecting strategy
  3. Confirm Phase 3 risk analysis matrix is populated before implementation starts
  4. Confirm Phase 4 constraint checklist is reviewed before strategy decision
  5. Confirm Phase 6 documentation template is filled with selection rationale

Guidelines for Meta-cognitive Execution

  1. Leverage Known Patterns: Use as starting point, explore creative combinations
  2. Active WebSearch Use: Research implementation examples from similar tech stacks
  3. Apply 5 Whys: Pursue root causes to grasp essence
  4. Multi-perspective Evaluation: Comprehensively evaluate from each Phase 1-4 perspective
提供集成与E2E测试设计原则、ROI计算及审查标准。涵盖测试类型定义、Lane选择策略及行为优先原则,用于指导测试用例设计、优先级排序及质量评估。
设计集成测试或E2E测试 进行测试用例优先级排序 审查测试代码质量 确定测试类型预算分配
dev-skills/skills/integration-e2e-testing/SKILL.md
npx skills add shinpr/claude-code-workflows --skill integration-e2e-testing -g -y
SKILL.md
Frontmatter
{
    "name": "integration-e2e-testing",
    "description": "Integration and E2E test design principles, ROI calculation, test skeleton specification, and review criteria. Use when designing integration tests, E2E tests, or reviewing test quality."
}

Integration and E2E Testing Principles

References

E2E test design: See references/e2e-design.md for UI Spec-driven E2E test candidate selection and browser test architecture. The reference uses Playwright as the default browser harness; substitute the project's standard when different.

Test Type Definition and Limits

Test Type Purpose Scope External Deps Limit per Feature Implementation Timing
Integration Verify component interactions in-process Partial system integration (in-process modules; for UI components, the framework's in-process renderer e.g., RTL+MSW for React/TS) Mocked or in-process MAX 3 Created alongside implementation
fixture-e2e Verify UI behavior in a browser with deterministic fixtures Full UI flow with mocked backend / fixture-driven state Mocked / fixture only — no live services MAX 3 Created alongside the UI feature
service-integration-e2e Verify critical user journeys against a running local stack Full system across services Live local services or stubs MAX 1-2 Executed only in the final phase

Lane selection (E2E only):

  • Default lane for user-facing UI journeys is fixture-e2e — it runs a real browser against deterministic fixtures, catches the bugs that unit/integration tests miss (button no-op, state never updates, navigation breaks), and runs in CI without infrastructure setup
  • Add service-integration-e2e only when the journey's correctness depends on real cross-service behavior (data persistence, transactional consistency, external service contracts) that cannot be faked safely

The two E2E lanes are budgeted independently — having a fixture-e2e for a journey does not consume the service-integration-e2e budget and vice versa.

Behavior-First Principle

Include (High ROI)

  • Business logic correctness (calculations, state transitions, data transformations)
  • Data integrity and persistence behavior
  • User-visible functionality completeness
  • Error handling behavior (what user sees/experiences)

Redirect to Other Test Types

  • External service connections → Verify via contract/interface tests
  • Performance metrics → Verify via dedicated load testing
  • Implementation details → Verify observable behavior instead
  • UI layout specifics → Verify information availability instead

Principle: Test = User-observable behavior verifiable in isolated CI environment

ROI Calculation

ROI is used to rank candidates within the same test type (integration candidates against each other, E2E candidates against each other). Cross-type comparison is unnecessary because integration and E2E budgets are selected independently.

ROI Score = Business Value × User Frequency + Legal Requirement × 10 + Defect Detection
              (range: 0–120)

Higher ROI Score = higher priority within its test type. No normalization or capping is applied — the raw score is used directly for ranking. Deduplication is a separate step that removes candidates entirely; it does not modify scores.

ROI Thresholds by Lane

The two E2E lanes have very different ownership costs and use independent thresholds.

Lane ROI threshold Rationale
fixture-e2e ROI ≥ 20 (beyond reserved slot) Cost is comparable to integration tests once the harness exists; the floor avoids filling MAX 3 with low-signal tests when fewer would suffice
service-integration-e2e ROI > 50 (beyond reserved slot) Creation, execution, and maintenance cost is 3-10× higher than integration; reserve for journeys whose value cannot be proven any other way

Reserved slot rules (see Multi-Step User Journey Definition below) apply per lane and override the threshold (the reserved candidate is emitted regardless of its ROI score). Below-floor candidates beyond the reserved slot are not emitted, leaving budget intentionally unfilled rather than padding with low-value tests.

ROI Calculation Examples

Scenario BV Freq Legal Defect ROI Score Test Type Selection Outcome
Core checkout UI flow 10 9 true 9 109 fixture-e2e Selected (reserved slot: user-facing multi-step journey, browser-level verification with fixtures)
Core checkout against live payment service 10 9 true 9 109 service-integration-e2e Selected (real-service correctness above ROI threshold)
Dismiss button updates UI state 6 7 false 8 50 fixture-e2e Selected (rank 2 of 3 fixture-e2e budget)
Payment error message display 5 4 false 7 27 fixture-e2e Selected (rank 3 of 3 fixture-e2e budget)
Optional filter toggle 3 4 false 2 14 fixture-e2e Not selected (rank 4, budget full)
Payment retry against real provider 8 3 false 7 31 service-integration-e2e Below ROI threshold (31 < 50), not selected
DB persistence check 8 8 false 8 72 Integration Selected (rank 1 of 3)
Pure data transformation 5 3 false 4 19 Integration Selected (rank 2 of 3)

Multi-Step User Journey Definition

A feature qualifies as containing a multi-step user journey when ALL of the following are true:

  1. 2+ distinct interaction boundaries are traversed in sequence to complete a user goal. What counts as a boundary depends on the system type:
    • Web: distinct routes/pages
    • Mobile native: distinct screens/views
    • CLI: distinct command invocations or interactive prompts
    • API: distinct API calls forming a transaction (e.g., create → confirm → finalize)
  2. State carries across steps — data produced or actions taken in one step affect what the next step accepts or displays
  3. The journey has a completion point — a final state the user or caller reaches (e.g., confirmation page, saved record, API success response, completed workflow)

User-Facing vs Service-Internal Journeys

Multi-step journeys are classified for reserved-slot eligibility:

Classification Condition Reserved Slot Eligibility Example
User-facing A human user directly triggers and observes the steps (via UI, CLI, or direct API interaction) Eligible — defaults to fixture-e2e reserved slot. Add a service-integration-e2e reserved slot only when the journey's correctness depends on real cross-service behavior Web checkout flow, CLI setup wizard, mobile onboarding
Service-internal Steps are triggered by backend services without direct user interaction Not eligible for reserved slot — use integration tests. Service-integration-e2e through normal ROI > 50 path is still valid when full-system verification is warranted Async job pipeline, service-to-service saga, scheduled batch processing

This classification applies only to the reserved-slot rule and the E2E Gap Check. Other selection follows lane-specific ROI rules above.

Use this definition when evaluating E2E test candidates and E2E gap detection.

Test Skeleton Specification

Required Comment Patterns

Each test MUST include the following annotations:

AC: [Original acceptance criteria text]
Behavior: [Trigger] → [Process] → [Observable Result]
@category: core-functionality | integration | edge-case | fixture-e2e | service-integration-e2e
@lane: integration | fixture-e2e | service-integration-e2e
@dependency: none | [component names] | full-system
@complexity: low | medium | high
ROI: [score]

@lane selection rule:

  • integration — Component interaction in-process, no browser (e.g., RTL+MSW for React/TS, in-process module/handler integration in any language)
  • fixture-e2e — Browser-level UI verification with mocked backend / fixture-driven state
  • service-integration-e2e — Browser-level or end-to-end verification against running local services or stubs

Use the project's comment syntax to wrap these annotations (e.g., // for C-family, # for Python/Ruby/Shell).

Verification Items (Optional)

When verification points need explicit enumeration:

Verification items:
- [Item 1]
- [Item 2]

EARS Format Mapping

EARS Keyword Test Type Generation Approach
When Event-driven Trigger event → verify outcome
While State condition Setup state → verify behavior
If-then Branch coverage Both condition paths verified
(none) Basic functionality Direct invocation → verify result

Test File Naming Convention

  • Integration tests: *.int.test.* or *.integration.test.*
  • fixture-e2e tests: *.fixture.e2e.test.* (or organize under tests/e2e/fixture/)
  • service-integration-e2e tests: *.service.e2e.test.* (or organize under tests/e2e/service/)

The test runner or framework in the project determines the appropriate file extension. Repos that already use a single *.e2e.test.* convention may keep it as long as each file declares @lane: in its header — the lane annotation is the source of truth for routing and budget accounting.

Review Criteria

Skeleton and Implementation Consistency

Check Failure Condition
Behavior Verification No assertion for "observable result" in the implemented test
Verification Item Coverage Listed items not all covered by assertions
Mock Boundary Internal components mocked in integration test

Implementation Quality

Check Failure Condition
AAA Structure Arrange/Act/Assert separation unclear
Independence State sharing between tests, order dependency
Reproducibility Date/random dependency, varying results
Readability Test name doesn't match verification content

Quality Standards

Required

  • Each test verifies one behavior
  • Clear AAA (Arrange-Act-Assert) structure
  • No test interdependencies
  • Deterministic execution
旨在通过明确输入输出、成功标准和决策,消除歧义,确保下游智能体无需猜测即可稳定执行。适用于编写或修订LLM提示词、交接文档及规划工件,提升指令的可操作性与确定性。
编写面向LLM的提示词 创建任务交接文档 生成规划工件或报告 审查和修订现有指令
dev-skills/skills/llm-friendly-context/SKILL.md
npx skills add shinpr/claude-code-workflows --skill llm-friendly-context -g -y
SKILL.md
Frontmatter
{
    "name": "llm-friendly-context",
    "description": "Clarifies inputs, outputs, success criteria, decisions, and unresolved conditions so downstream agents can execute without guessing. Use when writing or revising LLM-facing prompts, handoffs, planning artifacts, reviews, reports, or generated instructions."
}

LLM-Friendly Context

The goal is stable downstream execution: the next agent should know what to read, what to do, what counts as success, and when to stop or escalate.

Core Rules

  1. Use positive, executable instructions

    • State what the next agent should do.
    • Convert quality policies into positive criteria.
    • Example: "Preserve existing public API behavior across the documented compatibility cases."
  2. Make vague instructions concrete

    • Replace subjective terms with observable conditions, paths, commands, schemas, examples, or decision rules.
    • Terms that often need clarification when they leave a decision to the next agent: appropriate, proper, related, existing behavior, optional, as needed, if needed, per convention, unresolved alternatives, TBD, placeholder.
  3. Specify output shape

    • Define required sections, fields, table columns, JSON keys, or checklist items.
    • For handoffs, include paths to produced artifacts and the exact status fields the caller must inspect.
  4. Provide necessary context

    • Include the purpose, source artifacts, hard constraints, accepted decisions, and unresolved conditions.
    • Prefer concrete file paths and section hints over broad module names.
  5. Decompose complex work into verifiable steps

    • Split work with 3+ objectives or sequential dependencies into ordered steps.
    • Each step needs a checkpoint: what evidence proves it is complete.
  6. Permit uncertainty explicitly

    • If the source material is missing, contradictory, or not verifiable, state the uncertainty and the required escalation.
    • Record unknown business, product, security, or compatibility decisions as blocking unresolved items with the input needed to resolve them.
  7. Keep constraints proportionate

    • Add only constraints that reduce ambiguity or preserve a real requirement.
    • Keep simple downstream tasks lightweight when the target action, context, and success criteria are already clear.

Rewrite Patterns

Use these rewrites before treating a prompt, handoff, or artifact as complete.

Ambiguous form Rewrite as
optional used as an unresolved choice Required, omitted, or required only under a named condition
Multiple alternatives that the next agent must choose between The selected option, or a deterministic decision rule
as needed / if needed The triggering condition and required action
per convention The file, function, test, or documented convention to follow
related files Specific paths, globs, or search hints
existing behavior The observable behavior, source file, test, API response, or UI state to preserve
placeholder Exact temporary value/behavior, allowed dependencies, and verification expectation
TBD used as a placeholder for required information A blocking unresolved item with owner, required input, or escalation condition
appropriate / proper A measurable criterion or checklist

Handoff Checklist

Before sending a prompt or artifact to another agent, verify:

  • The target action is explicit.
  • Required input paths and source artifacts are named.
  • Accepted decisions and constraints are stated once, without alternate wording.
  • Output format or expected status fields are specified.
  • Success criteria are observable.
  • Ambiguous expressions have been rewritten or marked as unresolved.
  • The next agent can complete its scope with explicit choices, decision rules, or blocking unresolved items.

Generated Artifact Checklist

Before writing or finalizing a generated document:

  • Each requirement, claim, task, test skeleton, or review finding has enough source context to trace why it exists.
  • Every executable instruction names the target, action, and expected result.
  • Verification steps say what to run or observe and what result proves success.
  • If an artifact is derived from another artifact, copied decisions stay consistent in wording and meaning.
  • If downstream work is blocked by missing information, the artifact records the missing input and escalation condition.
指导实现各类测试,包括基于RTL+Vitest+MSW的React组件单元测试、集成测试及Playwright E2E测试。遵循AAA结构、测试独立性及用户视角命名规范,确保测试确定性与可维护性。
需要编写React组件单元测试 需要编写集成测试 需要编写E2E测试 实施前端测试最佳实践
dev-skills/skills/test-implement/SKILL.md
npx skills add shinpr/claude-code-workflows --skill test-implement -g -y
SKILL.md
Frontmatter
{
    "name": "test-implement",
    "description": "Test implementation patterns and conventions. Use when implementing unit tests, integration tests, or E2E tests, including RTL+Vitest+MSW component testing and Playwright E2E testing."
}

Test Implementation Patterns

Reference Selection

Test Type Reference When to Use
Unit / Integration references/frontend.md Implementing React component tests with RTL + Vitest + MSW
E2E references/e2e.md Implementing browser-level E2E tests with Playwright

Common Principles

AAA Structure

All tests follow Arrange-Act-Assert:

  • Arrange: Set up preconditions and inputs
  • Act: Execute the behavior under test
  • Assert: Verify the expected outcome

Test Independence

  • Each test runs independently without depending on other tests
  • No shared mutable state between tests
  • Deterministic execution — no random or time dependencies without mocking

Naming

  • Test names describe expected behavior from user perspective
  • One test verifies one behavior
提供语言无关的测试原则,涵盖TDD红绿重构循环、测试质量要求(如覆盖率警示)、三类测试(单元/集成/E2E)及AAA设计模式。适用于编写测试、制定策略或审查质量。
编写单元测试或集成测试时 设计测试策略或架构 审查现有测试代码的质量 需要遵循TDD流程时
dev-skills/skills/testing-principles/SKILL.md
npx skills add shinpr/claude-code-workflows --skill testing-principles -g -y
SKILL.md
Frontmatter
{
    "name": "testing-principles",
    "description": "Language-agnostic testing principles including TDD, test quality, coverage standards, and test design patterns. Use when writing tests, designing test strategies, or reviewing test quality."
}

Language-Agnostic Testing Principles

Test-Driven Development (TDD)

The RED-GREEN-REFACTOR Cycle

Always follow this cycle:

  1. RED: Write a failing test first

    • Write the test before implementation
    • Ensure the test fails for the right reason
    • Verify test can actually fail
  2. GREEN: Write minimal code to pass

    • Implement just enough to make the test pass
    • Focus on making it work
  3. REFACTOR: Improve code structure

    • Clean up implementation
    • Eliminate duplication
    • Improve naming and clarity
    • Keep all tests passing
  4. VERIFY: Ensure all tests still pass

    • Run full test suite
    • Check for regressions
    • Validate refactoring didn't break anything

Quality Requirements

Coverage

  • Treat coverage as a diagnostic signal for finding untested areas, not a target — a target gets gamed into trivial tests (Goodhart's Law)
  • Concentrate tests on critical paths, business logic, and behavior whose regression would matter
  • Prioritize meaningful assertions over the coverage number; any CI threshold is the project's config, not a quality goal in itself

Test Characteristics

All tests must be:

  • Independent: No dependencies between tests (see Test Independence Verification for detailed criteria)
  • Reproducible: Same input always produces same output
  • Fast: Unit tests < 100ms each, integration tests < 1s each, full suite < 10 minutes
  • Self-checking: Clear pass/fail without manual verification
  • Timely: Written close to the code they test

Test Types

Unit Tests

Purpose: Test individual components in isolation

Characteristics:

  • Test single function, method, or class
  • Fast execution (milliseconds)
  • No external dependencies
  • Mock external services
  • Majority of your test suite

Integration Tests

Purpose: Test interactions between components

Characteristics:

  • Test multiple components together
  • May include database, file system, or APIs
  • Slower than unit tests
  • Verify contracts between modules
  • Smaller portion of test suite

End-to-End (E2E) Tests

Purpose: Test complete workflows from user perspective

Characteristics:

  • Test entire application stack
  • Simulate real user interactions
  • Slowest test type
  • Fewest in number
  • Highest confidence level

Test Design Principles

AAA Pattern (Arrange-Act-Assert)

Structure every test in three clear phases:

// Arrange: Setup test data and conditions
user = createTestUser()
validator = createValidator()

// Act: Execute the code under test
result = validator.validate(user)

// Assert: Verify expected outcome
assert(result.isValid == true)

Adaptation: Apply this structure using your language's idioms (methods, functions, procedures)

One Assertion Per Concept

  • Test one behavior per test case
  • Multiple assertions OK if testing single concept
  • Split unrelated assertions into separate tests

Example: prefer returns error when email is invalid over validates user.

Descriptive Test Names

Test names should clearly describe:

  • What is being tested
  • Under what conditions
  • What the expected outcome is

Recommended format: "should [expected behavior] when [condition]"

Examples:

test("should return error when email is invalid")
test("should calculate discount when user is premium")
test("should throw exception when file not found")

Adaptation: Follow your project's naming convention (camelCase, snake_case, describe/it blocks)

Test Independence

Setup and Teardown

  • Use setup hooks to prepare test environment
  • Use teardown hooks to clean up resources
  • Keep setup minimal and focused
  • Ensure teardown runs even if test fails

Mocking and Test Doubles

When to Use Mocks

  • Mock external dependencies: APIs, databases, file systems
  • Mock slow operations: Network calls, heavy computations
  • Mock unpredictable behavior: Random values, current time
  • Mock unavailable services: Third-party services

Mocking Principles

  • Mock at boundaries, not internally
  • Keep mocks simple and focused
  • Verify mock expectations when relevant
  • Wrap external libraries/frameworks behind adapters and mock the adapter

Data Layer Testing

Mock Limitations for Data Layer

Mocks validate call patterns but cannot verify data layer correctness. The following pass through undetected with mock-only testing:

  • Schema mismatches (table names, column names, data types)
  • Query correctness (joins, filters, aggregations, grouping)
  • Database constraints (NOT NULL, UNIQUE, foreign keys)
  • Migration drift (schema changes that make code out of sync)

When Mocks Are Appropriate for Data Access

  • Testing business logic that receives data from the data layer (mock the repository, test the service)
  • Testing error handling paths (simulating connection failures, timeouts)
  • Unit tests where data access is a dependency, not the subject under test

When Mocks Are Insufficient for Data Access

  • Testing repository or data access implementations themselves
  • Verifying query correctness (joins, filters, aggregations, grouping)
  • Testing data integrity constraints
  • Testing migration compatibility

Real Database Testing (Environment-Dependent)

Options for verifying data layer correctness against a real database engine:

  • Containerized databases for CI environments
  • In-memory databases for fast feedback (note: dialect differences may mask issues)
  • Dedicated test databases with seed data

The appropriate approach depends on project environment and CI/CD capabilities.

AI-Generated Code and Schema Awareness

  • AI-generated data access code has heightened schema hallucination risk
  • Generated queries may use correct syntax but reference nonexistent schema elements
  • Mock-based tests pass regardless of schema accuracy
  • Mitigation: Design Docs should include explicit schema references so that documented schemas can be cross-checked against data access code during review

Test Quality Practices

Keep Tests Active

  • Fix or delete failing tests: Resolve failures immediately
  • Remove commented-out tests: Fix them or delete entirely
  • Keep tests running: Broken tests lose value quickly
  • Maintain test suite: Refactor tests as needed

Test Helpers and Utilities

  • Create reusable test data builders
  • Extract common setup into helper functions
  • Build test utilities for complex scenarios
  • Share helpers across test files appropriately

What to Test

Focus on Behavior

Test observable behavior, not implementation:

Good: Test that function returns expected output ✓ Good: Test that correct API endpoint is called ✗ Bad: Test that internal variable was set ✗ Bad: Test order of private method calls

Test Public APIs

  • Test through public interfaces
  • Avoid testing private methods directly
  • Test return values, outputs, exceptions
  • Test side effects (database, files, logs)

Test Edge Cases

Always test:

  • Boundary conditions: Min/max values, empty collections
  • Error cases: Invalid input, null values, missing data
  • Edge cases: Special characters, extreme values
  • Happy path: Normal, expected usage

Test Quality Criteria

These criteria ensure reliable, maintainable tests.

Literal Expected Values

  • Use hardcoded literal values in assertions
  • Calculate expected values independently from the implementation
  • If the implementation has a bug, the test catches it through independent verification
  • If expected value equals mock return value unchanged, the test verifies nothing (no transformation occurred)

Result-Based Verification

  • Verify final results and observable outcomes
  • Assert on return values, output data, or system state changes
  • For mock verification, check that correct arguments were passed

Meaningful Assertions

  • Every test must include at least one assertion
  • Assertions must validate observable behavior
  • A test without assertions always passes and provides no value

Appropriate Mock Scope

  • Mock direct external I/O dependencies: databases, HTTP clients, file systems
  • Use real implementations for internal utilities and business logic
  • Over-mocking reduces test value by verifying wiring instead of behavior

Boundary Value Testing

Test at boundaries of valid input ranges:

  • Minimum valid value
  • Maximum valid value
  • Just below minimum (invalid)
  • Just above maximum (invalid)
  • Empty input (where applicable)

Test Independence Verification

Each test must:

  • Create its own test data
  • Not depend on execution order
  • Clean up its own state
  • Pass when run in isolation

Verification Requirements

Before Commit

  • ✓ All tests pass — fix failing tests immediately
  • ✓ No tests skipped or commented — delete or fix
  • ✓ No debug code left in tests
  • ✓ Test coverage meets standards
  • ✓ No flaky tests — make deterministic
  • ✓ Tests run within performance thresholds

Test Organization

File Structure

  • Mirror production structure: Tests follow code organization
  • Clear naming conventions: Follow project's test file patterns
    • Examples: UserService.test.*, user_service_test.*, test_user_service.*, UserServiceTests.*
  • Logical grouping: Group related tests together
  • Separate test types: Unit, integration, e2e in separate directories

Performance Considerations

Test Speed

  • Unit tests: < 100ms each
  • Integration tests: < 1s each
  • Full suite: Should run frequently (< 10 minutes)

Optimization Strategies

  • Run tests in parallel when possible
  • Use in-memory databases for tests
  • Mock expensive operations
  • Split slow test suites
  • Profile and optimize slow tests

Continuous Integration

CI/CD Requirements

  • Run full test suite on every commit
  • Block merges if tests fail
  • Run tests in isolated environments
  • Test on target platforms/versions

Test Reports

  • Generate coverage reports
  • Track test execution time
  • Identify flaky tests
  • Monitor test trends

Test Design Guardrails

Every Test Must

  • Include at least one meaningful assertion
  • Create its own test data and clean up its own state
  • Pass when run in any order and in isolation
  • Test observable behavior through public interfaces
  • Keep test logic simple (no branching, no loops)
  • Mock only external I/O boundaries, use real implementations for internal logic

Flaky Test Resolution

  • Use deterministic time mocking instead of real clocks
  • Use fixed seed values instead of random data
  • Ensure proper resource cleanup in teardown
  • Resolve race conditions with synchronization primitives

Regression Testing

Prevent Regressions

  • Add test for every bug fix
  • Maintain comprehensive test suite
  • Run full suite regularly
  • Keep all tests unless the tested functionality is removed

Legacy Code

  • Add characterization tests before refactoring
  • Test existing behavior first
  • Gradually improve coverage
  • Refactor with confidence

Testing Best Practices by Language Paradigm

Type System Utilization

For languages with static type systems:

  • Leverage compile-time verification for correctness
  • Focus tests on business logic and runtime behavior
  • Use language's type system to prevent invalid states

For languages with dynamic typing:

  • Add comprehensive runtime validation tests
  • Explicitly test data contract validation
  • Consider property-based testing for broader coverage

Programming Paradigm Considerations

Functional approach:

  • Test pure functions thoroughly (deterministic, no side effects)
  • Test side effects at system boundaries
  • Leverage property-based testing for invariants

Object-oriented approach:

  • Test behavior through public interfaces
  • Mock dependencies via abstraction layers
  • Test polymorphic behavior carefully

Common principle: Adapt testing strategy to leverage language strengths while ensuring comprehensive coverage

Documentation and Communication

Tests as Documentation

  • Tests document expected behavior
  • Use clear, descriptive test names
  • Include examples of usage
  • Show edge cases and error handling

Test Failure Messages

  • Provide clear, actionable error messages
  • Include actual vs expected values
  • Add context about what was being tested
  • Make debugging easier
提供React/TypeScript前端开发规范,涵盖类型安全(禁用any)、组件设计、状态管理及代码重构原则。指导编写高类型安全性的组件、Hook及处理外部数据流,强调通过类型守卫和现代TS特性保障代码健壮性。
实现React组件 编写TypeScript代码 前端功能开发 处理API响应或URL参数类型
dev-skills/skills/typescript-rules/SKILL.md
npx skills add shinpr/claude-code-workflows --skill typescript-rules -g -y
SKILL.md
Frontmatter
{
    "name": "typescript-rules",
    "description": "React\/TypeScript frontend development rules including type safety, component design, state management, and error handling. Use when implementing React components, TypeScript code, or frontend features."
}

TypeScript Development Rules (Frontend)

Basic Principles

  • Aggressive Refactoring - Prevent technical debt and maintain health
  • Delete code when no current caller exists - YAGNI principle (Kent Beck)

Comment Writing Rules

Code first: names and types carry meaning; a comment must add what code cannot, and one comment per decision is enough. Frontend specifics:

  • Comment intent, not markup: explain why a component memoizes, guards, or re-renders — not what the JSX renders
  • Timeless content only: Record decisions and rationale; leave chronological history to version control

Type Safety

Absolute Rule: Replace every any with unknown, generics, or union types. any disables type checking and causes runtime errors.

any Type Alternatives (Priority Order)

  1. unknown Type + Type Guards: Use for validating external input (API responses, localStorage, URL parameters)
  2. Generics: When type flexibility is needed
  3. Union Types・Intersection Types: Combinations of multiple types
  4. Type Assertions (Last Resort): Only when type is certain

Type Guard Implementation Pattern

function isUser(value: unknown): value is User {
  return typeof value === 'object' && value !== null && 'id' in value && 'name' in value
}

Modern Type Features

  • satisfies Operator: const config = { apiUrl: '/api' } satisfies Config - Preserves inference
  • const Assertion: const ROUTES = { HOME: '/' } as const satisfies Routes - Immutable and type-safe
  • Branded Types: type UserId = string & { __brand: 'UserId' } - Distinguish meaning
  • Template Literal Types: type EventName = \on${Capitalize}`` - Express string patterns with types

Type Safety in Frontend Implementation

  • React Props/State: TypeScript manages types, unknown unnecessary
  • External API Responses: Always receive as unknown, validate with type guards
  • localStorage/sessionStorage: Treat as unknown, validate
  • URL Parameters: Treat as unknown, validate
  • Form Input (Controlled Components): Type-safe with React synthetic events

Type Safety in Data Flow

  • Frontend → Backend: Props/State (Type Guaranteed) → API Request (Serialization)
  • Backend → Frontend: API Response (unknown) → Type Guard → State (Type Guaranteed)

Type Complexity Management

  • Props Design:
    • Props count: 3-7 props ideal (consider component splitting if exceeds 10)
    • Optional Props: 50% or less (consider default values or Context if excessive)
    • Nesting: Up to 2 levels (flatten deeper structures)
  • Type Assertions: Review design if used 3+ times
  • External API Types: Relax constraints and define according to reality (convert appropriately internally)

Coding Conventions

Component Design Criteria

  • Function components only: Official React recommendation, optimizable by modern tooling (Exception: Error Boundary requires class component)
  • Custom Hooks: Standard pattern for logic reuse and dependency injection
  • Component Hierarchy: Use the project's adopted component architecture. When the project uses Atomic Design: Atoms → Molecules → Organisms → Templates → Pages. When the project uses Feature-based, Container-Presenter, or another structure: follow that structure consistently and document the chosen layering in the project README or design doc
  • Co-location: Place tests, styles, and related files alongside components

Server/Client Boundary (RSC frameworks only — e.g., Next.js App Router)

  • Default to server components for data fetching and rendering; isolate interactivity behind a "use client" boundary at the smallest scope that needs it
  • Keep browser-only APIs (window, localStorage, event handlers) inside client components; calling them in a server component breaks the render
  • N/A for client-only SPAs (e.g., Vite) — skip when the project has no server-component runtime

State Management Patterns

  • Local State: useState for component-specific state
  • Context API: For sharing state across component tree (theme, auth, etc.)
  • Custom Hooks: Encapsulate state logic and side effects
  • Server State: React Query or SWR for API data caching

Data Flow Principles

  • Single Source of Truth: Each piece of state has one authoritative source
  • Unidirectional Flow: Data flows top-down via props
  • Immutable Updates: Use immutable patterns for state updates
// Immutable state update — always create new arrays/objects
setUsers(prev => [...prev, newUser])

Function Design

  • 0-2 parameters maximum: Use object for 3+ parameters
    function createUser({ name, email, role }: CreateUserParams) {}
    

Props Design (Props-driven Approach)

  • Props are the interface: Define all necessary information as props
  • Pass all data dependencies as props; use Context only for cross-cutting concerns (theme, auth, locale)
  • Type-safe: Always define Props type explicitly

Environment Variables

  • Use the build tool's env accessor: read client-side env through the bundler's exposed accessor — Vite via import.meta.env, Next.js/CRA via prefixed process.env. Raw, unprefixed access is undefined in the browser bundle
  • Only prefixed vars reach the client: build tools expose only vars carrying their public prefix; an unprefixed var is undefined in the browser. The prefix differs per tool — match the project's bundler (Vite VITE_, Next.js public NEXT_PUBLIC_, CRA REACT_APP_)
  • Centrally manage env through a typed config object with a default for every variable
// Client-exposed env must carry the bundler's public prefix, or it is undefined in the browser.
// Vite:    import.meta.env.VITE_API_URL
// Next.js: process.env.NEXT_PUBLIC_API_URL
const config = {
  apiUrl: import.meta.env.VITE_API_URL || 'http://localhost:3000', // adjust accessor + prefix to the project's bundler
  appName: import.meta.env.VITE_APP_NAME || 'My App'
}

Security (Client-side Constraints)

  • CRITICAL: All frontend code is public and visible in browser
  • All secrets stay server-side: Store API keys, tokens, and secrets on the backend only
  • Exclude .env files via .gitignore
  • Limit error messages to non-sensitive context
// Backend manages secrets, frontend accesses via proxy
const response = await fetch('/api/data') // Backend handles API key authentication

Dependency Injection

  • Custom Hooks for dependency injection: Ensure testability and modularity

Asynchronous Processing

  • Promise Handling: Always use async/await
  • Error Handling: Always handle with try-catch or Error Boundary
  • Type Definition: Explicitly define return value types (e.g., Promise<Result>)
  • Effect race/cleanup: guard useEffect data fetches against out-of-order responses and post-unmount state updates — abort or ignore stale results (AbortController or a mounted flag), or use a server-state library (React Query/SWR) that cancels and dedupes. try-catch alone does not cover this

Format Rules

  • Semicolon omission (follow Biome settings)
  • Types in PascalCase, variables/functions in camelCase
  • Imports use absolute paths (src/)

Clean Code Principles

  • Delete unused code immediately
  • Delete debug console.log()
  • Delete commented-out code (retrieve from version control when needed)
  • Comments explain "why" (not "what")

Error Handling

Absolute Rule: Every caught error must be logged with context and either re-thrown to Error Boundary, returned as a Result error variant, or displayed as user-facing error state.

Fail-Fast Principle: Fail quickly on errors to prevent continued processing in invalid states

catch (error) {
  logger.error('Processing failed', error)
  throw error // Handle with Error Boundary or higher layer
}

Result Type Pattern: Express errors with types for explicit handling

type Result<T, E> = { ok: true; value: T } | { ok: false; error: E }

// Example: Express error possibility with types
function parseUser(data: unknown): Result<User, ValidationError> {
  if (!isValid(data)) return { ok: false, error: new ValidationError() }
  return { ok: true, value: data as User }
}

Custom Error Classes

export class AppError extends Error {
  constructor(message: string, public readonly code: string, public readonly statusCode = 500) {
    super(message)
    this.name = this.constructor.name
  }
}
// Purpose-specific: ValidationError(400), ApiError(502), NotFoundError(404)

Layer-Specific Error Handling (React)

  • Error Boundary: Catch React component errors, display fallback UI
  • Custom Hook: Detect business rule violations, propagate AppError as-is
  • API Layer: Convert fetch errors to domain errors

Structured Logging and Sensitive Information Protection Redact sensitive fields (password, token, apiKey, secret, creditCard) before logging

Asynchronous Error Handling in React

  • Error Boundary setup mandatory: Catch rendering errors
  • Use try-catch with all async/await in event handlers
  • Always log and re-throw errors or display error state

Refactoring Techniques

Basic Policy

  • Small Steps: Maintain always-working state through gradual improvements
  • Safe Changes: Minimize the scope of changes at once
  • Behavior Guarantee: Ensure existing behavior remains unchanged while proceeding

Implementation Procedure: Understand Current State → Gradual Changes → Behavior Verification → Final Validation

Priority: Duplicate Code Removal > Large Function Division > Complex Conditional Branch Simplification > Type Safety Improvement

Performance Optimization

  • Automatic memoization: when React Compiler is enabled, rely on it; reach for manual React.memo/useMemo/useCallback only as a profiler- or identity-justified escape hatch (a measured bottleneck, or stable reference identity for third-party APIs / effect dependencies)
  • State Optimization: Minimize re-renders with proper state structure
  • Lazy Loading: Use React.lazy and Suspense for code splitting
  • Bundle Size: Monitor via the build script against the project's budget

Non-functional Requirements

  • Browser Compatibility: Chrome/Firefox/Safari/Edge (latest 2 versions)
  • Rendering Time: Within 5 seconds for major pages
提供AI开发技术决策标准、反模式检测及故障优先设计原则。用于识别代码异味、规范错误处理流程,确保技术决策质量与系统可维护性,防止技术债务积累。
进行技术架构或代码设计决策时 检测代码异味或潜在的反模式 执行代码质量保证或审查时
dev-workflows-frontend/skills/ai-development-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill ai-development-guide -g -y
SKILL.md
Frontmatter
{
    "name": "ai-development-guide",
    "description": "Technical decision criteria, anti-pattern detection, debugging techniques, and quality check workflow. Use when making technical decisions, detecting code smells, or performing quality assurance."
}

AI Developer Guide - Technical Decision Criteria and Anti-pattern Collection

Technical Anti-patterns (Red Flag Patterns)

Immediately stop and reconsider design when detecting the following patterns:

Code Quality Anti-patterns

  1. Writing similar code 3 or more times - Violates Rule of Three
  2. Multiple responsibilities mixed in a single file - Violates Single Responsibility Principle (SRP)
  3. Defining same content in multiple files - Violates DRY principle
  4. Making changes without checking dependencies - Potential for unexpected impacts
  5. Disabling code with comments - Should use version control
  6. Error suppression - Hiding problems creates technical debt
  7. Bypassing safety mechanisms (type systems, validation, contracts) - Circumventing language's correctness guarantees

Design Anti-patterns

  • "Make it work for now" thinking - Accumulation of technical debt
  • Patchwork implementation - Unplanned additions to existing code
  • Optimistic implementation of uncertain technology - Designing unknown elements assuming "it'll probably work"
  • Symptomatic fixes - Surface-level fixes that don't solve root causes
  • Unplanned large-scale changes - Lack of incremental approach

Fail-Fast Fallback Design Principles

Core Principle

Make all errors visible and traceable with full context. Prioritize primary code reliability over fallback implementations. Excessive fallback mechanisms mask errors and make debugging difficult.

Implementation Guidelines

Default Approach

  • Propagate all errors explicitly unless a Design Doc specifies a fallback
  • Make failures explicit: Errors should be visible and traceable
  • Preserve error context: Include original error information when re-throwing

When Fallbacks Are Acceptable

  • Only with explicit Design Doc approval: Document why fallback is necessary
  • Business-critical continuity: When partial functionality is better than none
  • Graceful degradation paths: Clearly defined degraded service levels

Layer Responsibilities

  • Infrastructure Layer:

    • Always throw errors upward
    • No business logic decisions
    • Provide detailed error context
  • Application Layer:

    • Make business-driven error handling decisions
    • Implement fallbacks only when specified in requirements
    • Log all fallback activations for monitoring

Error Masking Detection

Review Triggers (require design review):

  • Writing 3rd error handler in the same feature
  • Multiple error handling blocks in single function/method
  • Nested error handling structures
  • Error handlers that return default values without logging

Before Implementing Any Fallback:

  1. Verify Design Doc explicitly defines this fallback
  2. Document the business justification
  3. Ensure error is logged with full context
  4. Add monitoring/alerting for fallback activation

Implementation Pattern

AVOID: Silent fallback that hides errors
    <handle error>:
        return DEFAULT_VALUE  // Error hidden, debugging impossible

PREFERRED: Explicit failure with context
    <handle error>:
        log_error('Operation failed', context, error)
        <propagate error>  // Re-throw exception, return Error, return error tuple

Adaptation: Use language-appropriate error handling (exceptions, Result types, error tuples, etc.)

Rule of Three - Criteria for Code Duplication

How to handle duplicate code based on Martin Fowler's "Refactoring":

Duplication Count Action Reason
1st time Inline implementation Cannot predict future changes
2nd time Consider future consolidation Pattern beginning to emerge
3rd time Implement commonalization Pattern established

Criteria for Commonalization

Cases for Commonalization

  • Business logic duplication
  • Complex processing algorithms
  • Areas likely requiring bulk changes
  • Validation rules

Cases to Avoid Commonalization

  • Accidental matches (coincidentally same code)
  • Possibility of evolving in different directions
  • Significant readability decrease from commonalization
  • Simple helpers in test code

Common Failure Patterns and Avoidance Methods

Pattern 1: Error Fix Chain

Symptom: Fixing one error causes new errors Cause: Surface-level fixes without understanding root cause Avoidance: Identify root cause with 5 Whys before fixing

Pattern 2: Circumventing Correctness Guarantees

Symptom: Bypassing safety mechanisms (type systems, validation, contracts) Cause: Impulse to avoid correctness errors Avoidance: Use language-appropriate safety mechanisms (static checking, runtime validation, contracts, assertions)

Pattern 3: Implementation Without Sufficient Testing

Symptom: Many bugs after implementation Cause: Ignoring Red-Green-Refactor process Avoidance: Always start with failing tests

Pattern 4: Ignoring Technical Uncertainty

Symptom: Frequent unexpected errors when introducing new technology Cause: Assuming "it should work according to official documentation" without prior investigation Avoidance:

  • Record certainty evaluation at the beginning of task files
    Certainty: low (Reason: no working examples found for this integration)
    Exploratory implementation: true
    Fallback: use established alternative approach
    
  • For low certainty cases, create minimal verification code first

Pattern 5: Insufficient Existing Code Investigation

Symptom: Duplicate implementations, architecture inconsistency, integration failures, adopting outdated patterns Cause: Insufficient understanding of existing code before implementation; referencing only nearby files without verifying representativeness Avoidance Methods:

  • Before implementation, always search for similar functionality (using domain, responsibility, configuration patterns as keywords)
  • Similar functionality found → Use that implementation (do not create new implementation)
  • Similar functionality is technical debt → Create ADR improvement proposal before implementation
  • No similar functionality exists → Implement new functionality following existing design philosophy
  • Record all decisions and rationale in "Existing Codebase Analysis" section of Design Doc
  • Reference representativeness check: When adopting a pattern or dependency from nearby code, verify it is representative across the repository before adopting — nearby files alone are an insufficient basis

Debugging Techniques

1. Error Analysis Procedure

  1. Read error message (first line) accurately
  2. Focus on first and last of stack trace
  3. Identify first line where your code appears

2. 5 Whys - Root Cause Analysis

Trace the failure through repeated "why" questions until the root cause is actionable.

3. Minimal Reproduction Code

To isolate problems, attempt reproduction with minimal code:

  • Remove unrelated parts
  • Replace external dependencies with mocks
  • Create minimal configuration that reproduces problem

4. Debug Log Output

Include operation context, relevant input data, current state, and timestamp.

Quality Assurance Mechanism Awareness

Before executing quality checks, identify what quality mechanisms exist for the change area:

  • Primary detection: inspect the change area's file types, project manifest, and configuration to identify applicable quality tools
    • Check CI pipeline definitions for checks that cover the affected paths
    • Check for domain-specific linter or validator configurations (e.g., schema validators, API spec validators, configuration file linters)
    • Check for domain-specific constraints in project configuration (naming rules, length limits, format requirements)
  • Supplementary hint: IF task file specifies Quality Assurance Mechanisms → use them as additional hints for which domain-specific checks to look for
  • Include discovered domain-specific checks alongside standard quality phases below

Quality Check Workflow

Universal quality assurance phases applicable to all languages:

Phase 1: Static Analysis

  1. Code Style Checking: Verify adherence to style guidelines
  2. Code Formatting: Ensure consistent formatting
  3. Unused Code Detection: Identify dead code and unused imports/variables
  4. Static Type Checking: Verify type correctness (for statically typed languages)
  5. Static Analysis: Detect potential bugs, security issues, code smells

Phase 2: Build Verification

  1. Compilation/Build: Verify code builds successfully (for compiled languages)
  2. Dependency Resolution: Ensure all dependencies are available and compatible
  3. Resource Validation: Check configuration files, assets are valid

Phase 3: Testing

  1. Unit Tests: Run all unit tests
  2. Integration Tests: Run integration tests
  3. Test Coverage: Measure and verify coverage meets standards
  4. E2E Tests: Run end-to-end tests

Phase 4: Final Quality Gate

All checks must pass before proceeding:

  • Zero static analysis errors
  • Build succeeds
  • All tests pass
  • Coverage meets project-configured threshold

Quality Check Pattern (Language-Agnostic)

Workflow:
1. Format check → 2. Lint/Style → 3. Static analysis →
4. Build/Compile → 5. Unit tests → 6. Coverage check →
7. Integration tests → 8. Final gate

Auto-fix capabilities (when available):
- Format auto-fix
- Lint auto-fix
- Dependency/import organization
- Simple code smell corrections

Situations Requiring Technical Decisions

Timing of Abstraction

  • Extract patterns after writing concrete implementation 3 times
  • Be conscious of YAGNI, implement only currently needed features
  • Prioritize current simplicity over future extensibility

Performance vs Readability

  • Prioritize readability unless profiling identifies a measurable bottleneck (e.g., response time exceeding SLA, memory exceeding allocation)
  • Measure before optimizing
  • Document reason with comments when optimizing

Granularity of Contracts and Interfaces

  • Overly detailed contracts reduce maintainability
  • Design interfaces where each method maps to a single domain operation and parameter types use domain vocabulary
  • Use abstraction mechanisms to reduce duplication

Scope Expansion

  • Apply implementation/edit instructions to the user's or task's specified scope. Escalate before expanding it.
  • Treat explicit quantities and targets ("one", "this file", "only X") as boundaries
  • Copy/move/mirror requests preserve content verbatim; edit content only when requested
  • Port/translation requests preserve intent and behavior; adapt only what the destination context requires
  • Before changing related files, symmetric locations, adjacent behavior, or adding helpful extras, escalate with the proposed expansion

Implementation Completeness Assurance

Impact Analysis: Mandatory 3-Stage Process

Complete these stages sequentially before any implementation:

1. Discovery - Identify all affected code:

  • Implementation references (imports, calls, instantiations)
  • Interface dependencies (contracts, types, data structures)
  • Test coverage
  • Configuration (build configs, env settings, feature flags)
  • Documentation (comments, docs, diagrams)

2. Understanding - Analyze each discovered location:

  • Role and purpose in the system
  • Dependency direction (consumer or provider)
  • Data flow (origin → transformations → destination)
  • Coupling strength

3. Identification - Produce structured report:

## Impact Analysis
### Direct Impact
- [Unit]: [Reason and modification needed]

### Indirect Impact
- [System]: [Integration path → reason]

### Data Flow
[Source] → [Transformation] → [Consumer]

### Risk Assessment
- High: [Complex dependencies, fragile areas]
- Medium: [Moderate coupling, test gaps]
- Low: [Isolated, well-tested areas]

### Implementation Order
1. [Start with lowest risk or deepest dependency]
2. [...]

Critical: Do not implement until all 3 stages are documented

Unused Code Deletion

When unused code is detected:

  • Will it be used in this work? Yes → Implement now | No → Delete now (Git preserves)
  • Applies to: Code, tests, docs, configs, assets

Existing Code Modification

In use? No → Delete
       Yes → Working? No → Delete + Reimplement
                     Yes → Fix/Extend

Principle: Prefer clean implementation over patching broken code

提供语言无关的代码原则,强调可维护性、简洁性和显式表达。指导功能实现、重构及代码审查,涵盖命名规范、函数设计(少参数、单一职责)、错误处理及持续改进策略,旨在提升代码质量与可读性。
实现新功能 重构现有代码 进行代码质量审查
dev-workflows-frontend/skills/coding-principles/SKILL.md
npx skills add shinpr/claude-code-workflows --skill coding-principles -g -y
SKILL.md
Frontmatter
{
    "name": "coding-principles",
    "description": "Language-agnostic coding principles for maintainability, readability, and quality. Use when implementing features, refactoring code, or reviewing code quality."
}

Language-Agnostic Coding Principles

Core Philosophy

  1. Maintainability over Speed: Prioritize long-term code health over initial development velocity
  2. Simplicity First: Choose the simplest solution that meets requirements (YAGNI principle)
  3. Minimum Surface for Required Coverage: When introducing maintenance-surface-bearing elements (persistent state, public-contract or cross-boundary fields/props, behavioral modes/flags/variants, reusable abstractions, or component splits), select the smallest design surface that covers the current user-visible requirements and accepted technical constraints (audit, data integrity, compatibility, security, performance, accessibility). Adoption is justified by naming a current requirement or constraint that smaller alternatives fail to cover; value-based arguments serve as tiebreakers. Distinct from YAGNI (time-axis judgment of present vs. future need), this principle governs surface-area minimization at a fixed coverage point.
  4. Explicit over Implicit: Make intentions clear through code structure and naming
  5. Delete over Comment: Remove unused code instead of commenting it out

Code Quality

Continuous Improvement

  • Refactor related code within each change set — address style, naming, or structure issues in the files being modified
  • Improve code structure incrementally
  • Keep the codebase lean and focused
  • Delete unused code immediately

Readability

  • Use meaningful, descriptive names drawn from the problem domain
  • Use full words in names; abbreviations are acceptable only when widely recognized in the domain
  • Use descriptive names; single-letter names are acceptable only for loop counters or well-known conventions (i, j, x, y)
  • Extract magic numbers and strings into named constants
  • Keep code self-documenting where possible

Function Design

Parameter Management

  • Recommended: 0-2 parameters per function
  • For 3+ parameters: Use objects, structs, or dictionaries to group related parameters
  • Example (conceptual):
    // Instead of: createUser(name, email, age, city, country)
    // Use: createUser(userData)
    

Single Responsibility

  • Each function should do one thing well
  • Keep functions small and focused (typically < 50 lines)
  • Extract complex logic into separate, well-named functions
  • Functions should have a single level of abstraction

Function Organization

  • Pure functions when possible (no side effects)
  • Separate data transformation from side effects
  • Use early returns to reduce nesting
  • Keep nesting to a maximum of 3 levels; use early returns or extracted functions to flatten deeper nesting

Error Handling

Error Management Principles

  • Always handle errors: Log with context or propagate explicitly
  • Log appropriately: Include context for debugging
  • Protect sensitive data: Mask or exclude passwords, tokens, PII from logs
  • Fail fast: Detect and report errors as early as possible

Error Propagation

  • Use language-appropriate error handling mechanisms
  • Propagate errors to appropriate handling levels
  • Provide meaningful error messages
  • Include error context when re-throwing

Dependency Management

Loose Coupling via Parameterized Dependencies

  • Inject external dependencies as parameters (constructor injection for classes, function parameters for procedural/functional code)
  • Depend on abstractions, not concrete implementations
  • Minimize inter-module dependencies
  • Facilitate testing through mockable dependencies

Reference Representativeness

Verifying References Before Adoption

When adopting patterns, APIs, or dependencies from existing code:

  • IF referencing only 2-3 nearby files → THEN confirm the pattern is representative by checking usage across the repository before adopting
  • IF multiple approaches coexist in the repository → THEN identify the majority pattern and make a deliberate choice — selecting whichever is nearest is insufficient
  • IF adopting an external dependency (library, plugin, SDK) → THEN verify repository-wide usage distribution for the same dependency; if the appropriate version cannot be determined from repository state alone, escalate
  • IF following an existing pattern → THEN state the reason for following it when an alternative exists (e.g., consistency with surrounding code, avoiding breaking changes, pending coordinated update)

Principle

Nearby code is a starting point for investigation, not a sufficient basis for adoption. Verify that what you reference is representative of the repository's conventions and current best practices before using it as a model.

Performance Considerations

Optimization Approach

  • Measure first: Profile before optimizing
  • Focus on algorithms: Algorithmic complexity > micro-optimizations
  • Use appropriate data structures: Choose based on access patterns
  • Resource management: Handle memory, connections, and files properly

When to Optimize

  • After identifying actual bottlenecks through profiling
  • When performance issues are measurable
  • Optimize only after measurable bottlenecks are identified, not during initial development

Code Organization

Structural Principles

  • Group related functionality: Keep related code together
  • Separate concerns: Domain logic, data access, presentation
  • Consistent naming: Follow project conventions
  • Module cohesion: High cohesion within modules, low coupling between

File Organization

  • One primary responsibility per file
  • Logical grouping of related functions/classes
  • Clear folder structure reflecting architecture
  • Avoid "god files" (files > 500 lines)

Commenting Principles

Default: code first

Names, types, and structure are the primary medium. A comment earns its place only by carrying information the code itself cannot express. When in doubt, improve the name instead of adding a comment.

The test for every comment

A comment is justified only if it answers one of these:

  • Why: reasoning, trade-off, or constraint behind a non-obvious decision
  • Limitation / edge case: a boundary a reader cannot infer from the code
  • Public API contract: behavior, inputs, outputs of an exported interface

One comment per decision. If a comment restates what the names and control flow already show, delete it and rename instead.

Comment Scope

  • Comment the why, limits, and public contracts (per the test above); let names and structure carry everything else, including the "how"
  • Record historical context in version control commit messages, not in comments
  • Delete commented-out code (retrieve from git history when needed)

Comment Quality

  • Write comments that remain accurate regardless of future code changes; avoid references to dates, versions, or temporary state
  • Update comments when changing code
  • Use proper grammar and formatting
  • Write for future maintainers

Refactoring Approach

Safe Refactoring

  • Small steps: Make one change at a time
  • Maintain working state: Keep tests passing
  • Verify behavior: Run tests after each change
  • Incremental improvement: Don't aim for perfection immediately

Refactoring Triggers

  • Code duplication (DRY principle)
  • Functions > 50 lines
  • Complex conditional logic
  • Unclear naming or structure

Testing Considerations

Testability

  • Write testable code from the start
  • Avoid hidden dependencies
  • Keep side effects explicit
  • Design for parameterized dependencies

Test-Driven Development

  • Write tests before implementation when appropriate
  • Keep tests simple and focused
  • Test behavior, not implementation
  • Maintain test quality equal to production code

Security Principles

Secure Defaults

  • Store credentials and secrets through environment variables or dedicated secret managers
  • Use parameterized queries (prepared statements) for all database access
  • Use established cryptographic libraries provided by the language or framework
  • Generate security-critical values (tokens, IDs, nonces) with cryptographically secure random generators
  • Encrypt sensitive data at rest and in transit using standard protocols

Input and Output Boundaries

  • Validate all external input at system entry points for expected format, type, and length
  • Encode output appropriately for its rendering context (HTML, SQL, shell, URL)
  • Return only information necessary for the caller in error responses; log detailed diagnostics server-side

Access Control

  • Apply authentication to all entry points that handle user data or trigger state changes
  • Verify authorization for each resource access, not only at the entry point
  • Grant only the permissions required for the operation (files, database connections, API scopes)

Knowledge Cutoff Supplement (2026-03)

  • OWASP Top 10:2025 shifted from symptoms to root causes; added "Software Supply Chain Failures" (A03) and "Mishandling of Exceptional Conditions" (A10)
  • Recent research indicates AI-generated code shows elevated rates of access control gaps — treat authentication and authorization as high-priority review targets
  • OpenSSF published "Security-Focused Guide for AI Code Assistant Instructions" — recommends language-specific, actionable constraints over generic advice
  • For detailed detection patterns, see references/security-checks.md

Documentation

Code Documentation

  • Document public APIs and interfaces
  • Include usage examples for complex functionality
  • Maintain README files for modules
  • Update documentation in the same commit that changes the corresponding behavior

Architecture Documentation

  • Document high-level design decisions
  • Explain integration points
  • Clarify data flows and boundaries
  • Record trade-offs and alternatives considered

Version Control Practices

Commit Practices

  • Make atomic, focused commits
  • Write clear, descriptive commit messages
  • Commit working code (passes tests)
  • Commit only production-ready code; store secrets in environment variables or secret managers

Code Review Readiness

  • Self-review before requesting review
  • Keep changes focused and reviewable
  • Provide context in pull request descriptions
  • Respond to feedback constructively

Language-Specific Adaptations

While these principles are language-agnostic, adapt them to your specific programming language:

  • Static typing: Use strong types when available
  • Dynamic typing: Add runtime validation
  • OOP languages: Apply SOLID principles
  • Functional languages: Prefer pure functions and immutability
  • Concurrency: Follow language-specific patterns for thread safety
提供PRD、ADR、设计文档等模板及创建标准。根据变更类型(如新功能、架构调整)和文件规模,指导生成所需文档及顺序,确保技术文档规范与可追溯性。
创建或审查技术文档 确定需要哪些文档 涉及架构决策或复杂逻辑实现
dev-workflows-frontend/skills/documentation-criteria/SKILL.md
npx skills add shinpr/claude-code-workflows --skill documentation-criteria -g -y
SKILL.md
Frontmatter
{
    "name": "documentation-criteria",
    "description": "Documentation creation criteria including PRD, ADR, Design Doc, and Work Plan requirements with templates. Use when creating or reviewing technical documents, or determining which documents are required."
}

Documentation Creation Criteria

Templates

Creation Decision Matrix

Condition Required Documents Creation Order
New Feature Addition (backend) PRD → [ADR] → Design Doc → Work Plan After PRD approval
New Feature Addition (frontend/fullstack) PRD → UI Spec → [ADR] → Design Doc → Work Plan UI Spec before Design Doc
ADR Conditions Met (see below) ADR → Design Doc → Work Plan Start immediately
6+ Files [ADR if conditions apply] → Design Doc → Work Plan (Design Doc + Work Plan required) Start immediately
3-5 Files Design Doc → Work Plan (Required) Start immediately
1-2 Files None Direct implementation

ADR Creation Conditions (Required if Any Apply)

1. Contract System Changes

  • Adding nested contracts with 3+ levels: Contract A { Contract B { Contract C { field: T } } }
    • Rationale: Deep nesting has high complexity and wide impact scope
  • Changing/deleting contracts used in 3+ locations
    • Rationale: Multiple location impacts require careful consideration
  • Contract responsibility changes (e.g., DTO→Entity, Request→Domain)
    • Rationale: Conceptual model changes affect design philosophy

2. Data Flow Changes

  • Storage location changes (DB→File, Memory→Cache)
  • Processing order changes with 3+ steps
    • Example: "Input→Validation→Save" to "Input→Save→Async Validation"
  • Data passing method changes (parameter passing→shared state, direct reference→event-based communication)

3. Architecture Changes

  • Layer addition, responsibility changes, component relocation

4. External Dependency Changes

  • Library/framework/external API introduction or replacement

5. Complex Implementation Logic (Regardless of Scale)

  • Managing 3+ states
  • Coordinating 5+ asynchronous processes

Detailed Document Definitions

PRD (Product Requirements Document)

Purpose: Define business requirements and user value

Includes:

  • Business requirements and user value
  • Success metrics and KPIs (each metric specifies a numeric target and measurement method)
  • User stories and use cases
  • MoSCoW prioritization (Must/Should/Could/Won't)
  • Acceptance criteria with sequential IDs (AC-001, AC-002, ...) for downstream traceability
  • MVP and Future phase separation
  • User journey diagram (required)
  • Scope boundary diagram (required)

Scope: Business requirements, user value, success metrics, user stories, and prioritization only. Implementation details belong in Design Doc, technical selection rationale in ADR, phases and task breakdown in Work Plan.

ADR (Architecture Decision Record)

Purpose: Record technical decision rationale and background

Includes:

  • Decision (what was selected)
  • Rationale (why that selection was made)
  • Option comparison (minimum 3 options) and trade-offs
  • Architecture impact
  • Principled implementation guidelines (e.g., "Use dependency injection")

Scope: Decision, rationale, option comparison, architecture impact, and principled guidelines only. Implementation procedures and code examples belong in Design Doc, schedule and resource assignments in Work Plan.

UI Specification

Purpose: Define UI structure, screen transitions, component decomposition, and interaction design for frontend features

Includes:

  • Screen list and transition conditions
  • Component decomposition with state x display matrix (default/loading/empty/error/partial)
  • Interaction definitions linked to PRD acceptance criteria (EARS format)
  • Prototype management (code-based prototypes as attachments, not source of truth)
  • AC traceability from PRD to screens/components
  • Existing component reuse map and design tokens
  • Visual acceptance criteria (golden states, layout constraints)
  • Accessibility requirements (keyboard, screen reader, contrast)

Scope: Screen structure, transitions, component decomposition, interaction design, and visual acceptance criteria only. Technical implementation and API contracts belong in Design Doc, test implementation in test skeleton generation output, schedule in Work Plan.

Required Structural Elements:

  • At least one component with state x display matrix and interaction table
  • AC traceability table mapping PRD ACs to screens/states
  • Screen list with transition conditions
  • Existing component reuse map (reuse/extend/new decisions)

Prototype Code Handling:

  • Prototype code provided by user is placed in docs/ui-spec/assets/{feature-name}/
  • Prototype is an attachment to UI Spec, never the source of truth
  • UI Spec + Design Doc are the canonical specifications

Design Document

Purpose: Define technical implementation methods in detail

Includes:

  • Existing codebase analysis (required)
    • Implementation path mapping (both existing and new)
    • Integration point clarification (connection points with existing code even for new implementations)
  • Technical implementation approach (vertical/horizontal/hybrid)
  • Technical dependencies and implementation constraints (required implementation order)
  • Interface and contract definitions
  • Data flow and component design
  • Acceptance criteria (each criterion specifies a verifiable condition with pass/fail threshold)
  • Change impact map (clearly specify direct impact/indirect impact/no ripple effect)
  • Complete enumeration of integration points
  • Data contract clarification
  • Agreement checklist (agreements with stakeholders)
  • Code inspection evidence (inspected files/functions during investigation)
  • Field propagation map (when fields cross component boundaries)
  • Data representation decision (when introducing new structures)
  • Applicable standards (explicit/implicit classification)
  • Prerequisite ADRs (including common ADRs)
  • Verification Strategy (required)
    • Correctness proof method (what "correct" means for this change, how it's verified, when)
    • Early verification point (first target to prove the approach works, success criteria, failure response)

Required Structural Elements:

Change Impact Map:
  Change Target: [Component/Feature]
  Direct Impact: [Files/Functions]
  Indirect Impact: [Data format/Processing time]
  No Ripple Effect: [Unaffected features]

Interface Change Matrix:
  Existing: [Function/method/operation name]
  New: [Function/method/operation name]
  Conversion Required: [Yes/No]
  Compatibility Method: [Approach]

Scope: Technical implementation methods, interfaces, data flow, acceptance criteria, and verification strategy only. Technology selection rationale belongs in ADR, schedule and assignments in Work Plan.

Work Plan

Purpose: Implementation task management and progress tracking

Includes:

  • Task breakdown and dependencies (maximum 2 levels)
  • Schedule and duration estimates
  • Include test skeleton file paths produced for this work plan (integration and E2E)
  • Verification Strategy summary (extracted from Design Doc)
  • Final Quality Assurance Phase (required)
  • Progress records (checkbox format)

Scope: Task breakdown, dependencies, schedule, verification strategy summary, and progress tracking only. Technical rationale belongs in ADR, design details in Design Doc.

Phase Division Criteria (adapt to implementation approach from Design Doc):

When Vertical Slice selected:

  • Each phase = one value unit (feature, component, or migration target)
  • Each phase includes its own implementation + verification per Verification Strategy

When Horizontal Slice selected:

  1. Phase 1: Foundation Implementation - Contract definitions, interfaces/signatures, test preparation
  2. Phase 2: Core Feature Implementation - Business logic, unit tests
  3. Phase 3: Integration Implementation - External connections, presentation layer

When Hybrid selected:

  • Combine vertical and horizontal as defined in Design Doc implementation approach

All approaches: Final phase is always Quality Assurance (acceptance criteria achievement, all tests passing, quality checks). Each phase's verification method follows Verification Strategy from Design Doc.

Three Elements of Task Completion Definition:

  1. Implementation Complete: Code is functional
  2. Quality Complete: Tests, static checks, linting pass
  3. Integration Complete: Verified connection with other components

Creation Process

  1. Problem Analysis: Change scale assessment, ADR condition check
    • Identify explicit and implicit project standards before investigation
  2. ADR Option Consideration (ADR only): Compare 3+ options, specify trade-offs
  3. Creation: Use templates, include measurable conditions
  4. Approval: "Accepted" after review enables implementation

Storage Locations

Document Path Naming Convention Template
PRD docs/prd/ [feature-name]-prd.md prd-template.md
ADR docs/adr/ ADR-[4-digits]-[title].md adr-template.md
UI Spec docs/ui-spec/ [feature-name]-ui-spec.md ui-spec-template.md
UI Spec Assets docs/ui-spec/assets/{feature-name}/ Prototype code files -
Design Doc docs/design/ [feature-name]-design.md design-template.md
Work Plan docs/plans/ YYYYMMDD-{type}-{description}.md plan-template.md
Task File docs/plans/tasks/ {plan-name}-task-{number}.md task-template.md

*Note: Work plans are excluded by .gitignore

ADR Status

ProposedAcceptedDeprecated/Superseded/Rejected

AI Automation Rules

  • 6+ files: Suggest ADR creation
  • Contract/data flow change detected: ADR mandatory
  • Check existing ADRs before implementation

Diagram Requirements

Required diagrams for each document (using mermaid notation):

Document Required Diagrams Purpose
PRD User journey diagram, Scope boundary diagram Clarify user experience and scope
ADR Option comparison diagram (when needed) Visualize trade-offs
UI Spec Screen transition diagram, Component tree diagram Clarify screen flow and component structure
Design Doc Architecture diagram, Data flow diagram Understand technical structure
Work Plan Phase structure diagram, Task dependency diagram Clarify implementation order

Common ADR Relationships

  1. At creation: Identify common technical areas (logging, error handling, async processing, etc.), reference existing common ADRs
  2. When missing: Consider creating necessary common ADRs
  3. Design Doc: Specify common ADRs in "Prerequisite ADRs" section
  4. Compliance check: Verify design aligns with common ADR decisions
捕获并持久化仓库外资源(如设计稿、API、IaC)的访问方式,供下游工作确定性调用。当任务依赖外部资源或提及特定来源时触发。
工作依赖外部资源 用户提及设计源、设计系统、API模式、基础设施即代码源或密钥库
dev-workflows-frontend/skills/external-resource-context/SKILL.md
npx skills add shinpr/claude-code-workflows --skill external-resource-context -g -y
SKILL.md
Frontmatter
{
    "name": "external-resource-context",
    "description": "Captures and persists access methods for resources outside the repository (design source, design system, API schema, IaC source, secret store) so downstream work can reach them deterministically. Use when work depends on external resources, or when the user mentions design source, design system, API schema, IaC source, secret store, or canonical source."
}

External Resource Context

Purpose

AI agents understand the codebase but not the external resources surrounding it. This skill captures, in a deterministic location, the access methods to resources outside the repository so downstream work (design, planning, implementation, review) can reach them without re-asking the user.

Resources covered: design origin (where the canonical visual specification lives), design system (component library and tokens), guidelines (usage docs, accessibility rules), visual verification environment (how to confirm rendering), database schema source, migration history, secret store location, API schema source (OpenAPI / proto / GraphQL SDL), mock environment, IaC source, environment configuration.

Scope Boundaries

In scope: hearing protocol, storage location, single-source-of-truth ownership rule, reference protocol for downstream consumers.

Out of scope: enforcing that captured resources are correct or current — verification belongs to the agent that consumes the resource. Generating the resources themselves (e.g., creating a DESIGN.md from scratch).

Storage Locations (Two-Tier)

Tier Location Holds Update Frequency
Project docs/project-context/external-resources.md Environment-stable facts: which resources exist for this project and how to access them (URL, MCP name, file path, command) Rare — only when the project's environment changes
Feature ## External Resources Used section inside the relevant UI Spec or Design Doc The subset of project-tier resources actually used by this feature, plus feature-specific identifiers (e.g., a specific node id within the design tool, a specific endpoint path) Per feature

Single Source of Truth Rule

The project tier owns environment facts. Feature-tier sections list only feature-specific identifiers (node id within the design source, specific endpoint path within the API, specific IaC module name) and reference project-tier entries by label; URLs, MCP names, and access commands remain in the project-tier file. When the environment changes, only the project-tier file is updated.

Example feature-tier entry uses the table format defined in references/template.md: a row with the project-tier label in the first column and the feature-specific identifier in the second column.

Hearing Protocol

When to Hear

Condition Action
docs/project-context/external-resources.md does not exist Run full hearing for the relevant domain(s)
File exists Ask the user via AskUserQuestion: "Update external-resources.md? (no / yes-full / yes-diff-only)". On yes-full run full hearing. On yes-diff-only ask the user which axes changed, hear only those. On no skip hearing

Domain Routing

Load the domain reference matching the current task:

Task type References to load
Frontend (UI work) references/frontend.md
Backend (server / data work) references/backend.md
API contract work references/api.md
Infrastructure / deployment references/infra.md
Fullstack All of the above; per-axis "Not applicable" answers are expected

Each domain reference defines the axes and the question template.

Two-Phase Hearing

  1. Structured hearing — for each axis defined in the domain reference, present the user with AskUserQuestion using the choices listed there (always include "Not applicable" as an option). For each non-N/A axis, follow up with an access-method question (URL / MCP name / file path / command).

  2. Self-declaration — after the structured axes, present a single AskUserQuestion: "Are there any other external resources for this work that the structured questions did not cover? If yes, describe them in your next message." If the user describes additional resources, append them to the storage file under an "Additional resources" subsection.

The two phases are sequential. Self-declaration runs even if the user answered "Not applicable" to every structured axis.

Storage Protocol

After hearing completes:

  1. Build the project-tier content from the answers. Use references/template.md as the structure.
  2. Write to docs/project-context/external-resources.md. Create the directory if absent.
  3. When the calling workflow has a target UI Spec or Design Doc, also append or update the document's ## External Resources Used section with the feature-tier subset (label references + feature-specific identifiers only).
  4. Report the file paths back to the calling workflow.

Reference Protocol (For Downstream Consumers)

Agents that load this skill consult resources in this order:

  1. Read docs/project-context/external-resources.md first (if present) to learn what is available and how to access it.
  2. Read the target UI Spec or Design Doc's ## External Resources Used section for feature-specific identifiers.
  3. Use the access method declared in the project tier (e.g., the named MCP, the URL, the file path) to fetch the actual resource content.

Agents that only need to consult the saved file as input data (not actively hear) can read it directly without loading this skill — frontmatter declaration is reserved for agents that may need to trigger hearing or interpret the protocol semantics.

Output Format

The project-tier file follows the structure in references/template.md. The project-tier file's heading levels and section names are fixed so downstream agents can locate sections deterministically.

For feature-tier sections inside UI Spec or Design Doc, the heading text "External Resources Used" is fixed; the heading level matches the parent document's natural structure (h2 in UI Spec where it is a sibling of other top-level sections, h3 in Design Doc where it sits under Background and Context).

Quality Checklist

  • Each axis answered has both a presence indicator and an access method, or is marked "Not applicable"
  • Self-declaration phase ran even when all structured axes were "Not applicable"
  • Project-tier file does not contain feature-specific identifiers
  • Feature-tier sections reference project-tier entries by label, not by duplicating URLs / MCP names
  • When the project file already existed, the update decision (no / yes-full / yes-diff-only) was confirmed before any write

References

提供前端技术决策标准、反模式识别及质量检查指南。用于在做出前端技术选型或执行质量保证时,规避代码与设计反模式,遵循失败快速原则和Rule of Three重构准则,提升代码可靠性与可维护性。
进行前端技术决策 执行前端代码质量审查 识别代码或设计反模式 处理重复代码重构
dev-workflows-frontend/skills/frontend-ai-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill frontend-ai-guide -g -y
SKILL.md
Frontmatter
{
    "name": "frontend-ai-guide",
    "description": "Frontend-specific technical decision criteria, anti-patterns, debugging techniques, and quality check workflow. Use when making frontend technical decisions or performing quality assurance."
}

AI Developer Guide - Technical Decision Criteria and Anti-pattern Collection (Frontend)

Technical Anti-patterns (Red Flag Patterns)

Immediately stop and reconsider design when detecting the following patterns:

Code Quality Anti-patterns

  1. Writing similar code 3 or more times - Violates Rule of Three
  2. Multiple responsibilities mixed in a single component - Violates Single Responsibility Principle (SRP)
  3. Defining same content in multiple components - Violates DRY principle
  4. Making changes without checking dependencies - Potential for unexpected impacts
  5. Disabling code with comments - Should use version control
  6. Error suppression - Hiding problems creates technical debt
  7. Excessive use of type assertions (as) - Abandoning type safety
  8. Prop drilling through 3+ levels - Should use Context API or state management
  9. Massive components (300+ lines) - Split into smaller components

Design Anti-patterns

  • "Make it work for now" thinking - Accumulation of technical debt
  • Patchwork implementation - Unplanned additions to existing components
  • Optimistic implementation of uncertain technology - Designing unknown elements assuming "it'll probably work"
  • Symptomatic fixes - Surface-level fixes that don't solve root causes
  • Unplanned large-scale changes - Lack of incremental approach

Fallback Design Principles

Core Principle: Fail-Fast

Design philosophy that prioritizes improving primary code reliability over fallback implementations.

Criteria for Fallback Implementation

  • Fallback rule: Implement fallbacks only when explicitly defined in Design Doc
  • Layer Responsibilities:
    • Component Layer: Use Error Boundary for error handling
    • Hook Layer: Implement decisions based on business requirements

Detection of Excessive Fallbacks

  • Require design review when writing the 3rd catch statement in the same feature
  • Verify Design Doc definition before implementing fallbacks
  • Properly log errors and make failures explicit

Rule of Three - Criteria for Code Duplication

How to handle duplicate code based on Martin Fowler's "Refactoring":

Duplication Count Action Reason
1st time Inline implementation Cannot predict future changes
2nd time Consider future consolidation Pattern beginning to emerge
3rd time Implement commonalization Pattern established

Criteria for Commonalization

Cases for Commonalization

  • Business logic duplication
  • Complex processing algorithms
  • Component patterns (form fields, cards, etc.)
  • Custom hooks
  • Validation rules

Cases to Avoid Commonalization

  • Accidental matches (coincidentally same code)
  • Possibility of evolving in different directions
  • Significant readability decrease from commonalization
  • Simple helpers in test code

Implementation Example

// 1st-2nd occurrence: keep separate, no commonalization yet
function UserEmailInput() { /* ... */ }
function ContactEmailInput() { /* ... */ }

// Commonalize on 3rd occurrence
function EmailInput({ context }: { context: 'user' | 'contact' | 'admin' }) { /* ... */ }

Common Failure Patterns and Avoidance Methods

Pattern 1: Error Fix Chain

Symptom: Fixing one error causes new errors Cause: Surface-level fixes without understanding root cause Avoidance: Identify root cause with 5 Whys before fixing

Pattern 2: Abandoning Type Safety

Symptom: Excessive use of any type or as Cause: Impulse to avoid type errors Avoidance: Handle safely with unknown type and type guards

Pattern 3: Implementation Without Sufficient Testing

Symptom: Many bugs after implementation Cause: Ignoring Red-Green-Refactor process Avoidance: Always start with failing tests

Pattern 4: Ignoring Technical Uncertainty

Symptom: Frequent unexpected errors when introducing new technology Cause: Assuming "it should work according to official documentation" without prior investigation Avoidance:

  • Record certainty evaluation at the beginning of task files
    Certainty: low (Reason: new experimental feature with limited production examples)
    Exploratory implementation: true
    Fallback: use established patterns
    
  • For low certainty cases, create minimal verification code first

Pattern 5: Insufficient Existing Code Investigation

Symptom: Duplicate implementations, architecture inconsistency, integration failures Cause: Insufficient understanding of existing code before implementation Avoidance Methods:

  • Before implementation, always search for similar functionality (using domain, responsibility, component patterns as keywords)
  • Similar functionality found → Use that implementation (do not create new implementation)
  • Similar functionality is technical debt → Create ADR improvement proposal before implementation
  • No similar functionality exists → Implement new functionality following existing design philosophy
  • Record all decisions and rationale in "Existing Codebase Analysis" section of Design Doc

Debugging Techniques

1. Error Analysis Procedure

  1. Read error message (first line) accurately
  2. Focus on first and last of stack trace
  3. Identify first line where your code appears
  4. Check React DevTools for component hierarchy

2. 5 Whys - Root Cause Analysis

Symptom: Component not rendering
Why1: Props are undefined → Why2: Parent component didn't pass props
Why3: Parent using old prop names → Why4: Component interface was updated
Why5: No update to parent after refactoring
Root cause: Incomplete refactoring, missing call-site updates

3. Minimal Reproduction Code

To isolate problems, attempt reproduction with minimal code:

  • Remove unrelated components
  • Replace API calls with mocks
  • Create minimal configuration that reproduces problem
  • Use React DevTools to inspect component tree

4. Debug Log Output (temporary)

Add structured debug logs to isolate the issue, then remove them before commit (per "Delete debug console.log()" in typescript-rules):

console.log('DEBUG:', {
  context: 'user-form-submission',
  props: { email, name },
  state: currentState,
  timestamp: new Date().toISOString()
})

Quality Check Workflow

Read package.json scripts and run them with the project's package manager (packageManager field). Map the project's actual script names to the phases below — do not assume fixed names.

Phases (run in order)

  1. Lint/format — the project's formatter + linter (e.g., Biome, or ESLint + Prettier)
  2. Type check — type check without emit
  3. Build — production build
  4. Test — unit/integration tests
  5. Coverage — coverage run when the task added or changed behavior

Troubleshooting

  • Port already in use — stop the stale dev/preview/test process holding the port
  • Stale cache — re-run with the project's fresh/clean-cache option
  • Dependency errors — clean reinstall dependencies

Situations Requiring Technical Decisions

Timing of Abstraction

  • Extract patterns after writing concrete implementation 3 times
  • Be conscious of YAGNI, implement only currently needed features
  • Prioritize current simplicity over future extensibility

Performance vs Readability

  • Prioritize readability unless React DevTools Profiler identifies a measurable bottleneck (e.g., render time exceeding 16ms, unnecessary re-renders)
  • Measure before optimizing with React DevTools Profiler
  • Document reason with comments when optimizing

Granularity of Component/Type Definitions

  • Overly detailed components/types reduce maintainability
  • Design components that appropriately express UI patterns
  • Use composition over inheritance

Implementation Completeness Assurance

Required Procedure for Impact Analysis

Completion Criteria: Complete all 3 stages

1. Discovery

Grep -n "ComponentName\|hookName" -o content
Grep -n "importedFunction" -o content
Grep -n "propsType\|StateType" -o content

2. Understanding

Mandatory: Read all discovered files and include necessary parts in context:

  • Caller's purpose and context
  • Component hierarchy
  • Data flow: Props → State → Event handlers → Callbacks

3. Identification

Structured impact report (mandatory):

## Impact Analysis
### Direct Impact: ComponentA, ComponentB (with reasons)
### Indirect Impact: FeatureX, PageY (with integration paths)
### Processing Flow: Props → Render → Events → Callbacks

Important: Execute all 3 stages to completion

Unused Code Deletion Rule

When unused code is detected → Will it be used?

  • Yes → Implement immediately (no deferral allowed)
  • No → Delete immediately (remains in Git history)

Target: Components, hooks, utilities, documentation, configuration files

Existing Code Deletion Decision Flow

In use? No → Delete immediately (remains in Git history)
       Yes → Working? No → Delete + Reimplement
                     Yes → Fix
用于制定实施策略的元认知框架,涵盖现状分析、策略探索、风险评估及约束验证。适用于规划实现方案、选择开发方法或定义验证标准,通过系统化流程优化技术决策与迁移路径。
需要制定软件实施策略 选择开发或迁移方法 定义验证标准 评估技术风险
dev-workflows-frontend/skills/implementation-approach/SKILL.md
npx skills add shinpr/claude-code-workflows --skill implementation-approach -g -y
SKILL.md
Frontmatter
{
    "name": "implementation-approach",
    "description": "Implementation strategy selection framework. Use when planning implementation strategy, selecting development approach, or defining verification criteria."
}

Implementation Strategy Selection Framework (Meta-cognitive Approach)

Meta-cognitive Strategy Selection Process

Phase 1: Comprehensive Current State Analysis

Core Question: "What does the existing implementation look like?"

Analysis Framework

Architecture Analysis: Responsibility separation, data flow, dependencies, technical debt
Implementation Quality Assessment: Code quality, test coverage, performance, security
Historical Context Understanding: Current form rationale, past decision validity, constraint changes, requirement evolution

Meta-cognitive Question List

  • What is the true responsibility of this implementation?
  • Which parts are business essence and which derive from technical constraints?
  • What dependencies or implicit preconditions are unclear from the code?
  • What benefits and constraints does the current design bring?

Phase 2: Strategy Exploration and Creation

Core Question: "When determining before → after, what implementation patterns or strategies should be referenced?"

Strategy Discovery Process

Research and Exploration: Tech stack examples (WebSearch), similar projects, OSS references, literature/blogs
Creative Thinking: Strategy combinations, constraint-based design, phase division, extension point design

Reference Strategy Patterns (Creative Combinations Encouraged)

Legacy Handling Strategies:

  • Strangler Pattern: Gradual migration through phased replacement
  • Facade Pattern: Complexity hiding through unified interface
  • Adapter Pattern: Bridge with existing systems

New Development Strategies:

  • Feature-driven Development: Vertical implementation prioritizing user value
  • Foundation-driven Development: Foundation-first construction prioritizing stability
  • Risk-driven Development: Prioritize addressing maximum risk elements

Integration/Migration Strategies:

  • Proxy Pattern: Transparent feature extension
  • Decorator Pattern: Phased enhancement of existing features
  • Bridge Pattern: Flexibility through abstraction

Important: The optimal solution is discovered through creative thinking according to each project's context.

Phase 3: Risk Assessment and Control

Core Question: "What risks arise when applying this to existing implementation, and what's the best way to control them?"

Risk Analysis Matrix

Technical Risks: System impact, data consistency, performance degradation, integration complexity
Operational Risks: Service availability, deployment downtime, process changes, rollback procedures
Project Risks: Schedule delays, learning costs, quality achievement, team coordination

Risk Control Strategies

Preventive Measures: Phased migration, parallel operation verification, integration/regression tests, monitoring setup
Incident Response: Rollback procedures, log/metrics preparation, communication system, service continuation procedures

Phase 4: Constraint Compatibility Verification

Core Question: "What are this project's constraints?"

Constraint Checklist

Technical Constraints: Library compatibility, resource capacity, mandatory requirements, numerical targets
Temporal Constraints: Deadlines/priorities, dependencies, milestones, learning periods
Resource Constraints: Team/skills, work hours/systems, budget, external contracts
Business Constraints: Market launch timing, customer impact, regulatory compliance

Phase 5: Implementation Approach Decision

Select optimal solution from basic implementation approaches (creative combinations encouraged):

Vertical Slice (Feature-driven)

Characteristics: Vertical implementation across all layers by feature unit Application Conditions: Features share fewer than 2 data models, each feature is independently deliverable, changes touch 3+ architecture layers Verification Method: End-user value delivery at each feature completion

Horizontal Slice (Foundation-driven)

Characteristics: Phased construction by architecture layer Application Conditions: 3+ features depend on a common foundation layer, foundation changes require stability verification before consumers can proceed Verification Method: Integrated operation verification when all foundation layers complete

Hybrid (Creative Combination)

Characteristics: Flexible combination according to project characteristics Application Conditions: Unclear requirements, need to change approach per phase, transition from prototyping to full implementation Verification Method: Verify at appropriate L1/L2/L3 levels according to each phase's goals

Phase 6: Decision Rationale Documentation

Design Doc Documentation: Record in the Design Doc's implementation approach section:

  1. Selected strategy name and characteristics
  2. Alternatives considered and reason for rejection
  3. Risk mitigation plan (from Phase 3)
  4. Constraint compliance summary (from Phase 4)
  5. Verification level (L1/L2/L3) and integration point definition

Verification Level Definitions

Priority for completion verification of each task:

  • L1: Functional Operation Verification - Operates as end-user feature (e.g., search executable)
  • L2: Test Operation Verification - New tests added and passing
  • L3: Build Success Verification - Code builds/runs without errors

Priority: L1 > L2 > L3 in order of verifiability importance

Integration Point Definitions

Define integration points according to selected strategy:

  • Strangler-based: When switching between old and new systems for each feature
  • Feature-driven: When users can actually use the feature
  • Foundation-driven: When all architecture layers are ready and E2E tests pass
  • Hybrid: When individual goals defined for each phase are achieved

Quality Checks

  1. Verify at least one strategy combination beyond listed patterns was considered
  2. Confirm Phase 1 analysis framework is complete before selecting strategy
  3. Confirm Phase 3 risk analysis matrix is populated before implementation starts
  4. Confirm Phase 4 constraint checklist is reviewed before strategy decision
  5. Confirm Phase 6 documentation template is filled with selection rationale

Guidelines for Meta-cognitive Execution

  1. Leverage Known Patterns: Use as starting point, explore creative combinations
  2. Active WebSearch Use: Research implementation examples from similar tech stacks
  3. Apply 5 Whys: Pursue root causes to grasp essence
  4. Multi-perspective Evaluation: Comprehensively evaluate from each Phase 1-4 perspective
提供集成与E2E测试的设计原则、ROI计算模型、骨架规范及审查标准。用于指导测试用例设计、类型选择(如fixture-e2e)、优先级排序及质量评审,确保测试覆盖高价值用户行为并优化投入产出比。
设计集成或端到端测试用例 评估测试用例的投资回报率 审查现有测试代码的质量 确定测试类型预算分配
dev-workflows-frontend/skills/integration-e2e-testing/SKILL.md
npx skills add shinpr/claude-code-workflows --skill integration-e2e-testing -g -y
SKILL.md
Frontmatter
{
    "name": "integration-e2e-testing",
    "description": "Integration and E2E test design principles, ROI calculation, test skeleton specification, and review criteria. Use when designing integration tests, E2E tests, or reviewing test quality."
}

Integration and E2E Testing Principles

References

E2E test design: See references/e2e-design.md for UI Spec-driven E2E test candidate selection and browser test architecture. The reference uses Playwright as the default browser harness; substitute the project's standard when different.

Test Type Definition and Limits

Test Type Purpose Scope External Deps Limit per Feature Implementation Timing
Integration Verify component interactions in-process Partial system integration (in-process modules; for UI components, the framework's in-process renderer e.g., RTL+MSW for React/TS) Mocked or in-process MAX 3 Created alongside implementation
fixture-e2e Verify UI behavior in a browser with deterministic fixtures Full UI flow with mocked backend / fixture-driven state Mocked / fixture only — no live services MAX 3 Created alongside the UI feature
service-integration-e2e Verify critical user journeys against a running local stack Full system across services Live local services or stubs MAX 1-2 Executed only in the final phase

Lane selection (E2E only):

  • Default lane for user-facing UI journeys is fixture-e2e — it runs a real browser against deterministic fixtures, catches the bugs that unit/integration tests miss (button no-op, state never updates, navigation breaks), and runs in CI without infrastructure setup
  • Add service-integration-e2e only when the journey's correctness depends on real cross-service behavior (data persistence, transactional consistency, external service contracts) that cannot be faked safely

The two E2E lanes are budgeted independently — having a fixture-e2e for a journey does not consume the service-integration-e2e budget and vice versa.

Behavior-First Principle

Include (High ROI)

  • Business logic correctness (calculations, state transitions, data transformations)
  • Data integrity and persistence behavior
  • User-visible functionality completeness
  • Error handling behavior (what user sees/experiences)

Redirect to Other Test Types

  • External service connections → Verify via contract/interface tests
  • Performance metrics → Verify via dedicated load testing
  • Implementation details → Verify observable behavior instead
  • UI layout specifics → Verify information availability instead

Principle: Test = User-observable behavior verifiable in isolated CI environment

ROI Calculation

ROI is used to rank candidates within the same test type (integration candidates against each other, E2E candidates against each other). Cross-type comparison is unnecessary because integration and E2E budgets are selected independently.

ROI Score = Business Value × User Frequency + Legal Requirement × 10 + Defect Detection
              (range: 0–120)

Higher ROI Score = higher priority within its test type. No normalization or capping is applied — the raw score is used directly for ranking. Deduplication is a separate step that removes candidates entirely; it does not modify scores.

ROI Thresholds by Lane

The two E2E lanes have very different ownership costs and use independent thresholds.

Lane ROI threshold Rationale
fixture-e2e ROI ≥ 20 (beyond reserved slot) Cost is comparable to integration tests once the harness exists; the floor avoids filling MAX 3 with low-signal tests when fewer would suffice
service-integration-e2e ROI > 50 (beyond reserved slot) Creation, execution, and maintenance cost is 3-10× higher than integration; reserve for journeys whose value cannot be proven any other way

Reserved slot rules (see Multi-Step User Journey Definition below) apply per lane and override the threshold (the reserved candidate is emitted regardless of its ROI score). Below-floor candidates beyond the reserved slot are not emitted, leaving budget intentionally unfilled rather than padding with low-value tests.

ROI Calculation Examples

Scenario BV Freq Legal Defect ROI Score Test Type Selection Outcome
Core checkout UI flow 10 9 true 9 109 fixture-e2e Selected (reserved slot: user-facing multi-step journey, browser-level verification with fixtures)
Core checkout against live payment service 10 9 true 9 109 service-integration-e2e Selected (real-service correctness above ROI threshold)
Dismiss button updates UI state 6 7 false 8 50 fixture-e2e Selected (rank 2 of 3 fixture-e2e budget)
Payment error message display 5 4 false 7 27 fixture-e2e Selected (rank 3 of 3 fixture-e2e budget)
Optional filter toggle 3 4 false 2 14 fixture-e2e Not selected (rank 4, budget full)
Payment retry against real provider 8 3 false 7 31 service-integration-e2e Below ROI threshold (31 < 50), not selected
DB persistence check 8 8 false 8 72 Integration Selected (rank 1 of 3)
Pure data transformation 5 3 false 4 19 Integration Selected (rank 2 of 3)

Multi-Step User Journey Definition

A feature qualifies as containing a multi-step user journey when ALL of the following are true:

  1. 2+ distinct interaction boundaries are traversed in sequence to complete a user goal. What counts as a boundary depends on the system type:
    • Web: distinct routes/pages
    • Mobile native: distinct screens/views
    • CLI: distinct command invocations or interactive prompts
    • API: distinct API calls forming a transaction (e.g., create → confirm → finalize)
  2. State carries across steps — data produced or actions taken in one step affect what the next step accepts or displays
  3. The journey has a completion point — a final state the user or caller reaches (e.g., confirmation page, saved record, API success response, completed workflow)

User-Facing vs Service-Internal Journeys

Multi-step journeys are classified for reserved-slot eligibility:

Classification Condition Reserved Slot Eligibility Example
User-facing A human user directly triggers and observes the steps (via UI, CLI, or direct API interaction) Eligible — defaults to fixture-e2e reserved slot. Add a service-integration-e2e reserved slot only when the journey's correctness depends on real cross-service behavior Web checkout flow, CLI setup wizard, mobile onboarding
Service-internal Steps are triggered by backend services without direct user interaction Not eligible for reserved slot — use integration tests. Service-integration-e2e through normal ROI > 50 path is still valid when full-system verification is warranted Async job pipeline, service-to-service saga, scheduled batch processing

This classification applies only to the reserved-slot rule and the E2E Gap Check. Other selection follows lane-specific ROI rules above.

Use this definition when evaluating E2E test candidates and E2E gap detection.

Test Skeleton Specification

Required Comment Patterns

Each test MUST include the following annotations:

AC: [Original acceptance criteria text]
Behavior: [Trigger] → [Process] → [Observable Result]
@category: core-functionality | integration | edge-case | fixture-e2e | service-integration-e2e
@lane: integration | fixture-e2e | service-integration-e2e
@dependency: none | [component names] | full-system
@complexity: low | medium | high
ROI: [score]

@lane selection rule:

  • integration — Component interaction in-process, no browser (e.g., RTL+MSW for React/TS, in-process module/handler integration in any language)
  • fixture-e2e — Browser-level UI verification with mocked backend / fixture-driven state
  • service-integration-e2e — Browser-level or end-to-end verification against running local services or stubs

Use the project's comment syntax to wrap these annotations (e.g., // for C-family, # for Python/Ruby/Shell).

Verification Items (Optional)

When verification points need explicit enumeration:

Verification items:
- [Item 1]
- [Item 2]

EARS Format Mapping

EARS Keyword Test Type Generation Approach
When Event-driven Trigger event → verify outcome
While State condition Setup state → verify behavior
If-then Branch coverage Both condition paths verified
(none) Basic functionality Direct invocation → verify result

Test File Naming Convention

  • Integration tests: *.int.test.* or *.integration.test.*
  • fixture-e2e tests: *.fixture.e2e.test.* (or organize under tests/e2e/fixture/)
  • service-integration-e2e tests: *.service.e2e.test.* (or organize under tests/e2e/service/)

The test runner or framework in the project determines the appropriate file extension. Repos that already use a single *.e2e.test.* convention may keep it as long as each file declares @lane: in its header — the lane annotation is the source of truth for routing and budget accounting.

Review Criteria

Skeleton and Implementation Consistency

Check Failure Condition
Behavior Verification No assertion for "observable result" in the implemented test
Verification Item Coverage Listed items not all covered by assertions
Mock Boundary Internal components mocked in integration test

Implementation Quality

Check Failure Condition
AAA Structure Arrange/Act/Assert separation unclear
Independence State sharing between tests, order dependency
Reproducibility Date/random dependency, varying results
Readability Test name doesn't match verification content

Quality Standards

Required

  • Each test verifies one behavior
  • Clear AAA (Arrange-Act-Assert) structure
  • No test interdependencies
  • Deterministic execution
旨在优化LLM交互上下文,通过明确指令、具体标准、输出格式及不确定性处理,确保下游智能体无需猜测即可稳定执行。适用于编写或修订提示词、交接文档及计划任务。
编写或修订面向LLM的提示词 创建或优化智能体间的工作交接说明 生成或审查规划类工件与报告 将模糊指令转化为可执行的具体步骤
dev-workflows-frontend/skills/llm-friendly-context/SKILL.md
npx skills add shinpr/claude-code-workflows --skill llm-friendly-context -g -y
SKILL.md
Frontmatter
{
    "name": "llm-friendly-context",
    "description": "Clarifies inputs, outputs, success criteria, decisions, and unresolved conditions so downstream agents can execute without guessing. Use when writing or revising LLM-facing prompts, handoffs, planning artifacts, reviews, reports, or generated instructions."
}

LLM-Friendly Context

The goal is stable downstream execution: the next agent should know what to read, what to do, what counts as success, and when to stop or escalate.

Core Rules

  1. Use positive, executable instructions

    • State what the next agent should do.
    • Convert quality policies into positive criteria.
    • Example: "Preserve existing public API behavior across the documented compatibility cases."
  2. Make vague instructions concrete

    • Replace subjective terms with observable conditions, paths, commands, schemas, examples, or decision rules.
    • Terms that often need clarification when they leave a decision to the next agent: appropriate, proper, related, existing behavior, optional, as needed, if needed, per convention, unresolved alternatives, TBD, placeholder.
  3. Specify output shape

    • Define required sections, fields, table columns, JSON keys, or checklist items.
    • For handoffs, include paths to produced artifacts and the exact status fields the caller must inspect.
  4. Provide necessary context

    • Include the purpose, source artifacts, hard constraints, accepted decisions, and unresolved conditions.
    • Prefer concrete file paths and section hints over broad module names.
  5. Decompose complex work into verifiable steps

    • Split work with 3+ objectives or sequential dependencies into ordered steps.
    • Each step needs a checkpoint: what evidence proves it is complete.
  6. Permit uncertainty explicitly

    • If the source material is missing, contradictory, or not verifiable, state the uncertainty and the required escalation.
    • Record unknown business, product, security, or compatibility decisions as blocking unresolved items with the input needed to resolve them.
  7. Keep constraints proportionate

    • Add only constraints that reduce ambiguity or preserve a real requirement.
    • Keep simple downstream tasks lightweight when the target action, context, and success criteria are already clear.

Rewrite Patterns

Use these rewrites before treating a prompt, handoff, or artifact as complete.

Ambiguous form Rewrite as
optional used as an unresolved choice Required, omitted, or required only under a named condition
Multiple alternatives that the next agent must choose between The selected option, or a deterministic decision rule
as needed / if needed The triggering condition and required action
per convention The file, function, test, or documented convention to follow
related files Specific paths, globs, or search hints
existing behavior The observable behavior, source file, test, API response, or UI state to preserve
placeholder Exact temporary value/behavior, allowed dependencies, and verification expectation
TBD used as a placeholder for required information A blocking unresolved item with owner, required input, or escalation condition
appropriate / proper A measurable criterion or checklist

Handoff Checklist

Before sending a prompt or artifact to another agent, verify:

  • The target action is explicit.
  • Required input paths and source artifacts are named.
  • Accepted decisions and constraints are stated once, without alternate wording.
  • Output format or expected status fields are specified.
  • Success criteria are observable.
  • Ambiguous expressions have been rewritten or marked as unresolved.
  • The next agent can complete its scope with explicit choices, decision rules, or blocking unresolved items.

Generated Artifact Checklist

Before writing or finalizing a generated document:

  • Each requirement, claim, task, test skeleton, or review finding has enough source context to trace why it exists.
  • Every executable instruction names the target, action, and expected result.
  • Verification steps say what to run or observe and what result proves success.
  • If an artifact is derived from another artifact, copied decisions stay consistent in wording and meaning.
  • If downstream work is blocked by missing information, the artifact records the missing input and escalation condition.
诊断技能,通过编排调查、验证和求解子代理,结构化分析根本原因并生成解决方案。支持变更失败与新发现分类,结合规则顾问优化调查重点,迭代验证直至覆盖充分。
需要排查系统或业务问题的根本原因 用户报告故障并要求提供解决方案 涉及变更引发的异常需区分是修复还是新Bug
dev-workflows-frontend/skills/recipe-diagnose/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-diagnose -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-diagnose",
    "description": "Investigate problem, verify findings, and derive solutions",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Diagnosis flow to identify root cause and present solutions

Target problem: $ARGUMENTS

Orchestrator Definition

Core Identity: "I am not a worker. I am an orchestrator."

Execution Method:

  • Investigation → performed by investigator
  • Verification → performed by verifier
  • Solution derivation → performed by solver

Orchestrator invokes sub-agents and passes structured JSON between them.

Task Registration: Register execution steps using TaskCreate and proceed systematically. Update status using TaskUpdate.

Step 0: Problem Structuring (Before investigator invocation)

0.1 Problem Type Determination

Type Criteria
Change Failure Indicates some change occurred before the problem appeared
New Discovery No relation to changes is indicated

If uncertain, ask the user whether any changes were made right before the problem occurred.

0.2 Information Supplementation for Change Failures

If the following are unclear, ask with AskUserQuestion before proceeding:

  • What was changed (cause change)
  • What broke (affected area)
  • Relationship between both (shared components, etc.)

0.3 Problem Essence Understanding

Invoke rule-advisor via Agent tool:

subagent_type: rule-advisor
description: "Problem essence analysis"
prompt: Identify the essence and required rules for this problem: [Problem reported by user]

Confirm from rule-advisor output:

  • taskAnalysis.mainFocus: Primary focus of the problem
  • mandatoryChecks.taskEssence: Root problem beyond surface symptoms
  • selectedRules: Applicable rule sections
  • warningPatterns: Patterns to avoid

0.4 Reflecting in investigator Prompt

Include the following in investigator prompt:

  1. Problem essence (taskEssence)
  2. Key applicable rules summary (from selectedRules)
  3. Investigation focus (investigationFocus): Convert warningPatterns to "points prone to confusion or oversight in this investigation"
  4. For change failures, additionally include:
    • Detailed analysis of the change content
    • Commonalities between cause change and affected area
    • Determination of whether the change is a "correct fix" or "new bug" with comparison baseline selection

Diagnosis Flow Overview

Problem → investigator → verifier → solver ─┐
                 ↑                          │
                 └── coverage insufficient ─┘
                      (max 2 iterations)

coverage sufficient → Report

Context Separation: Pass only structured JSON output to each step. Each step starts fresh with the JSON data only.

Execution Steps

Register the following using TaskCreate and execute:

Step 1: Investigation (investigator)

Agent tool invocation:

subagent_type: investigator
description: "Investigate problem"
prompt: |
  Comprehensively collect information related to the following phenomenon.

  Phenomenon: [Problem reported by user]

  Problem essence: [taskEssence from Step 0.3]
  Investigation focus: [investigationFocus from Step 0.4]

  [For change failures, additionally include:]
  Change details: [What was changed]
  Affected area: [What broke]
  Shared components: [Commonalities between cause and effect]

Expected output: pathMap (execution paths per symptom), failurePoints (faults found at each node), impactAnalysis per failure point, unexplored areas, investigation limitations

Step 2: Investigation Quality Check

Review investigation output:

Quality Check (verify JSON output contains the following):

  • pathMap exists with at least one symptom, and each symptom has at least one path with nodes listed
  • Each failure point has: location, upstreamDependency, symptomExplained, causalChain (reaching a stop condition), checkStatus, evidence with a source citing a specific file or location
  • Each failure point has comparisonAnalysis (normalImplementation found or explicitly null)
  • causeCategory for each failure point is one of: typo / logic_error / missing_constraint / design_gap / external_factor
  • investigationSources covers at least 3 distinct source types (code, history, dependency, config, document, external)
  • Investigation covers investigationFocus items (when provided in Step 0.4)
  • All nodes on mapped paths have been checked (no path was abandoned after finding the first fault)

If quality insufficient: Re-run investigator specifying missing items explicitly:

prompt: |
  Re-investigate with focus on the following gaps:
  - Missing: [list specific missing items from quality check]

  Previous investigation results (for context, do not re-investigate covered areas):
  [Previous investigation JSON]

design_gap Escalation:

When investigator output contains causeCategory: design_gap or recurrenceRisk: high:

  1. Insert user confirmation before verifier execution
  2. Use AskUserQuestion: "A design-level issue was detected. How should we proceed?"
    • A: Attempt fix within current design
    • B: Include design reconsideration
  3. If user selects B, pass includeRedesign: true to solver

Proceed to verifier once quality is satisfied.

Step 3: Verification (verifier)

Agent tool invocation:

subagent_type: verifier
description: "Verify investigation results"
prompt: Verify the following investigation results.

Investigation results: [Investigation JSON output]

Expected output: Coverage check (missing paths, unchecked nodes), Devil's Advocate evaluation per failure point, failure point evaluation with checkStatus, coverage assessment

Coverage Criteria:

  • sufficient: Main paths traced, all critical nodes checked, each failure point individually evaluated
  • partial: Main paths traced, some nodes unchecked or some failure points at blocked/not_reached
  • insufficient: Significant paths untraced, or critical nodes not investigated

Step 4: Solution Derivation (solver)

Agent tool invocation:

subagent_type: solver
description: "Derive solutions"
prompt: Derive solutions based on the following verified failure points.

Confirmed failure points: [verifier's conclusion.confirmedFailurePoints]
Refuted failure points: [verifier's conclusion.refutedFailurePoints]
Failure point relationships: [verifier's conclusion.failurePointRelationships]
Impact analysis: [investigator's impactAnalysis]
Coverage assessment: [sufficient/partial/insufficient]

Expected output: Multiple solutions (at least 3), tradeoff analysis, recommendation and implementation steps, residual risks

Completion condition: coverageAssessment=sufficient

When not reached:

  1. Return to Step 1 with unchecked areas identified by verifier as investigation targets
  2. Maximum 2 additional investigation iterations
  3. After 2 iterations without reaching sufficient, present user with options:
    • Continue additional investigation
    • Execute solution at current coverage level

Step 5: Final Report Creation

Prerequisite: coverageAssessment=sufficient achieved

After diagnosis completion, report to user in the following format:

## Diagnosis Result Summary

### Identified Failure Points
[Confirmed failure points from verification results]
- Per failure point: location, symptom explained, finalStatus

### Verification Process
- Path coverage: [Paths traced and nodes checked]
- Additional investigation iterations: [0/1/2]
- Coverage assessment: [sufficient/partial/insufficient]

### Recommended Solution
[Solution derivation recommendation]

Rationale: [Selection rationale]

### Implementation Steps
1. [Step 1]
2. [Step 2]
...

### Alternatives
[Alternative description]

### Residual Risks
[solver's residualRisks]

### Post-Resolution Verification Items
- [Verification item 1]
- [Verification item 2]

Completion Criteria

  • Executed investigator and obtained pathMap, failurePoints, and impactAnalysis
  • Performed investigation quality check and re-ran if insufficient
  • Executed verifier and obtained coverage assessment
  • Executed solver
  • Achieved coverageAssessment=sufficient (or obtained user approval after 2 additional iterations)
  • Presented final report to user
用于在会话中调整已实现的UI,通过执行编辑、对照设计源验证及迭代的闭环流程确保质量。涵盖资源获取、代码分析、规模评估、修复及提交,直至完成验收。
需要调整已实现UI时 需对照设计源验证UI变更时
dev-workflows-frontend/skills/recipe-front-adjust/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-adjust -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-adjust",
    "description": "Adjust an already-implemented UI in-session with verification against the design source",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: UI adjustment on already-implemented features. The verification loop (edit → check against the design source → refine) runs in the parent session.

Execution Pattern

Core Identity: "I am a guided executor. I run the adjustment and the verification loop myself; subagents handle one-shot tasks."

Execution Protocol:

  1. Delegate to subagents (one-shot calls): ui-analyzer, work-planner, quality-fixer-frontend.
  2. Run in the parent session (multi-step loops and user dialogs): external-resource hearing via AskUserQuestion, write-set confirmation, scale judgment, adjustment edits, verification against the design source, iteration until acceptance.
  3. Stop at every [Stop: ...] marker before proceeding.

Initial Mandatory Tasks

Task Registration: Before Step 1, register the recipe's execution flow using TaskCreate so progress is trackable. Register Steps 1-7 below as individual tasks plus a final task "Verify completion against Completion Criteria". Update status using TaskUpdate as each step starts and completes.

Workflow Overview

Adjustment request → external resource hearing (parent session, AskUserQuestion)
                                  ↓
                     ui-analyzer (subagent: fetch external sources + analyze code + propose candidateWriteSet)
                                  ↓
                     write-set confirmation (parent session, AskUserQuestion)
                                  ↓
                     scale judgment on confirmed write set (documentation-criteria matrix)
                                  ↓
            ┌────────────────────┴────────────────────┐
            ↓                                          ↓
   (1-2 files: inline)                  (3-5 files: work-planner subagent → [Stop])
            ↓                                          ↓
            └─→ adjustment + verification (parent session) ←──┘
                                  ↓
                     quality-fixer-frontend (subagent: typecheck/lint/test)
                                  ↓
                     commit

Scope Boundaries

Included in this skill:

  • External resource hearing per the external-resource-context skill
  • UI fact gathering via ui-analyzer
  • Scale judgment via documentation-criteria's Creation Decision Matrix
  • Optional work plan creation via work-planner
  • Adjustment edits and verification against the design source (run in this session)
  • Quality verification via quality-fixer-frontend
  • Commit per adjustment unit

Responsibility Boundary: This skill completes when the adjustment is committed and quality has passed. Adjustment work is end-to-end within this recipe; parent session owns edits, verification loops, quality-result routing, and commits.

Escalation Boundary: Escalate to the full frontend design phase when the request requires PRD, UI Spec, Design Doc, new architecture, multi-screen redesign, or any ADR Creation Condition from documentation-criteria.

Adjustment request: $ARGUMENTS

Execution Flow

Step 1: External Resource Hearing

Run the hearing protocol per the external-resource-context skill (frontend domain).

Step 2: UI Fact Gathering

  • Invoke ui-analyzer using Agent tool
    • subagent_type: "dev-workflows-frontend:ui-analyzer"
    • description: "UI fact gathering for adjustment"
    • prompt: "requirement_analysis: { affectedFiles: [files inferred from the adjustment request], scale: 'small', purpose: 'UI adjustment', technicalConsiderations: [] }. requirements: [adjustment request]. target_components: [components named in the request]. ui_spec_path: [path if an existing UI Spec covers the affected components, else absent]. Read docs/project-context/external-resources.md, fetch external UI sources via the declared access methods, and analyze the existing UI codebase. Populate candidateWriteSet[] with the files most likely to require modification."

Step 3: Scale Judgment

Execute Skill: documentation-criteria (loads the Creation Decision Matrix and ADR Creation Conditions used in this step and in the Escalation Boundary).

  1. Read candidateWriteSet[] from ui-analyzer output.
  2. Present the candidate list to the user via AskUserQuestion: "Confirmed write set for this adjustment? (a) accept high-confidence entries / (b) accept all entries / (c) edit list manually". On c, send a follow-up plain message asking the user to paste the edited file list, then proceed with that list.
  3. Apply the Creation Decision Matrix from the documentation-criteria skill to the confirmed write set count:
    • 0 files: The adjustment request did not map to any existing file. Escalate to the user with the message "No write target identified from the adjustment request. Please clarify which component(s) should change, or run the full frontend design phase if this is a new feature." Stop this recipe.
    • 1-2 files: Direct adjustment, no work plan.
    • 3-5 files: Work plan required.
    • 6+ files OR any ADR Creation Condition triggered (architecture changes, contract changes affecting 3+ locations, complex multi-state logic, etc.): Adjustment scope exceeded. Escalate the user to the full frontend design phase. Stop this recipe.

Step 4: Plan Creation (Conditional)

Branch on the scale outcome.

Branch A — 1-2 files

No work plan. Build a minimal adjustment context for the parent session:

  • Adjustment request (verbatim)
  • ui-analyzer focusAreas[] (raw fact_id; the ui: prefix is only applied when merging with codebase-analysis facts in a Fact Disposition Table, which Branch A does not do)
  • Affected files list
  • External resources fetched_summary and access methods that the verification loop will use

Present the adjustment context to the user for review.

  • [STOP]: User confirms the adjustment context covers the work.

Branch B — 3-5 files

Create a right-sized work plan. Invoke work-planner using Agent tool:

  • subagent_type: "dev-workflows-frontend:work-planner"
  • description: "Adjustment work plan"
  • prompt: "Create a work plan for this UI adjustment. Adjustment request: [verbatim]. ui_analysis: [ui-analyzer JSON]. External resources: docs/project-context/external-resources.md. Scale: 3-5 files (no Design Doc, no ADR). Each phase should be implementable as 1-3 commits. Include a quality checklist matched to the affected components: visual verification, accessibility, i18n parity, generated artifact regeneration when relevant. Output path: docs/plans/[YYYYMMDD]-adjust-[short-description].md."

After work-planner returns:

  • Present the work plan to the user.
  • [STOP]: Wait for plan approval or revision request. If the user requests changes, re-invoke work-planner with revised guidance.

Step 5: Adjustment + Verification (parent session)

For each adjustment unit (per file in Branch A; per work plan phase in Branch B):

  1. Plan the edit based on ui-analyzer focusAreas and the relevant external resource (e.g., design origin's fetched_summary).
  2. Apply the edit using Edit / Write / MultiEdit on the affected files.
  3. Verify against external sources using whichever access method docs/project-context/external-resources.md declares for each axis:
    • Design origin: compare current rendering against the design source via the declared access method (e.g., design-tool MCP, WebFetch from a public URL, file read from a specification path)
    • Visual rendering: capture screenshot or run a smoke check via the declared visual verification method (e.g., browser MCP, E2E test runner CLI invoked via Bash, dev-server URL inspection, Storybook URL)
    • Design system tokens / variants: confirm against the declared design system source (e.g., design-system MCP, package import, Storybook URL, internal documentation path)
  4. Refine and re-verify until the adjustment matches the design source, or matches the user-confirmed adjustment target when no separate design source exists.
  5. When the adjustment unit converges, proceed to Step 6 for that unit.

When the project-tier file declares no automated verification mechanism for an axis, ask the user to confirm the result manually, or use file-based comparison when a specification file is available.

Step 6: Quality Verification (per adjustment unit)

  • Invoke quality-fixer-frontend using Agent tool
    • subagent_type: "dev-workflows-frontend:quality-fixer-frontend"
    • description: "Quality verification for adjustment unit"
    • Build the prompt by branch. Scope is always filesModified; task_file (when passed) is a supplementary hint that quality-fixer-frontend may use to read the document's "Quality Assurance Mechanisms" section.
      • Branch A (1-2 files): omit task_file. Pass filesModified: [list of files edited in this adjustment unit].
      • Branch B (3-5 files): pass task_file: <work plan path> (supplementary hint) AND filesModified: [list of files edited in this adjustment unit] (primary scope).
    • Example (Branch A): prompt: "filesModified: [src/components/Card/Card.tsx, src/components/Card/Card.module.css]. Run quality checks across the listed files."
    • Example (Branch B): prompt: "task_file: docs/plans/[plan-name].md. filesModified: [src/components/Card/Card.tsx, src/components/Card/Card.module.css]. Run quality checks across the listed files."
  • Route the quality-fixer-frontend response by status:
    • approved → proceed to Step 7
    • stub_detected → return to Step 5 to complete the implementation for this unit, then re-invoke quality-fixer-frontend
    • blocked → read reason. When "Cannot determine due to unclear specification", surface blockingIssues[] to the user and stop. When "Execution prerequisites not met", surface missingPrerequisites[] with resolutionSteps to the user and stop

Step 7: Commit (per adjustment unit)

Commit the adjustment unit on quality approval. Include the affected files and any regenerated artifacts (CSS module typings, message catalog typings, etc.) flagged by ui-analyzer's generatedArtifacts section.

Then loop back to Step 5 for the next unit (Branch B work plan phase, or next file in Branch A) until all units are committed.

Completion Criteria

  • External resource hearing executed (project-tier file written or update explicitly skipped)
  • ui-analyzer returned a JSON output, including externalResources fetch_status per axis and candidateWriteSet
  • Write set confirmed by the user before scale judgment
  • Scale judgment applied to the confirmed write set; 6+ files or ADR conditions escalated to the design phase
  • Branch A: adjustment context presented and confirmed; Branch B: work plan approved
  • All adjustment units edited and verified using the project's declared verification mechanism (manual confirmation when no automated mechanism is declared)
  • Each adjustment unit passed quality-fixer-frontend with explicit filesModified scoping
  • Each adjustment unit committed

Output Example

Frontend adjustment completed.
- External resources: docs/project-context/external-resources.md (updated|unchanged)
- UI fact gathering: ui-analyzer focused on [N] components, [M] focus areas, external sources [fetched|partial|not_recorded]
- Scale: <1-2 files | 3-5 files>
- Work plan: <path | not required>
- Adjustment units committed: [count]
- Quality status: all passed
前端构建编排技能,用于自主执行前端实现。通过解析任务文件确定工作计划,执行任务生成、执行、质量修复及提交的4步循环,最终清理已消耗的任务文件并承诺代码。
用户下达前端自主执行指令 存在待处理的前端任务文件
dev-workflows-frontend/skills/recipe-front-build/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-build -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-build",
    "description": "Execute frontend implementation in autonomous execution mode",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Follow the 4-step task cycle exactly: task-executor-frontend → escalation check → quality-fixer-frontend → commit
  3. Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
  4. Scope: Complete when all tasks are committed or escalation occurs

CRITICAL: Run quality-fixer-frontend before every commit.

Work plan: $ARGUMENTS

Pre-execution Prerequisites

Work Plan Resolution

Before any task processing, locate the work plan. Resolution rule:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md. Layer-aware fullstack tasks ({plan-name}-backend-task-*.md / {plan-name}-frontend-task-*.md) are excluded here so a stale fullstack run does not redirect this recipe to the wrong work plan
  2. From the matched files, also exclude every file matching any of these patterns — they originate from other workflow phases and are not implementation tasks for this run's plan: *-task-prep-*.md (readiness preflight tasks), _overview-*.md (decomposition overview file), *-phase*-completion.md (per-phase completion files), review-fixes-*.md (post-implementation review fixes), integration-tests-*-task-*.md (integration-test add-on scaffolding)
  3. For each remaining file, extract the {plan-name} prefix as the segment that appears before -task-
  4. When at least one task file matches, the work plan is docs/plans/{plan-name}.md for the prefix that has the most recent task-file mtime; ties broken by the lexicographically last {plan-name}
  5. When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template .md in docs/plans/

Consumed Task Set

Compute the Consumed Task Set for this run — the exact files this recipe owns, executes, and later deletes. Use the same restricted pattern as Work Plan Resolution:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md for the {plan-name} resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded
  2. Exclude every file matching: *-task-prep-*.md, _overview-*.md, *-phase*-completion.md, review-fixes-*.md, integration-tests-*-task-*.md (these originate from other workflow phases)

Every subsequent reference to "task files" in this recipe — Task Generation Decision Flow, Task Execution Cycle iteration, and Final Cleanup — uses this set, not the unrestricted docs/plans/tasks/*.md glob.

Task Generation Decision Flow

Analyze the Consumed Task Set and determine the action required:

State Criteria Next Action
Tasks exist Consumed Task Set is non-empty User's execution instruction serves as batch approval → Enter autonomous execution immediately
No tasks + plan exists Consumed Task Set is empty but the resolved work plan exists Confirm with user → run task-decomposer
Neither exists + Design Doc exists No plan, no Consumed Task Set, but docs/design/*.md exists Invoke work-planner to create work plan from Design Doc, then run document-reviewer (dev-workflows-frontend:document-reviewer, doc_type: WorkPlan); branch on the reviewer's verdict.decision — on needs_revision, re-invoke work-planner (update) and re-review until approved/approved_with_conditions, then present the reviewed plan for batch approval before task decomposition; on rejected, stop before task decomposition and escalate to the user
Neither exists No plan, no Consumed Task Set, no Design Doc Report missing prerequisites to user and stop

Task Decomposition Phase (Conditional)

When the Consumed Task Set is empty:

1. User Confirmation

No task files in the Consumed Task Set.
Work plan: docs/plans/[plan-name].md

Generate tasks from the work plan? (y/n):

2. Task Decomposition (if approved)

Invoke task-decomposer using Agent tool:

  • subagent_type: "dev-workflows-frontend:task-decomposer"
  • description: "Decompose work plan"
  • prompt: "Read work plan at docs/plans/[plan-name].md and decompose into atomic tasks. Output: Individual task files in docs/plans/tasks/. Granularity: 1 task = 1 commit = independently executable"

3. Verify Generation

Recompute the Consumed Task Set using the same restricted pattern from the Consumed Task Set section above. Confirm it is now non-empty. If it is still empty, escalate to the user — task-decomposer either failed silently or produced files that don't match the expected pattern.

Flow: Task generation → Consumed Task Set recompute → Autonomous execution (in this order)

Pre-execution Checklist

  • Confirmed Consumed Task Set is non-empty (computed in the Consumed Task Set section above)
  • Identified task execution order within the Consumed Task Set (dependencies)
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Task Execution Cycle (4-Step Cycle)

MANDATORY EXECUTION CYCLE: task-executor-frontend → escalation check → quality-fixer-frontend → commit

For EACH task in the Consumed Task Set, YOU MUST:

  1. Register tasks using TaskCreate: Register work steps. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON"
  2. Agent tool (subagent_type: "dev-workflows-frontend:task-executor-frontend") → Pass task file path in prompt, receive structured response
  3. CHECK task-executor-frontend response:
    • status: "escalation_needed" or "blocked" → STOP and escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 2 with requiredFixes
      • approved → Proceed to step 4
    • readyForQualityCheck: true → Proceed to step 4
  4. INVOKE quality-fixer-frontend: Execute all quality checks and fixes. Always pass the current task file path as task_file
  5. CHECK quality-fixer-frontend response:
    • stub_detected → Return to step 2 with incompleteImplementations[] details
    • blocked → STOP and escalate to user
    • approved → Proceed to step 6
  6. COMMIT on approval: Execute git commit

CRITICAL: Parse every sub-agent response for status fields. Execute the matching branch in the 4-step cycle. Proceed to next task only after quality-fixer-frontend returns approved.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Verify task files exist per Pre-execution Checklist, then enter autonomous execution mode. When requirement changes are detected during execution, escalate to the user with the change summary before continuing.

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows-frontend:code-verifier") → doc_type: design-doc, Design Doc path, code_paths: implementation file list (git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows-frontend:security-reviewer") → Design Doc path, implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute task-executor-frontend with consolidated fixes → quality-fixer-frontend
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file in the Consumed Task Set
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer for this {plan-name})
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Completion Report Contract

Final report must include:

  • Task decomposition status
  • Implemented task count
  • Quality check result
  • Commit count
  • Cleanup result
  • Escalation or blocking summary, if any
该技能用于前端设计阶段,作为编排者协调多个子代理完成从代码库分析到设计文档生成的全流程。通过范围引导、UI分析与技术设计等步骤,确保输出高质量的前端设计方案,并在关键节点等待用户审批以确保质量。
需要进行前端设计阶段的任务 创建前端设计文档或架构决策记录
dev-workflows-frontend/skills/recipe-front-design/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-design -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-design",
    "description": "Execute from codebase analysis to frontend design document creation",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the frontend design phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results. The one exception is the Step 1 scope bootstrap, a recipe-local orchestrator task limited to locating seed files.
  2. Run the frontend design flow below in order (this recipe covers medium/large frontend):
    • Execute: scope bootstrap → codebase-analyzer → [Stop: Scope confirmation] → external resource hearing → ui-analyzer → ui-spec-designer → technical-designer-frontend → code-verifier → document-reviewer → design-sync
    • ui-spec-designer, code-verifier, and design-sync apply when the design output is a Design Doc; all are skipped for ADR-only
    • Stop at every [Stop: ...] marker → Wait for user approval before proceeding
  3. Scope: Complete when design documents receive approval

subagents-orchestration-guide usage: Reference the guide only for orchestration principles (Delegation Boundary, Decision precedence, permitted tools), the Scale Determination table, and handoff contracts HC-02 onward. This recipe defines its own start order and subagent prompts. The guide's requirement-analyzer-origin flow, First Action Rule, HC-01, and Call Examples do not apply to this recipe.

CRITICAL: Execute document-reviewer, design-sync (for Design Docs), and all stopping points — each serves as a quality gate. Skipping any step risks undetected inconsistencies.

Workflow Overview

Requirements → scope bootstrap → codebase-analyzer → [Stop: Scope confirmation]
                                                            ↓
                                          external resource hearing (frontend domain)
                                                            ↓
                                                       ui-analyzer
                                                            ↓
                                              ui-spec-designer → [Stop: UI Spec approval]
                                                            ↓
                                              technical-designer-frontend
                                                            ↓
                                              code-verifier → document-reviewer
                                                            ↓
                                                 design-sync → [Stop: Design approval]

Scope Boundaries

Included in this skill:

  • Scope bootstrap: locating seed files so codebase-analyzer receives a populated input
  • Codebase analysis with codebase-analyzer (entry point of the frontend design phase)
  • Scope confirmation with the user, grounded in codebase-analyzer findings
  • External resource hearing per the external-resource-context skill
  • UI fact gathering with ui-analyzer
  • UI Specification creation with ui-spec-designer (prototype code inquiry included)
  • ADR creation (if architecture changes, new technology, or data flow changes)
  • Design Doc creation with technical-designer-frontend
  • Design Doc verification with code-verifier (before document review)
  • Document review with document-reviewer
  • Design Doc consistency verification with design-sync

Responsibility Boundary: This skill completes with frontend design document (UI Spec/ADR/Design Doc) approval. Work planning and beyond are outside scope.

Execution Flow

Requirements: $ARGUMENTS

Step 1: Scope Bootstrap

codebase-analyzer requires a populated requirement_analysis.affectedFiles. Build that seed with a lightweight, orchestrator-local pass — locating files only, with no deep reading and no design decisions:

  1. Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
  2. Search the repository with Bash (rg, or grep when rg is unavailable) for files matching those keywords.
  3. Collect the matched file paths as the seed affectedFiles.
  4. When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as affectedFiles before invoking codebase-analyzer. If the user confirms no related code exists, report that codebase-grounded design does not apply and confirm with the user how to proceed.
  5. When the search returns more than ~20 files: the keywords are too broad for a focused design scope. Present the most relevant candidates to the user (AskUserQuestion) and confirm the seed affectedFiles before invoking codebase-analyzer.

This step locates seed files only. Reading files in full, tracing dependencies, and analysis remain codebase-analyzer's responsibility.

Step 2: Codebase Analysis

Invoke codebase-analyzer with its existing schema. The orchestrator constructs requirement_analysis from the Step 1 seed.

  • Invoke codebase-analyzer using Agent tool
    • subagent_type: "dev-workflows-frontend:codebase-analyzer", description: "Codebase analysis"
    • prompt: include
      • requirements: the user requirements verbatim
      • requirement_analysis: a JSON object with all four fields — affectedFiles (Step 1 seed), purpose (the user requirements), scale (provisional value from the Scale Determination table applied to the seed file count), technicalConsiderations ({ constraints: [], risks: [], dependencies: [] } — the bootstrap performs no analysis, so the object is present with empty lists)
      • Expected action: analyze the seed files for frontend design guidance (data, contracts, dependencies, quality assurance mechanisms)

Step 3: Scope Confirmation

After codebase-analyzer returns, confirm the design scope with the user before any design work. This is a recipe-local confirmation step. Use AskUserQuestion.

Present, sourced from the codebase-analyzer JSON:

  • Target files/modules: analysisScope.filesAnalyzed and the modules they belong to
  • Affected layers: layers touched, derived from analysisScope.categoriesDetected and focusAreas
  • Unknowns/assumptions: limitations plus any assumptions codebase-analyzer recorded
  • Questions before design: open points that need a user answer before design proceeds

Ask the user to choose one:

  • Proceed to design with this scope — continue to Step 4
  • Correct the scope and re-run — return to Step 1 with the corrected scope; when the user names the corrected files or modules, use those directly as the Step 1 seed instead of re-deriving them by search
  • Hold additional hearing, then proceed — gather the missing answers, then continue to Step 4
  • Produce an ADR — when the confirmed scope involves architecture changes, new technology, or data flow changes, continue through the flow with an ADR as the design document; Step 6 (UI Specification) is skipped for ADR

After the user confirms the scope, count the confirmed target files and set the scale from the subagents-orchestration-guide Scale Determination table. This confirmed scale supersedes the Step 2 provisional value and determines the design document.

[STOP]: Wait for the user's choice before proceeding.

Step 4: External Resource Hearing

Run the hearing protocol per the external-resource-context skill (frontend domain). The orchestrator owns this step because it requires AskUserQuestion. The skill defines file-existence branching, two-phase hearing (structured axes + self-declaration), and persistence to docs/project-context/external-resources.md.

Step 5: UI Fact Gathering

Invoke ui-analyzer to gather UI facts. It reads the project-tier external-resources file, fetches external UI sources via the inherited MCP/URL access methods, then analyzes the UI codebase. Its output complements the codebase-analyzer output from Step 2 (data, contracts, dependencies, quality assurance mechanisms).

  • Invoke ui-analyzer using Agent tool
    • subagent_type: "dev-workflows-frontend:ui-analyzer", description: "UI fact gathering"
    • prompt: include
      • requirements: the user requirements
      • requirement_analysis: a JSON object with all four fields — affectedFiles (analysisScope.filesAnalyzed from Step 2 codebase-analyzer), purpose (the user requirements), scale (the Step 3 confirmed scale), technicalConsiderations ({ constraints: [], risks: [], dependencies: [] })
      • Expected action: read docs/project-context/external-resources.md, fetch external UI sources via the declared access methods, and analyze the existing UI codebase

Both outputs (codebase-analyzer JSON from Step 2 and ui-analyzer JSON from Step 5) are reused by ui-spec-designer in Step 6 and by technical-designer-frontend in Step 7.

Step 6: UI Specification Phase

When the design document is a Design Doc (this step is skipped for ADR-only): after Step 5 output is received, ask the user about prototype code:

Ask the user: "Do you have prototype code for this feature? If so, please provide the path to the code. The prototype will be placed in docs/ui-spec/assets/ as reference material for the UI Spec."

  • [STOP]: Wait for user response about prototype code availability

Then create the UI Specification:

  • Invoke ui-spec-designer using Agent tool
    • subagent_type: "dev-workflows-frontend:ui-spec-designer"
    • description: "UI Spec creation"
    • Build the prompt by including:
      • Source: an existing PRD in docs/prd/ when one exists for this feature; otherwise the user requirements with the Step 2 codebase-analyzer JSON and the Step 3 confirmed scope
      • ui_analysis: ui-analyzer JSON from Step 5 (includes externalResources fetched_summary and componentStructure / propsPatterns / cssLayout / etc.)
      • Prototype path when provided
    • Example (existing PRD): prompt: "Create UI Spec from PRD at [path]. ui_analysis: [JSON from Step 5 ui-analyzer]. Prototype code is at [user-provided path]. Place prototype in docs/ui-spec/assets/{feature-name}/."
    • Example (no PRD): prompt: "Create UI Spec from these requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. Confirmed scope: [Step 3 confirmed scope]. ui_analysis: [JSON from Step 5 ui-analyzer]. Prototype code is at [user-provided path]. Place prototype in docs/ui-spec/assets/{feature-name}/."
  • Invoke document-reviewer to verify UI Spec
    • subagent_type: "dev-workflows-frontend:document-reviewer", description: "UI Spec review", prompt: "doc_type: UISpec target: [ui-spec path] Review for consistency and completeness"
  • [STOP]: Present UI Spec for user approval

Step 7: Design Document Creation Phase

technical-designer-frontend presents at least two architecture alternatives (technology selection, data flow design) with trade-offs for each. Pass the Step 2 codebase-analyzer output and the Step 5 ui-analyzer output:

  • Invoke technical-designer-frontend using Agent tool
    • For ADR: subagent_type: "dev-workflows-frontend:technical-designer-frontend", description: "ADR creation", prompt: "Create ADR for [technical decision]. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. UI analysis: [ui-analyzer JSON from Step 5]. Confirmed scope: [Step 3 confirmed scope]. Present at least two alternatives with trade-offs."
    • For Design Doc: subagent_type: "dev-workflows-frontend:technical-designer-frontend", description: "Design Doc creation", prompt: "Create Design Doc based on the requirements. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. UI analysis: [ui-analyzer JSON from Step 5]. UI Spec is at [ui-spec path]. Inherit component structure and state design from UI Spec. Apply code: prefix to codebase-analyzer fact_ids and ui: prefix to ui-analyzer fact_ids when filling the Fact Disposition Table. Present at least two architecture alternatives with trade-offs."
  • (Design Doc only) Invoke code-verifier to verify Design Doc against existing code. Skip for ADR.
    • subagent_type: "dev-workflows-frontend:code-verifier", description: "Design Doc verification", prompt: "doc_type: design-doc document_path: [Design Doc path] Verify Design Doc against existing code."
  • Invoke document-reviewer to verify consistency (pass code-verifier results for Design Doc; omit for ADR)
    • subagent_type: "dev-workflows-frontend:document-reviewer", description: "Document review", prompt: "Review [document path] for consistency and completeness. codebase_analysis: [codebase-analyzer JSON from Step 2]. ui_analysis: [ui-analyzer JSON from Step 5]. code_verification: [code verification output from this step] (Design Doc only)"

Step 8: Design Consistency Verification

  • (Design Doc only) Invoke design-sync using Agent tool. Skip for ADR-only.
    • subagent_type: "dev-workflows-frontend:design-sync", description: "Design consistency check", prompt: "Check consistency across all Design Docs in docs/design/. Report conflicts and overlaps."
  • [STOP]: Present the design document, plus design-sync results for a Design Doc, and obtain user approval

Completion Criteria

  • Built the Step 1 scope bootstrap seed (or obtained target files from the user when the search returned none)
  • Executed codebase-analyzer with a populated requirement_analysis
  • Confirmed the design scope with the user and set the scale from the confirmed target files
  • Executed external resource hearing per the external-resource-context skill (file written or update explicitly skipped by user)
  • Executed ui-analyzer; codebase-analyzer (Step 2) and ui-analyzer (Step 5) outputs reused by ui-spec-designer and technical-designer-frontend
  • Created UI Specification with ui-spec-designer (when applicable) — its External Resources Used section is filled
  • Created appropriate design document (ADR or Design Doc) with technical-designer-frontend — its External Resources Used subsection is filled when present
  • Executed code-verifier on Design Doc and passed results to document-reviewer (skip for ADR-only)
  • Executed document-reviewer and addressed feedback
  • Executed design-sync for consistency verification (skip for ADR-only)
  • Obtained user approval for design document

Output Example

Frontend design phase completed.

  • UI Specification: docs/ui-spec/[feature-name]-ui-spec.md
  • Design document: docs/design/[document-name].md or docs/adr/[document-name].md
  • Approval status: User approved
根据设计文档生成前端工作计划并获取审批。通过编排子代理,依次执行设计文档选择、测试骨架生成及工作计划创建与审查,最终在获得计划批准后结束任务。
需要根据设计文档制定前端开发计划 请求生成前端工作计划并获取批准
dev-workflows-frontend/skills/recipe-front-plan/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-plan -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-plan",
    "description": "Create frontend work plan from design document and obtain plan approval",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the frontend planning phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
  2. Follow subagents-orchestration-guide skill planning flow:
    • Execute steps defined below
    • Stop and obtain approval for plan content before completion
  3. Scope: See Scope Boundaries below

CRITICAL: When the user requests test generation, always execute acceptance-test-generator first — it provides the test skeleton that work-planner depends on.

Scope Boundaries

Included in this skill:

  • Design document selection
  • Test skeleton generation with acceptance-test-generator
  • Work plan creation with work-planner
  • Work plan review with document-reviewer
  • Plan approval obtainment

Responsibility Boundary: This skill completes with work plan approval.

Follow the planning process below:

Execution Process

Step 1: Design Document Selection

! ls -la docs/design/*.md | head -10

  • Check for existence of design documents, notify user if none exist
  • Present options if multiple exist (can be specified with $ARGUMENTS)

Step 2: Test Skeleton Generation Confirmation

  • Confirm with user whether to generate test skeletons (integration + fixture-e2e + service-integration-e2e) first
  • If user wants generation: acceptance-test-generator generates skeletons across all applicable lanes
    • Invoke acceptance-test-generator using Agent tool:
      • subagent_type: "dev-workflows-frontend:acceptance-test-generator"
      • description: "Test skeleton generation"
      • If UI Spec exists: prompt: "Generate test skeletons from Design Doc at [path]. UI Spec at [ui-spec path]."
      • If no UI Spec: prompt: "Generate test skeletons from Design Doc at [path]."
  • Pass integration test file path, fixture-e2e and service-integration-e2e file paths (or null per lane), and e2eAbsenceReason (per lane) to work-planner according to subagents-orchestration-guide "acceptance-test-generator → work-planner" section

Step 3: Work Plan Creation

Invoke work-planner using Agent tool:

  • subagent_type: "dev-workflows-frontend:work-planner"

  • description: "Work plan creation"

  • If test skeletons were generated in Step 2, build the prompt by listing every lane's status:

    • Always include: "Integration test file: [path or 'not generated']"
    • For each E2E lane (fixtureE2e, serviceE2e):
      • When generatedFiles.<lane> is not null: "[lane] test file: [path]"
      • When generatedFiles.<lane> is null: "No [lane] skeleton generated (reason: [e2eAbsenceReason.])"
    • Append placement guidance: "Integration tests are created simultaneously with each phase implementation. fixture-e2e tests are created alongside the UI feature phase. service-integration-e2e tests are executed only in the final phase."
  • If test skeletons were not generated: prompt: "Create work plan from Design Doc at [path]."

  • Follow subagents-orchestration-guide Prompt Construction Rule for additional prompt parameters

Step 4: Work Plan Review

Invoke document-reviewer to review the work plan:

  • subagent_type: "dev-workflows-frontend:document-reviewer"
  • description: "Work plan review"
  • prompt: "doc_type: WorkPlan target: docs/plans/[plan-name].md. Review semantic traceability to the Design Doc, early verification placement, real-boundary verification coverage, Failure Mode Checklist, and Review Scope."
  • The work plan is a derivation of the Design Doc, so plan-fidelity findings are resolved without user input. Branch on the reviewer's verdict.decision: on needs_revision, re-invoke work-planner in update mode with the findings and re-review, repeating until approved or approved_with_conditions. On rejected, escalate to the user.

Step 5: Present for Approval

  • Present the reviewed work plan to the user for batch approval. If the user requests changes, re-invoke work-planner with revised parameters and re-run Step 4.
  • Highlight steps with unclear scope or external dependencies and ask the user to confirm

Response at Completion

Recommended: End with the following standard response after plan content approval

Frontend planning phase completed.
- Work plan: docs/plans/[plan-name].md
- Status: Approved

Please provide separate instructions for implementation.
针对React/TypeScript前端项目的实现后质量保证技能。通过code-reviewer和security-reviewer子代理,校验代码与设计文档(Design Doc)的合规性及安全性。支持自动修复代码偏差或更新过时设计文档,并根据安全拦截结果决定流程走向。
需要验证前端代码是否符合设计文档规范时 执行前端安全审查与合规性检查时 发现代码与设计文档不一致需决定修复方向时
dev-workflows-frontend/skills/recipe-front-review/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-review -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-review",
    "description": "Design Doc compliance and security validation with optional auto-fixes",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Post-implementation quality assurance for React/TypeScript frontend

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

First Action: Register Steps 1-11 using TaskCreate before any execution.

Execution Method

  • Compliance validation → performed by code-reviewer
  • Security validation → performed by security-reviewer
  • Code-side fix path: Fix implementation → task-executor-frontend; Quality checks → quality-fixer-frontend; Re-validation → code-reviewer / security-reviewer
  • Design-side update path: DD revision → technical-designer-frontend (update mode); DD review → document-reviewer; cross-DD consistency → design-sync (when multiple DDs exist); Re-validation → code-reviewer

The design-side path applies when the discrepancy reflects code that was correct but the Design Doc became stale, rather than code that violated the Design Doc.

Design Doc (uses most recent if omitted): $ARGUMENTS

Execution Flow

Step 1: Prerequisite Check

# Identify Design Doc
ls docs/design/*.md | grep -v template | tail -1

# Check implementation files
git diff --name-only main...HEAD

Step 2: Execute code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows-frontend:code-reviewer"
  • description: "Code compliance review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review mode: full. Validate Design Doc compliance and return structured JSON report."

Store output as: $STEP_2_OUTPUT

Step 3: Execute security-reviewer

Invoke security-reviewer using Agent tool:

  • subagent_type: "dev-workflows-frontend:security-reviewer"
  • description: "Security review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review security compliance."

Store output as: $STEP_3_OUTPUT

Step 4: Verdict and Response

If security-reviewer returned blocked: Stop immediately. Report the blocked finding and escalate to user. Do not proceed to fix steps.

Code compliance criteria (considering project stage):

  • Prototype: Pass at 70%+
  • Production: 90%+ recommended

Security criteria:

  • approved or approved_with_notes → Pass
  • needs_revision → Fail

Report both results independently using subagent output fields only:

Before presenting to the user, the orchestrator computes a recommended route per finding using the rule below (this rule is internal — do not include it in the user-facing prompt):

Finding pattern Recommended route
dd_violation where the code intent matches the original requirement but the Design Doc captured a different design d (Design-side update)
dd_violation where the code drifted from a still-correct Design Doc c (Code-side fix)
reliability / security / maintainability findings c (Code-side fix)

Then present to the user (label each finding with its recommended route, grouped by route):

Code Compliance: [complianceRate from code-reviewer]
  Verdict: [verdict from code-reviewer]
  Identifier Match Rate: [identifierMatchRate from code-reviewer]
  Acceptance Criteria:
  - [fulfilled] [item] (confidence: [high/medium/low])
  - [partially_fulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  - [unfulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  Identifier Mismatches:
  - [identifier]: DD=[designDocValue] Code=[codeValue] at [location] [recommended: c | d]
  Quality Findings:
  - [category] [location]: [description] — [rationale] [recommended: c]

Security Review: [status from security-reviewer]
  Findings by category:
  - [confirmed_risk] [location]: [description] — [rationale] [recommended: c]
  - [defense_gap] [location]: [description] — [rationale] [recommended: c]
  - [hardening] [location]: [description] — [rationale] [recommended: c]
  - [policy] [location]: [description] — [rationale] [recommended: c]
  Notes: [notes from security-reviewer, if present]

Resolve discrepancies — confirm or override the recommended route per finding:
  c) Code-side fix       — code violates Design Doc; modify code to match
  d) Design-side update  — code is correct; Design Doc is stale, revise it
  s) Skip                — accept current state without changes

Use AskUserQuestion. The default offer is "accept all recommended routes" — a single confirmation for the typical case where the orchestrator's recommendations are correct. When the user wants to override, collect per-finding c/d/s decisions instead. If the user selects s for everything: skip Steps 5-10, proceed to Step 11.

Step 5: Execute Skill

Execute Skill: documentation-criteria (for task file template)

Step 5d: Design-Side Update

Run this step only when the user routed at least one finding to d. When all routes are c or s, skip directly to Step 6.

  1. Invoke technical-designer-frontend in update mode using Agent tool:

    • subagent_type: "dev-workflows-frontend:technical-designer-frontend"
    • description: "Design Doc update from review findings"
    • prompt: "Update Design Doc at [path] in update mode. The implementation has diverged in the following ways that the team has decided to ratify in the design rather than in the code: [list of d-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
  2. Invoke document-reviewer to verify the updated Design Doc:

    • subagent_type: "dev-workflows-frontend:document-reviewer"
    • description: "Document review of updated Design Doc"
    • prompt: "Review updated Design Doc at [path] for consistency and completeness."
  3. When multiple Design Docs exist (ls docs/design/*.md | grep -v template | wc -l > 1), invoke design-sync:

    • subagent_type: "dev-workflows-frontend:design-sync"
    • description: "Cross-DD consistency check"
    • prompt: "source_design: [updated DD path]. Detect conflicts across all Design Docs after the update."
    • When sync_status: conflicts_found: present conflicts to the user; resolution requires re-invoking technical-designer-frontend for affected DDs.
  4. After Step 5d completes:

    • If the user selected d for all findings (no c routes) → skip Steps 6-8, proceed to Step 9 for re-validation
    • If the user selected both d and c → re-evaluate the c-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remaining c findings

Step 6: Create Task File

Create task file at docs/plans/tasks/review-fixes-YYYYMMDD.md Include both code compliance issues and security requiredFixes.

Step 7: Execute Fixes

Invoke task-executor-frontend using Agent tool:

  • subagent_type: "dev-workflows-frontend:task-executor-frontend"
  • description: "Execute review fixes"
  • prompt: "Task file: docs/plans/tasks/review-fixes-YYYYMMDD.md. Apply staged fixes (stops at 5 files)."

Step 8: Quality Check

Invoke quality-fixer-frontend using Agent tool:

  • subagent_type: "dev-workflows-frontend:quality-fixer-frontend"
  • description: "Quality gate check"
  • prompt: "Confirm quality gate passage for fixed files."

Step 9: Re-validate code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows-frontend:code-reviewer"
  • description: "Re-validate compliance"
  • prompt: "Re-validate Design Doc compliance after fixes. Design Doc: [path]. Implementation files: [file list]. Prior compliance issues: $STEP_2_OUTPUT. Verify each prior issue is resolved (whether resolved code-side or design-side)."

Step 10: Re-validate security-reviewer

Invoke security-reviewer using Agent tool (only if security fixes were applied):

  • subagent_type: "dev-workflows-frontend:security-reviewer"
  • description: "Re-validate security"
  • prompt: "Re-validate security after fixes. Prior findings: $STEP_3_OUTPUT. Design Doc: [path]. Implementation files: [file list]."

Step 11: Final Cleanup and Report

Delete the review-fix task file this recipe created (if any). Its work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete docs/plans/tasks/review-fixes-YYYYMMDD.md if it exists

If the file cannot be deleted (filesystem error), report the failure but do not block the final report.

Then present the final report:

Code Compliance:
  Initial: [X]%
  Final: [Y]% (if fixes executed)

Security Review:
  Initial: [status]
  Final: [status] (if fixes executed)
  Notes: [notes from approved_with_notes, if any]

Remaining issues:
- [items requiring manual intervention]

Cleanup: review-fixes task file removed

Auto-fixable Items (code-side path)

  • Simple unimplemented acceptance criteria
  • Error handling additions
  • Contract definition fixes
  • Function splitting (length/complexity improvements)
  • Security confirmed_risk and defense_gap fixes (input validation, auth checks, output encoding)

Non-fixable Items

  • Fundamental business logic changes
  • Architecture-level modifications
  • Committed secrets (blocked → human intervention)

Design-Side Update Triggers

Discrepancies suitable for the design-side path (code is correct, DD became stale):

  • Identifier renames where the new identifier reflects the team's current naming
  • Behavioral changes that match the original requirement intent better than what the DD captured
  • Component splits or merges where the new structure is sound and the DD documented the prior structure
  • New ACs that the implementation already satisfies but the DD never enumerated

Scope: Design Doc compliance validation, security review, code-side auto-fixes, and design-side update routing.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the review scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.
通过调用rule-advisor进行元认知分析,选择规则并识别失败模式,随后利用TaskCreate规划任务列表,最终依据规则和指导执行任务,确保高质量交付。
需要遵循特定规则执行复杂任务 涉及Agent提示词、交接或生成工件的创作 希望结合元认知分析优化任务执行流程
dev-workflows-frontend/skills/recipe-task/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-task -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-task",
    "description": "Execute tasks following appropriate rules with rule-advisor metacognition",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Task Execution with Metacognitive Analysis

Task: $ARGUMENTS

Mandatory Execution Process

Step 1: Rule Selection via rule-advisor (REQUIRED)

Invoke rule-advisor using Agent tool:

  • subagent_type: "dev-workflows:rule-advisor"
  • description: "Rule selection"
  • prompt: "Task: $ARGUMENTS. Select appropriate rules and perform metacognitive analysis."

Step 2: Utilize rule-advisor Output

After receiving rule-advisor's JSON response, proceed with:

  1. Understand Task Essence (from taskAnalysis.essence)

    • Focus on fundamental purpose, not surface-level work
    • Distinguish between "quick fix" vs "proper solution"
  2. Follow Selected Rules (from selectedRules)

    • Review each selected rule section
    • Apply concrete procedures and guidelines
  3. Recognize Past Failures (from metaCognitiveGuidance.pastFailures)

    • Apply countermeasures for known failure patterns
    • Use suggested alternative approaches
  4. Execute First Action (from metaCognitiveGuidance.firstStep)

    • Start with recommended action
    • Use suggested tools first

Step 3: Create Task List with TaskCreate

Register work steps using TaskCreate. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON".

Break down the task based on rule-advisor's guidance:

  • Reflect taskAnalysis.essence in task descriptions
  • Apply metaCognitiveGuidance.firstStep to first task
  • Restructure tasks considering warningPatterns
  • Set priorities based on dependency order and warningPatterns severity

Step 4: Execute Implementation

Proceed with task execution following:

  • Start with metaCognitiveGuidance.firstStep action from rule-advisor
  • Update task structure with TaskUpdate to reflect rule-advisor insights
  • Selected rules from rule-advisor
  • Task structure (managed via TaskCreate/TaskUpdate)
  • Quality standards defined in the selectedRules output from rule-advisor
  • Monitor warningPatterns flags throughout execution and adjust approach when triggered
用于更新现有设计文档、PRD或ADR。通过识别目标文档、明确变更内容,调用相应子代理执行更新,并经过代码验证、文档审查及一致性检查等多重质量关卡,最终获得审批后完成闭环。
用户要求更新现有的设计文档、产品需求文档或架构决策记录 用户指定具体文档路径并要求进行修订或补充
dev-workflows-frontend/skills/recipe-update-doc/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-update-doc -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-update-doc",
    "description": "Update existing design documents (Design Doc \/ PRD \/ ADR) with review",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to updating existing design documents.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

First Action: Register Steps 1-6 using TaskCreate before any execution.

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Execute update flow:
    • Identify target → Clarify changes → Update document → Review → Consistency check
    • Stop at every [Stop: ...] marker → Wait for user approval before proceeding
  3. Scope: Complete when updated document receives approval

CRITICAL: Execute document-reviewer and all stopping points — each serves as a quality gate for document accuracy.

Workflow Overview

Target document → [Stop: Confirm changes]
                        ↓
              technical-designer / technical-designer-frontend / prd-creator (update mode)
                        ↓ (Design Doc only)
              code-verifier → document-reviewer → [Stop: Review approval]
                        ↓ (Design Doc only)
              design-sync → [Stop: Final approval]

Scope Boundaries

Included in this skill:

  • Existing document identification and selection
  • Change content clarification with user
  • Document update with appropriate agent (update mode)
  • Document review with document-reviewer
  • Consistency verification with design-sync (Design Doc only)

Out of scope (redirect to appropriate skills):

  • New requirement analysis
  • Work planning or implementation

Responsibility Boundary: This skill completes with updated document approval.

Target document: $ARGUMENTS

Execution Flow

Step 1: Target Document Identification

# Check existing documents
ls docs/design/*.md docs/prd/*.md docs/adr/*.md 2>/dev/null | grep -v template

Decision flow:

Situation Action
$ARGUMENTS specifies a path Use specified document
$ARGUMENTS describes a topic Search documents matching the topic
Multiple candidates found Present options with AskUserQuestion
No documents found Report and end (document creation is out of scope)

Step 2: Document Type and Layer Determination

Determine type from document path, then determine the layer to select the correct update agent:

Path Pattern Type Update Agent Notes
docs/design/*.md Design Doc technical-designer or technical-designer-frontend See layer detection below
docs/prd/*.md PRD prd-creator -
docs/adr/*.md ADR technical-designer or technical-designer-frontend See layer detection below

Layer detection (for Design Doc and ADR): Read the document and determine its layer from content signals:

  • Frontend (→ technical-designer-frontend): Document title/scope mentions React, components, UI, frontend; or file contains component hierarchy, state management, UI interactions
  • Backend (→ technical-designer): All other cases (API, data layer, business logic, infrastructure)

ADR Update Guidance:

  • Minor changes (clarification, typo fix, small scope adjustment): Update the existing ADR file
  • Major changes (decision reversal, significant scope change): Create a new ADR that supersedes the original

Step 3: Change Content Clarification [Stop]

Use AskUserQuestion to clarify what changes are needed:

  • What sections need updating
  • Reason for the change (bug fix findings, spec change, review feedback, etc.)
  • Expected outcome after the update

Confirm understanding of changes with user before proceeding.

Step 4: Document Update

Invoke the update agent determined in Step 2:

subagent_type: [Update Agent from Step 2]
description: "Update [Type from Step 2]"
prompt: |
  Operation Mode: update
  Existing Document: [path from Step 1]

  ## Changes Required
  [Changes clarified in Step 3]

  Update the document to reflect the specified changes.
  Add change history entry.

Step 5: Document Review [Stop]

For Design Doc updates only: Before document-reviewer, invoke code-verifier:

subagent_type: code-verifier
description: "Verify updated Design Doc"
prompt: |
  doc_type: design-doc
  document_path: [path from Step 1]
  Verify the updated Design Doc against current codebase.

  Verification focus: Pay special attention to literal identifier referential
  integrity in the updated sections (paths, endpoints, type names, config keys).

Store output as: $CODE_VERIFICATION_OUTPUT

Invoke document-reviewer:

subagent_type: document-reviewer
description: "Review updated document"
prompt: |
  Review the following updated document.

  doc_type: [Design Doc / PRD / ADR]
  target: [path from Step 1]
  mode: standard
  code_verification: $CODE_VERIFICATION_OUTPUT (Design Doc only, omit for PRD/ADR)

  Focus on:
  - Consistency of updated sections with rest of document
  - No contradictions introduced by changes
  - Completeness of change history

Store output as: $STEP_5_OUTPUT

On review result:

  • Approved → Proceed to Step 6
  • Needs revision → Return to Step 4 with the following prompt (max 2 iterations):
    subagent_type: [Update Agent from Step 2]
    description: "Revise [Type from Step 2]"
    prompt: |
      Operation Mode: update
      Existing Document: [path from Step 1]
    
      ## Review Feedback to Address
      $STEP_5_OUTPUT
    
      Address each issue raised in the review feedback.
    
  • After 2 rejections → Flag for human review, present accumulated feedback to user and end

Present review result to user for approval.

Step 6: Consistency Verification (Design Doc only) [Stop]

Skip condition: Document type is PRD or ADR → Proceed to completion.

For Design Doc, invoke design-sync:

subagent_type: design-sync
description: "Verify consistency"
prompt: |
  Verify consistency of the updated Design Doc with other design documents.

  Updated document: [path from Step 1]

On consistency result:

  • No conflicts → Present result to user for final approval
  • Conflicts detected → Present conflicts to user with AskUserQuestion:
    • A: Return to Step 4 to resolve conflicts in this document
    • B: End and address conflicts separately

Error Handling

Error Action
Target document not found Report and end (document creation is out of scope)
Sub-agent update fails Log failure, present error to user, retry once
Review rejects after 2 revisions Stop loop, flag for human intervention
design-sync detects conflicts Present to user for resolution decision

Completion Criteria

  • Identified target document
  • Clarified change content with user
  • Updated document with appropriate agent (update mode)
  • Executed code-verifier before document-reviewer (Design Doc only)
  • Executed document-reviewer and addressed feedback
  • Executed design-sync for consistency verification (Design Doc only)
  • Obtained user approval for updated document

Output Example

Document update completed.

  • Updated document: docs/design/[document-name].md
  • Approval status: User approved
指导多智能体协调与工作流程编排。负责任务分发、规模评估及子代理调度,监控需求变更并触发重分析,确保各专家代理自主执行,涵盖从需求分析到安全审查的全流程管理。
需要协调多个子代理完成任务 管理工作流阶段或执行模式 检测需求范围扩展信号
dev-workflows-frontend/skills/subagents-orchestration-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill subagents-orchestration-guide -g -y
SKILL.md
Frontmatter
{
    "name": "subagents-orchestration-guide",
    "description": "Guides subagent coordination through implementation workflows. Use when orchestrating multiple agents, managing workflow phases, or determining autonomous execution mode."
}

Subagents Orchestration Guide

Role: The Orchestrator

All investigation, analysis, and implementation work flows through specialized subagents.

First Action Rule

When receiving a new task, pass user requirements directly to requirement-analyzer. Determine the workflow based on its scale assessment result.

Requirement Change Detection During Flow

During flow execution, monitor user responses for scope-expanding signals:

  • Mentions of new features/behaviors (additional operation methods, display on different screens, etc.)
  • Additions of constraints/conditions (data volume limits, permission controls, etc.)
  • Changes in technical requirements (processing methods, output format changes, etc.)

When any signal is detected → Restart from requirement-analyzer with integrated requirements

Available Subagents

Implementation support:

  1. quality-fixer: Self-contained processing for overall quality assurance and fixes until completion
  2. task-decomposer: Appropriate task decomposition of work plans
  3. task-executor: Individual task execution and structured response
  4. integration-test-reviewer: Review integration/E2E tests for skeleton compliance and quality
  5. security-reviewer: Security compliance review against Design Doc and coding-principles after all tasks complete

Document creation: 6. requirement-analyzer: Requirement analysis and work scale determination 7. codebase-analyzer: Analyze existing codebase to produce focused guidance for technical design (data, contracts, dependencies, quality assurance mechanisms) 8. ui-analyzer: Read the project's external-resources file, fetch external UI sources (design origin, design system, guidelines) via MCP/URL/file, and analyze existing UI code. Frontend/fullstack features; runs in parallel with codebase-analyzer. Uses disallowedTools to inherit MCP access 9. prd-creator: Product Requirements Document creation 10. ui-spec-designer: UI Specification creation from PRD and optional prototype code (frontend/fullstack features) 11. technical-designer: ADR/Design Doc creation 12. work-planner: Work plan creation from Design Doc and test skeletons 13. document-reviewer: Single document quality and rule compliance check 14. code-verifier: Verify document-code consistency. Pre-implementation: Design Doc claims against existing codebase. Post-implementation: implementation against Design Doc 15. design-sync: Design Doc consistency verification across multiple documents 16. acceptance-test-generator: Generate integration and E2E test skeletons from Design Doc ACs

Orchestration Principles

Delegation Boundary: What vs How

The orchestrator passes what to accomplish and where to work. Each specialist determines how to execute autonomously.

Pass to specialists (what/where/constraints):

  • Target directory, package, or file paths
  • Task file path or scope description
  • Acceptance criteria and hard constraints from the user or design artifacts

Let specialists determine (how):

  • Specific commands to run (specialists discover these from project configuration and repo conventions)
  • Execution order and tool flags
  • Which files to inspect or modify within the given scope
Bad (orchestrator prescribes how) Good (orchestrator passes what)
quality-fixer "Run these checks: 1. lint 2. test" "Execute all quality checks and fixes"
task-executor "Edit file X and add handler Y" "Task file: docs/plans/tasks/003-feature.md"

Decision precedence when outputs conflict:

  1. User instructions (explicit requests or constraints)
  2. Task files and design artifacts (Design Doc, PRD, work plan)
  3. Objective repo state (git status, file system, project configuration)
  4. Specialist judgment

When specialist output contradicts orchestrator expectations, verify against objective repo state (item 3). If repo state confirms the specialist, follow the specialist. Override specialist output only when it conflicts with items 1 or 2.

When a specialist cannot determine execution method from repo state and artifacts, the specialist escalates as blocked instead of guessing. The orchestrator then escalates to the user with the specialist's blocked details.

Task Assignment with Responsibility Separation

Assign work based on each subagent's responsibilities:

What to delegate to task-executor:

  • Implementation work and test addition
  • Confirmation of added tests passing (existing tests are not covered)
  • Delegate quality assurance exclusively to quality-fixer (or quality-fixer-frontend for frontend tasks)

What to delegate to quality-fixer:

  • Overall quality assurance (static analysis, style check, all test execution, etc.)
  • Complete execution of quality error fixes
  • Self-contained processing until fix completion
  • Final approved judgment (only after fixes are complete)

Constraints Between Subagents

Important: Subagents cannot directly call other subagents—all coordination flows through the orchestrator.

Explicit Stop Points

Autonomous execution MUST stop and wait for user input at these points. Use AskUserQuestion to present confirmations and questions.

Phase Stop Point User Action Required
Requirements After requirement-analyzer completes Confirm requirements / Answer questions
PRD After document-reviewer completes PRD review Approve PRD
UI Spec After document-reviewer completes UI Spec review (frontend/fullstack) Approve UI Spec
ADR After document-reviewer completes ADR review (if ADR created) Approve ADR
Design After design-sync completes consistency verification Approve Design Doc
Work Plan After work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) or work-planner (Small) completes Batch approval for implementation phase

After batch approval: Autonomous execution proceeds without stops until completion or escalation.

Scale Determination and Document Requirements

Scale File Count PRD ADR Design Doc Work Plan
Small 1-2 Update※1 Not needed Not needed Simplified
Medium 3-5 Update※1 Conditional※2 Required Required
Large 6+ Required※3 Conditional※2 Required Required

※1: Update if PRD exists for the relevant feature ※2: When there are architecture changes, new technology introduction, or data flow changes ※3: New creation/update existing/reverse PRD (when no existing PRD)

How to Call Subagents

Execution Method

Each subagent invocation is a fresh Agent tool call, isolating each phase's context; a SendMessage resume reuses the prior agent's context and breaks that isolation. Each call uses:

  • subagent_type: Agent name (e.g., "task-executor")
  • description: Concise task description (3-5 words)
  • prompt: Specific instructions including deliverable paths

Orchestrator's Permitted Tools

The orchestrator coordinates work using only the following tools:

Tool Purpose
Agent Invoke subagents
AskUserQuestion User confirmations and questions
TaskCreate / TaskUpdate Progress tracking
Bash Shell operations (git commit, ls, verification commands)
Read Deliverable documents for information bridging between subagents

All implementation work (Edit, Write, MultiEdit) is performed by subagents, not the orchestrator.

Prompt Construction Rule

Every subagent prompt must include:

  1. Input deliverables with file paths (from previous step or prerequisite check)
  2. Expected action (what the agent should do)

Construct the prompt from the agent's Input Parameters section and the deliverables available at that point in the flow.

Two additional rules:

  • Subagents see only the Agent prompt and files they read. Include required paths, prior JSON, parameters, and scope constraints explicitly.
  • Replace every [placeholder] in examples below with concrete values before invoking the Agent tool.

Call Example (requirement-analyzer)

  • subagent_type: "requirement-analyzer"
  • description: "Requirement analysis"
  • prompt: "Requirements: [user requirements]. Context: [any relevant context]. Perform requirement analysis and scale determination."

Call Example (codebase-analyzer)

  • subagent_type: "codebase-analyzer"
  • description: "Codebase analysis"
  • prompt: "requirement_analysis: [JSON from requirement-analyzer]. prd_path: [path if exists]. requirements: [original user requirements]. Analyze the existing codebase and produce design guidance."

Call Example (ui-analyzer)

  • subagent_type: "ui-analyzer"
  • description: "UI fact gathering"
  • prompt: "requirement_analysis: [JSON from requirement-analyzer]. requirements: [original user requirements]. ui_spec_path: [path if exists]. target_components: [list if focused]. Read docs/project-context/external-resources.md, fetch external UI sources via the declared access methods (MCP / URL / file), and analyze the existing UI codebase. Output the consolidated UI fact JSON."

When invoked alongside codebase-analyzer for frontend or fullstack-frontend work, run both agents in parallel and pass both JSON outputs to consumers (ui-spec-designer for the design phase; technical-designer-frontend for the Design Doc phase).

Call Example (task-executor)

  • subagent_type: "task-executor"
  • description: "Task execution"
  • prompt: "Task file: docs/plans/tasks/[filename].md Please complete the implementation"

Structured Response Specification

Subagents respond in JSON format. Key fields for orchestrator decisions:

  • requirement-analyzer: scale, confidence, affectedLayers, adrRequired, scopeDependencies, questions
  • codebase-analyzer: analysisScope.categoriesDetected, dataModel.detected, qualityAssurance (mechanisms[], domainConstraints[]), focusAreas[], existingElements count, limitations
  • ui-analyzer: analysisScope.uiConventions, externalResources (designOrigin/designSystem/guidelines/visualVerification with fetch_status), componentStructure[], propsPatterns[], cssLayout[], stateDisplay[], displayConditions[], i18n, accessibility[], generatedArtifacts[], focusAreas[] (raw fact_id; consumers apply ui: prefix when merging with codebase analysis facts), candidateWriteSet[] (with confidence labels), limitations
  • code-verifier: status (consistent/mostly_consistent/needs_review/inconsistent), consistencyScore, discrepancies[], reverseCoverage (including dataOperationsInCode, testBoundariesSectionPresent). Pre-implementation: verifies Design Doc claims against existing codebase. Post-implementation: verifies implementation consistency against Design Doc (pass code_paths scoped to changed files)
  • task-executor: status (escalation_needed/completed), escalation_type (design_compliance_violation/similar_function_found/investigation_target_not_found/out_of_scope_file/dependency_version_uncertain/binding_decision_violation/test_environment_not_ready), testsAdded, requiresTestReview
  • quality-fixer: Input: task_file (path to current task file — always pass this in orchestrated flows). Status: approved/stub_detected/blocked. stub_detected → route back to task-executor with incompleteImplementations[] details for completion, then re-run quality-fixer. blocked → discriminate by reason field: "Cannot determine due to unclear specification" → read blockingIssues[] for specification details; "Execution prerequisites not met" → read missingPrerequisites[] with resolutionSteps — present these to the user as actionable next steps
  • document-reviewer: verdict.decision (approved/approved_with_conditions/needs_revision/rejected)
  • design-sync: sync_status (synced/conflicts_found)
  • integration-test-reviewer: status (approved/needs_revision/blocked), requiredFixes
  • security-reviewer: status (approved/approved_with_notes/needs_revision/blocked), findings, notes, requiredFixes
  • acceptance-test-generator: status, generatedFiles.{integration,fixtureE2e,serviceE2e} (path|null per lane), budgetUsage per lane, e2eAbsenceReason per E2E lane (null when emitted; reason enum is owned by acceptance-test-generator and integration-e2e-testing skill)

Handling Requirement Changes

Handling Requirement Changes in requirement-analyzer

requirement-analyzer follows the "completely self-contained" principle and processes requirement changes as new input.

How to Integrate Requirements

Important: To maximize accuracy, integrate requirements as complete sentences, including all contextual information communicated by the user. Result format: raw concatenation of all requirements, followed by a labeled summary (Initial requirement: … / Additional requirement: …).

Update Mode for Document Generation Agents

Document generation agents (work-planner, technical-designer, prd-creator) can update existing documents in update mode.

  • Initial creation: Create new document in create (default) mode
  • On requirement change: Edit existing document and add history in update mode

Criteria for timing when to call each agent:

  • work-planner: Request updates only before execution
  • technical-designer: Request updates according to design changes → Execute document-reviewer for consistency check
  • prd-creator: Request updates according to requirement changes → Execute document-reviewer for consistency check
  • document-reviewer: Always execute before user approval after PRD/ADR/Design Doc creation/update, and after Work Plan creation/update at Medium/Large scale (Small uses a simplified plan with no semantic review — no Design Doc to trace against)

Basic Flow: Planning and Implementation

Always start with requirement-analyzer, then select the minimum planning flow required by scale and affected layers.

Planning flow (per scale)

Scale Planning flow (ends at task-decomposer for Medium/Large; ends at work-planner for Small)
Large requirement-analyzer → PRD → PRD review → external resource hearing → optional ADR → codebase-analyzer (+ ui-analyzer in parallel for frontend/fullstack) → optional UI Spec → Design Doc → code-verifier → document-reviewer → design-sync → acceptance-test-generator → work-planner → work plan review (document-reviewer, doc_type WorkPlan) → task-decomposer
Medium requirement-analyzer → external resource hearing → codebase-analyzer (+ ui-analyzer in parallel for frontend/fullstack) → optional UI Spec → optional ADR → Design Doc → code-verifier → document-reviewer → design-sync → acceptance-test-generator → work-planner → work plan review (document-reviewer, doc_type WorkPlan) → task-decomposer
Small requirement-analyzer → work-planner

External resource hearing runs in the orchestrator (it requires AskUserQuestion). ui-analyzer joins codebase-analyzer in parallel only when the work has a frontend surface; for backend-only work the planning flow uses codebase-analyzer alone.

After the planning flow completes and the user grants batch approval, implementation proceeds. Verifying the plan is implementable end-to-end (verification lanes, fixtures, E2E environment) is an optional preflight the user runs at their discretion via the recipe-prepare-implementation recipe; this guide does not invoke any orchestrator above the agent layer.

Then execute the task execution cycle: task-executor → quality-fixer → commit for each task. See "Autonomous Execution Mode" below for full per-task details. At Small scale this cycle still applies — implementation runs through task-executor, not orchestrator-direct edits.

Each agent name in the chain is invoked via the Agent tool (per "Orchestrator's Permitted Tools" above).

Rules:

  • Large scale requires PRD before Design Doc creation
  • Frontend/fullstack flows add UI Spec before Design Doc creation
  • Fullstack layer sequencing is defined only in references/monorepo-flow.md
  • design-sync is required whenever multiple Design Docs exist
  • task-decomposer begins only after work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) and batch approval
  • Work plan review self-heals: on verdict.decision needs_revision, route back to work-planner (update) and re-review until approved/approved_with_conditions; rejected escalates to the user. The work plan is a derivation of the Design Doc, so plan-fidelity findings need no user adjudication

Autonomous Execution Mode

Pre-Execution Environment Check

Principle: Verify subagents can complete their responsibilities

Required environments:

  • Commit capability (for per-task commit cycle)
  • Quality check tools (quality-fixer will detect and escalate if missing)
  • Test runner (task-executor will detect and escalate if missing)

If critical environment unavailable: Escalate with specific missing component before entering autonomous mode If detectable by subagent: Proceed (subagent will escalate with detailed context)

Authority Delegation

After environment check passes:

  • Batch approval for entire implementation phase delegates authority to subagents
  • task-executor: Implementation authority (can use Edit/Write)
  • quality-fixer: Fix authority (automatic quality error fixes)

Definition of Autonomous Execution Mode

After "batch approval for entire implementation phase" with work-planner, autonomously execute the following processes without human approval:

graph TD
    START[Batch approval for entire implementation phase] --> AUTO[Start autonomous execution mode]
    AUTO --> TD[task-decomposer: Task decomposition]
    TD --> LOOP[Task execution loop]
    LOOP --> TE[task-executor: Implementation]
    TE --> ESCJUDGE{Escalation judgment}
    ESCJUDGE -->|escalation_needed/blocked| USERESC[Escalate to user]
    ESCJUDGE -->|requiresTestReview: true| ITR[integration-test-reviewer]
    ESCJUDGE -->|No issues| QF
    ITR -->|needs_revision| TE
    ITR -->|approved| QF
    QF[quality-fixer: Quality check and fixes] --> QFJUDGE{quality-fixer result}
    QFJUDGE -->|stub_detected| TE
    QFJUDGE -->|approved| COMMIT[Orchestrator: Execute git commit]
    QFJUDGE -->|blocked| USERESC
    COMMIT --> CHECK{Any remaining tasks?}
    CHECK -->|Yes| LOOP
    CHECK -->|No| VERIFY[Post-implementation verification]
    VERIFY --> CV[code-verifier: DD consistency check]
    VERIFY --> SEC[security-reviewer: Security review]
    CV --> VRESULT{Verification results}
    SEC --> VRESULT
    VRESULT -->|All passed| REPORT[Completion report]
    VRESULT -->|Any failed| VFIX[task-executor: Verification fixes]
    VFIX --> QF2[quality-fixer: Quality check]
    QF2 --> REVERIFY[Re-run failed verifiers only]
    REVERIFY --> VRESULT
    VRESULT -->|blocked| USERESC

    LOOP --> INTERRUPT{User input?}
    INTERRUPT -->|None| TE
    INTERRUPT -->|Yes| REQCHECK{Requirement change check}
    REQCHECK -->|No change| TE
    REQCHECK -->|Change| STOP[Stop autonomous execution]
    STOP --> RA[Re-analyze with requirement-analyzer]

Post-Implementation Verification Pass/Fail Criteria

Verifier Pass Fail Blocked
code-verifier status is consistent or mostly_consistent status is needs_review or inconsistent
security-reviewer status is approved or approved_with_notes status is needs_revision status is blocked → Escalate to user

Re-run rule: After fix cycle, re-run only verifiers that returned fail. Verifiers that passed on the previous run are not re-run.

Conditions for Stopping Autonomous Execution

Stop autonomous execution and escalate to user in the following cases:

  1. Escalation from subagent

    • When receiving response with status: "escalation_needed"
    • When receiving response with status: "blocked"
  2. When requirement change detected

    • Any match in requirement change detection checklist
    • Stop autonomous execution and re-analyze with integrated requirements in requirement-analyzer
  3. When work-planner update restriction is violated

    • Requirement changes after task-decomposer starts require overall redesign
    • Restart entire flow from requirement-analyzer
  4. When user explicitly stops

    • Direct stop instruction or interruption

Task Management: 4-Step Cycle

Per-task cycle:

  1. Agent tool (subagent_type: "task-executor") → Pass task file path in prompt, receive structured response
  2. Check task-executor response:
    • status: escalation_needed or blocked → Escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 1 with requiredFixes
      • approved → Proceed to step 3
    • Otherwise → Proceed to step 3
  3. quality-fixer → Quality check and fixes. Always pass the current task file path as task_file
    • stub_detected → Return to step 1 with incompleteImplementations[] details
    • blocked → Escalate to user
    • approved → Proceed to step 4
  4. git commit → Execute with Bash (on approved)

Progress Tracking

Register overall phases using TaskCreate. Update each phase with TaskUpdate as it completes.

Main Orchestrator Roles

  1. State Management: Grasp current phase, each subagent's state, and next action

  2. Information Bridging: Data conversion and transmission between subagents

    • Convert each subagent's output to next subagent's input format
    • Always pass deliverables from previous process to next agent
    • Extract necessary information from structured responses
    • Compose commit messages from changeSummary
    • Explicitly integrate initial and additional requirements when requirements change

    Handoff Contracts

    HC-01: requirement-analyzer → codebase-analyzer

    • Pass: requirement_analysis, prd_path (if exists), original user requirements

    HC-02: codebase-analyzer → technical-designer

    • Pass: full codebase-analyzer JSON as additional context
    • Required downstream uses:
      • focusAreas → canonical disposition-target list for the Fact Disposition Table
      • dataModel, dataTransformationPipelines, qualityAssurance → Existing Codebase Analysis / Verification Strategy / Quality Assurance sections

    HC-03: technical-designer → code-verifier

    • Pass: Design Doc path (doc_type: design-doc)
    • Do not pass code_paths; code-verifier discovers scope from the document

    HC-04: code-verifier + codebase-analyzer → document-reviewer

    • Pass: code_verification JSON and the same codebase_analysis JSON previously given to the designer
    • Purpose: reviewer validates both discrepancy integration and Fact Disposition coverage against focusAreas

    HC-05: code-verifier → next-layer technical-designer (fullstack only)

    • Defined only for multi-layer fullstack flow in references/monorepo-flow.md
    • Pass: prior-layer Design Doc path plus prior_layer_verification
    • Use only discrepancies[] as known issues to address or escalate. Do not infer verified claims that are not explicitly present in the verifier output.

    technical-designer → work-planner

    Pass to work-planner: Design Doc path. Work-planner reads the DD template from documentation-criteria skill, scans all DD sections, and extracts technical requirements in these categories:

    • Verification Strategy: Extracted to work plan header (Correctness Proof Method + Early Verification Point)
    • Implementation targets: Components, functions, or data structures to create or modify
    • Connection/switching/registration: Integration points, dependency wiring, switching methods
    • Contract changes and propagation: Interface changes, data contracts, field propagation across boundaries
    • Verification requirements: Verification methods, test boundaries, integration verification points
    • Prerequisite work: Migration steps, security measures, environment setup

    Work-planner produces a Design-to-Plan Traceability table mapping each extracted item to covering task(s). Items without a covering task must be marked as gap with justification. Unjustified gaps are errors. Justified gaps require user confirmation before plan approval.

    HC-06: acceptance-test-generator → work-planner

    Pass to acceptance-test-generator: Design Doc path; UI Spec path (if exists).

    Orchestrator verification: Every non-null generatedFiles.<lane> path exists on disk. For each null lane, e2eAbsenceReason.<lane> is present (intentional absence, not an error).

    Pass to work-planner: integration / fixture-e2e / service-integration-e2e file paths (or null per lane), per-lane absence reasons, plus timing guidance — integration tests are created alongside each phase implementation, fixture-e2e tests are created alongside the UI feature phase, service-integration-e2e tests are executed only in the final phase.

    On error: Escalate to user when status != completed and integration file generation failed unexpectedly. A null E2E lane with a valid absence reason is not an error.

  3. ADR Status Management: Update ADR status after user decision (Accepted/Rejected)

Important Constraints

Recap (defined above): quality-fixer approval before commit; inter-agent communication is JSON; document-reviewer + user approval before proceeding; check next step against work planning flow after approval; resolve conflicts via Decision precedence.

References

  • references/monorepo-flow.md: Fullstack (monorepo) orchestration flow
执行元认知任务分析与技能选择,通过解析任务本质、估算规模及类型,结合标签匹配与隐式依赖,从技能索引中筛选并排序推荐技能,辅助复杂决策。
需要评估任务复杂度时 决定选用哪些开发技能时 估算工作规模或文件数量时
dev-workflows-frontend/skills/task-analyzer/SKILL.md
npx skills add shinpr/claude-code-workflows --skill task-analyzer -g -y
SKILL.md
Frontmatter
{
    "name": "task-analyzer",
    "description": "Performs metacognitive task analysis and skill selection. Use when determining task complexity, selecting appropriate skills, or estimating work scale."
}

Task Analyzer

Provides metacognitive task analysis and skill selection guidance.

Skills Index

See skills-index.yaml for available skills metadata.

Task Analysis Process

1. Understand Task Essence

Identify the fundamental purpose beyond surface-level work:

Surface Work Fundamental Purpose
"Fix this bug" Problem solving, root cause analysis
"Implement this feature" Feature addition, value delivery
"Refactor this code" Quality improvement, maintainability
"Update this file" Change management, consistency

Action: Map the user request to one row in the Surface Work → Fundamental Purpose table above. If no row matches, state the fundamental purpose explicitly before proceeding.

2. Estimate Task Scale

Scale File Count Indicators
Small 1-2 Single function/component change
Medium 3-5 Multiple related components
Large 6+ Cross-cutting concerns, architecture impact

Scale affects skill priority:

  • Scale >= Large → include documentation-criteria and implementation-approach in selectedSkills with priority high
  • Scale = Small → limit selectedSkills to task-type essential skills only (max 3)

3. Identify Task Type

Type Characteristics Key Skills
Implementation New code, features coding-principles, testing-principles
Fix Bug resolution ai-development-guide, testing-principles
Refactoring Structure improvement coding-principles, ai-development-guide
Design Architecture decisions documentation-criteria, implementation-approach
Quality Testing, review testing-principles, integration-e2e-testing

4. Tag-Based Skill Matching

Extract relevant tags from task description and match against skills-index.yaml:

Task: "Implement user authentication with tests"
Extracted tags: [implementation, testing, security]
Matched skills:
  - coding-principles (implementation, security)
  - testing-principles (testing)
  - ai-development-guide (implementation)

5. Implicit Relationships

Consider hidden dependencies:

Task Involves Also Include
Error handling debugging, testing
New features design, implementation, documentation
Performance profiling, optimization, testing
Frontend typescript-rules, test-implement
API/Integration integration-e2e-testing

Output Format

Return structured analysis with skill metadata from skills-index.yaml:

taskAnalysis:
  essence: <string>  # Fundamental purpose identified
  type: <implementation|fix|refactoring|design|quality>
  scale: <small|medium|large>
  estimatedFiles: <number>
  tags: [<string>, ...]  # Extracted from task description

selectedSkills:
  - skill: <skill-name>  # From skills-index.yaml
    priority: <high|medium|low>
    reason: <string>  # Why this skill was selected
    # Pass through metadata from skills-index.yaml
    tags: [...]
    typical-use: <string>
    size: <small|medium|large>
    sections: [...]  # All sections from yaml, unfiltered

Note: Section selection (choosing which sections are relevant) is done after reading the actual SKILL.md files.

Skill Selection Priority

  1. Essential - Directly related to task type
  2. Quality - Testing and quality assurance
  3. Process - Workflow and documentation
  4. Supplementary - Reference and best practices

Metacognitive Question Design

Generate 3-5 questions according to task nature:

Task Type Question Focus
Implementation Design validity, edge cases, performance
Fix Root cause (5 Whys), impact scope, regression testing
Refactoring Current problems, target state, phased plan
Design Requirement clarity, future extensibility, trade-offs

Warning Patterns

Detect and flag these patterns:

Pattern Warning Mitigation
Large change detected Pair with implementation-approach Split into phases per strategy
Implementation task detected Pair with testing-principles Apply TDD from start
Error fix requested Pair with ai-development-guide Apply 5 Whys before fixing
Multi-file task without plan Pair with documentation-criteria Create work plan first
用于指导单元测试、集成测试及E2E测试的实现规范。涵盖React组件测试(RTL+Vitest+MSW)和Playwright E2E测试,遵循AAA结构、独立性及用户视角命名原则。
编写React组件单元测试 实现集成测试 开发Playwright E2E测试 需要遵循特定测试约定
dev-workflows-frontend/skills/test-implement/SKILL.md
npx skills add shinpr/claude-code-workflows --skill test-implement -g -y
SKILL.md
Frontmatter
{
    "name": "test-implement",
    "description": "Test implementation patterns and conventions. Use when implementing unit tests, integration tests, or E2E tests, including RTL+Vitest+MSW component testing and Playwright E2E testing."
}

Test Implementation Patterns

Reference Selection

Test Type Reference When to Use
Unit / Integration references/frontend.md Implementing React component tests with RTL + Vitest + MSW
E2E references/e2e.md Implementing browser-level E2E tests with Playwright

Common Principles

AAA Structure

All tests follow Arrange-Act-Assert:

  • Arrange: Set up preconditions and inputs
  • Act: Execute the behavior under test
  • Assert: Verify the expected outcome

Test Independence

  • Each test runs independently without depending on other tests
  • No shared mutable state between tests
  • Deterministic execution — no random or time dependencies without mocking

Naming

  • Test names describe expected behavior from user perspective
  • One test verifies one behavior
提供语言无关的测试原则,涵盖TDD红绿重构循环、覆盖率策略、独立快速的可复现测试标准,以及单元/集成/E2E测试类型与AAA设计模式。适用于编写测试、制定测试策略及审查测试质量。
编写单元测试或集成测试时 设计整体测试策略或覆盖标准时 审查现有测试代码的质量与结构时 实施TDD流程遇到阻碍时
dev-workflows-frontend/skills/testing-principles/SKILL.md
npx skills add shinpr/claude-code-workflows --skill testing-principles -g -y
SKILL.md
Frontmatter
{
    "name": "testing-principles",
    "description": "Language-agnostic testing principles including TDD, test quality, coverage standards, and test design patterns. Use when writing tests, designing test strategies, or reviewing test quality."
}

Language-Agnostic Testing Principles

Test-Driven Development (TDD)

The RED-GREEN-REFACTOR Cycle

Always follow this cycle:

  1. RED: Write a failing test first

    • Write the test before implementation
    • Ensure the test fails for the right reason
    • Verify test can actually fail
  2. GREEN: Write minimal code to pass

    • Implement just enough to make the test pass
    • Focus on making it work
  3. REFACTOR: Improve code structure

    • Clean up implementation
    • Eliminate duplication
    • Improve naming and clarity
    • Keep all tests passing
  4. VERIFY: Ensure all tests still pass

    • Run full test suite
    • Check for regressions
    • Validate refactoring didn't break anything

Quality Requirements

Coverage

  • Treat coverage as a diagnostic signal for finding untested areas, not a target — a target gets gamed into trivial tests (Goodhart's Law)
  • Concentrate tests on critical paths, business logic, and behavior whose regression would matter
  • Prioritize meaningful assertions over the coverage number; any CI threshold is the project's config, not a quality goal in itself

Test Characteristics

All tests must be:

  • Independent: No dependencies between tests (see Test Independence Verification for detailed criteria)
  • Reproducible: Same input always produces same output
  • Fast: Unit tests < 100ms each, integration tests < 1s each, full suite < 10 minutes
  • Self-checking: Clear pass/fail without manual verification
  • Timely: Written close to the code they test

Test Types

Unit Tests

Purpose: Test individual components in isolation

Characteristics:

  • Test single function, method, or class
  • Fast execution (milliseconds)
  • No external dependencies
  • Mock external services
  • Majority of your test suite

Integration Tests

Purpose: Test interactions between components

Characteristics:

  • Test multiple components together
  • May include database, file system, or APIs
  • Slower than unit tests
  • Verify contracts between modules
  • Smaller portion of test suite

End-to-End (E2E) Tests

Purpose: Test complete workflows from user perspective

Characteristics:

  • Test entire application stack
  • Simulate real user interactions
  • Slowest test type
  • Fewest in number
  • Highest confidence level

Test Design Principles

AAA Pattern (Arrange-Act-Assert)

Structure every test in three clear phases:

// Arrange: Setup test data and conditions
user = createTestUser()
validator = createValidator()

// Act: Execute the code under test
result = validator.validate(user)

// Assert: Verify expected outcome
assert(result.isValid == true)

Adaptation: Apply this structure using your language's idioms (methods, functions, procedures)

One Assertion Per Concept

  • Test one behavior per test case
  • Multiple assertions OK if testing single concept
  • Split unrelated assertions into separate tests

Example: prefer returns error when email is invalid over validates user.

Descriptive Test Names

Test names should clearly describe:

  • What is being tested
  • Under what conditions
  • What the expected outcome is

Recommended format: "should [expected behavior] when [condition]"

Examples:

test("should return error when email is invalid")
test("should calculate discount when user is premium")
test("should throw exception when file not found")

Adaptation: Follow your project's naming convention (camelCase, snake_case, describe/it blocks)

Test Independence

Setup and Teardown

  • Use setup hooks to prepare test environment
  • Use teardown hooks to clean up resources
  • Keep setup minimal and focused
  • Ensure teardown runs even if test fails

Mocking and Test Doubles

When to Use Mocks

  • Mock external dependencies: APIs, databases, file systems
  • Mock slow operations: Network calls, heavy computations
  • Mock unpredictable behavior: Random values, current time
  • Mock unavailable services: Third-party services

Mocking Principles

  • Mock at boundaries, not internally
  • Keep mocks simple and focused
  • Verify mock expectations when relevant
  • Wrap external libraries/frameworks behind adapters and mock the adapter

Data Layer Testing

Mock Limitations for Data Layer

Mocks validate call patterns but cannot verify data layer correctness. The following pass through undetected with mock-only testing:

  • Schema mismatches (table names, column names, data types)
  • Query correctness (joins, filters, aggregations, grouping)
  • Database constraints (NOT NULL, UNIQUE, foreign keys)
  • Migration drift (schema changes that make code out of sync)

When Mocks Are Appropriate for Data Access

  • Testing business logic that receives data from the data layer (mock the repository, test the service)
  • Testing error handling paths (simulating connection failures, timeouts)
  • Unit tests where data access is a dependency, not the subject under test

When Mocks Are Insufficient for Data Access

  • Testing repository or data access implementations themselves
  • Verifying query correctness (joins, filters, aggregations, grouping)
  • Testing data integrity constraints
  • Testing migration compatibility

Real Database Testing (Environment-Dependent)

Options for verifying data layer correctness against a real database engine:

  • Containerized databases for CI environments
  • In-memory databases for fast feedback (note: dialect differences may mask issues)
  • Dedicated test databases with seed data

The appropriate approach depends on project environment and CI/CD capabilities.

AI-Generated Code and Schema Awareness

  • AI-generated data access code has heightened schema hallucination risk
  • Generated queries may use correct syntax but reference nonexistent schema elements
  • Mock-based tests pass regardless of schema accuracy
  • Mitigation: Design Docs should include explicit schema references so that documented schemas can be cross-checked against data access code during review

Test Quality Practices

Keep Tests Active

  • Fix or delete failing tests: Resolve failures immediately
  • Remove commented-out tests: Fix them or delete entirely
  • Keep tests running: Broken tests lose value quickly
  • Maintain test suite: Refactor tests as needed

Test Helpers and Utilities

  • Create reusable test data builders
  • Extract common setup into helper functions
  • Build test utilities for complex scenarios
  • Share helpers across test files appropriately

What to Test

Focus on Behavior

Test observable behavior, not implementation:

Good: Test that function returns expected output ✓ Good: Test that correct API endpoint is called ✗ Bad: Test that internal variable was set ✗ Bad: Test order of private method calls

Test Public APIs

  • Test through public interfaces
  • Avoid testing private methods directly
  • Test return values, outputs, exceptions
  • Test side effects (database, files, logs)

Test Edge Cases

Always test:

  • Boundary conditions: Min/max values, empty collections
  • Error cases: Invalid input, null values, missing data
  • Edge cases: Special characters, extreme values
  • Happy path: Normal, expected usage

Test Quality Criteria

These criteria ensure reliable, maintainable tests.

Literal Expected Values

  • Use hardcoded literal values in assertions
  • Calculate expected values independently from the implementation
  • If the implementation has a bug, the test catches it through independent verification
  • If expected value equals mock return value unchanged, the test verifies nothing (no transformation occurred)

Result-Based Verification

  • Verify final results and observable outcomes
  • Assert on return values, output data, or system state changes
  • For mock verification, check that correct arguments were passed

Meaningful Assertions

  • Every test must include at least one assertion
  • Assertions must validate observable behavior
  • A test without assertions always passes and provides no value

Appropriate Mock Scope

  • Mock direct external I/O dependencies: databases, HTTP clients, file systems
  • Use real implementations for internal utilities and business logic
  • Over-mocking reduces test value by verifying wiring instead of behavior

Boundary Value Testing

Test at boundaries of valid input ranges:

  • Minimum valid value
  • Maximum valid value
  • Just below minimum (invalid)
  • Just above maximum (invalid)
  • Empty input (where applicable)

Test Independence Verification

Each test must:

  • Create its own test data
  • Not depend on execution order
  • Clean up its own state
  • Pass when run in isolation

Verification Requirements

Before Commit

  • ✓ All tests pass — fix failing tests immediately
  • ✓ No tests skipped or commented — delete or fix
  • ✓ No debug code left in tests
  • ✓ Test coverage meets standards
  • ✓ No flaky tests — make deterministic
  • ✓ Tests run within performance thresholds

Test Organization

File Structure

  • Mirror production structure: Tests follow code organization
  • Clear naming conventions: Follow project's test file patterns
    • Examples: UserService.test.*, user_service_test.*, test_user_service.*, UserServiceTests.*
  • Logical grouping: Group related tests together
  • Separate test types: Unit, integration, e2e in separate directories

Performance Considerations

Test Speed

  • Unit tests: < 100ms each
  • Integration tests: < 1s each
  • Full suite: Should run frequently (< 10 minutes)

Optimization Strategies

  • Run tests in parallel when possible
  • Use in-memory databases for tests
  • Mock expensive operations
  • Split slow test suites
  • Profile and optimize slow tests

Continuous Integration

CI/CD Requirements

  • Run full test suite on every commit
  • Block merges if tests fail
  • Run tests in isolated environments
  • Test on target platforms/versions

Test Reports

  • Generate coverage reports
  • Track test execution time
  • Identify flaky tests
  • Monitor test trends

Test Design Guardrails

Every Test Must

  • Include at least one meaningful assertion
  • Create its own test data and clean up its own state
  • Pass when run in any order and in isolation
  • Test observable behavior through public interfaces
  • Keep test logic simple (no branching, no loops)
  • Mock only external I/O boundaries, use real implementations for internal logic

Flaky Test Resolution

  • Use deterministic time mocking instead of real clocks
  • Use fixed seed values instead of random data
  • Ensure proper resource cleanup in teardown
  • Resolve race conditions with synchronization primitives

Regression Testing

Prevent Regressions

  • Add test for every bug fix
  • Maintain comprehensive test suite
  • Run full suite regularly
  • Keep all tests unless the tested functionality is removed

Legacy Code

  • Add characterization tests before refactoring
  • Test existing behavior first
  • Gradually improve coverage
  • Refactor with confidence

Testing Best Practices by Language Paradigm

Type System Utilization

For languages with static type systems:

  • Leverage compile-time verification for correctness
  • Focus tests on business logic and runtime behavior
  • Use language's type system to prevent invalid states

For languages with dynamic typing:

  • Add comprehensive runtime validation tests
  • Explicitly test data contract validation
  • Consider property-based testing for broader coverage

Programming Paradigm Considerations

Functional approach:

  • Test pure functions thoroughly (deterministic, no side effects)
  • Test side effects at system boundaries
  • Leverage property-based testing for invariants

Object-oriented approach:

  • Test behavior through public interfaces
  • Mock dependencies via abstraction layers
  • Test polymorphic behavior carefully

Common principle: Adapt testing strategy to leverage language strengths while ensuring comprehensive coverage

Documentation and Communication

Tests as Documentation

  • Tests document expected behavior
  • Use clear, descriptive test names
  • Include examples of usage
  • Show edge cases and error handling

Test Failure Messages

  • Provide clear, actionable error messages
  • Include actual vs expected values
  • Add context about what was being tested
  • Make debugging easier
提供React/TypeScript前端开发规范,涵盖类型安全、组件设计、状态管理及错误处理。指导编写无技术债务的代码,强调使用unknown替代any、合理设计Props及遵循YAGNI原则。
实现React组件 编写TypeScript代码 前端功能开发
dev-workflows-frontend/skills/typescript-rules/SKILL.md
npx skills add shinpr/claude-code-workflows --skill typescript-rules -g -y
SKILL.md
Frontmatter
{
    "name": "typescript-rules",
    "description": "React\/TypeScript frontend development rules including type safety, component design, state management, and error handling. Use when implementing React components, TypeScript code, or frontend features."
}

TypeScript Development Rules (Frontend)

Basic Principles

  • Aggressive Refactoring - Prevent technical debt and maintain health
  • Delete code when no current caller exists - YAGNI principle (Kent Beck)

Comment Writing Rules

Code first: names and types carry meaning; a comment must add what code cannot, and one comment per decision is enough. Frontend specifics:

  • Comment intent, not markup: explain why a component memoizes, guards, or re-renders — not what the JSX renders
  • Timeless content only: Record decisions and rationale; leave chronological history to version control

Type Safety

Absolute Rule: Replace every any with unknown, generics, or union types. any disables type checking and causes runtime errors.

any Type Alternatives (Priority Order)

  1. unknown Type + Type Guards: Use for validating external input (API responses, localStorage, URL parameters)
  2. Generics: When type flexibility is needed
  3. Union Types・Intersection Types: Combinations of multiple types
  4. Type Assertions (Last Resort): Only when type is certain

Type Guard Implementation Pattern

function isUser(value: unknown): value is User {
  return typeof value === 'object' && value !== null && 'id' in value && 'name' in value
}

Modern Type Features

  • satisfies Operator: const config = { apiUrl: '/api' } satisfies Config - Preserves inference
  • const Assertion: const ROUTES = { HOME: '/' } as const satisfies Routes - Immutable and type-safe
  • Branded Types: type UserId = string & { __brand: 'UserId' } - Distinguish meaning
  • Template Literal Types: type EventName = \on${Capitalize}`` - Express string patterns with types

Type Safety in Frontend Implementation

  • React Props/State: TypeScript manages types, unknown unnecessary
  • External API Responses: Always receive as unknown, validate with type guards
  • localStorage/sessionStorage: Treat as unknown, validate
  • URL Parameters: Treat as unknown, validate
  • Form Input (Controlled Components): Type-safe with React synthetic events

Type Safety in Data Flow

  • Frontend → Backend: Props/State (Type Guaranteed) → API Request (Serialization)
  • Backend → Frontend: API Response (unknown) → Type Guard → State (Type Guaranteed)

Type Complexity Management

  • Props Design:
    • Props count: 3-7 props ideal (consider component splitting if exceeds 10)
    • Optional Props: 50% or less (consider default values or Context if excessive)
    • Nesting: Up to 2 levels (flatten deeper structures)
  • Type Assertions: Review design if used 3+ times
  • External API Types: Relax constraints and define according to reality (convert appropriately internally)

Coding Conventions

Component Design Criteria

  • Function components only: Official React recommendation, optimizable by modern tooling (Exception: Error Boundary requires class component)
  • Custom Hooks: Standard pattern for logic reuse and dependency injection
  • Component Hierarchy: Use the project's adopted component architecture. When the project uses Atomic Design: Atoms → Molecules → Organisms → Templates → Pages. When the project uses Feature-based, Container-Presenter, or another structure: follow that structure consistently and document the chosen layering in the project README or design doc
  • Co-location: Place tests, styles, and related files alongside components

Server/Client Boundary (RSC frameworks only — e.g., Next.js App Router)

  • Default to server components for data fetching and rendering; isolate interactivity behind a "use client" boundary at the smallest scope that needs it
  • Keep browser-only APIs (window, localStorage, event handlers) inside client components; calling them in a server component breaks the render
  • N/A for client-only SPAs (e.g., Vite) — skip when the project has no server-component runtime

State Management Patterns

  • Local State: useState for component-specific state
  • Context API: For sharing state across component tree (theme, auth, etc.)
  • Custom Hooks: Encapsulate state logic and side effects
  • Server State: React Query or SWR for API data caching

Data Flow Principles

  • Single Source of Truth: Each piece of state has one authoritative source
  • Unidirectional Flow: Data flows top-down via props
  • Immutable Updates: Use immutable patterns for state updates
// Immutable state update — always create new arrays/objects
setUsers(prev => [...prev, newUser])

Function Design

  • 0-2 parameters maximum: Use object for 3+ parameters
    function createUser({ name, email, role }: CreateUserParams) {}
    

Props Design (Props-driven Approach)

  • Props are the interface: Define all necessary information as props
  • Pass all data dependencies as props; use Context only for cross-cutting concerns (theme, auth, locale)
  • Type-safe: Always define Props type explicitly

Environment Variables

  • Use the build tool's env accessor: read client-side env through the bundler's exposed accessor — Vite via import.meta.env, Next.js/CRA via prefixed process.env. Raw, unprefixed access is undefined in the browser bundle
  • Only prefixed vars reach the client: build tools expose only vars carrying their public prefix; an unprefixed var is undefined in the browser. The prefix differs per tool — match the project's bundler (Vite VITE_, Next.js public NEXT_PUBLIC_, CRA REACT_APP_)
  • Centrally manage env through a typed config object with a default for every variable
// Client-exposed env must carry the bundler's public prefix, or it is undefined in the browser.
// Vite:    import.meta.env.VITE_API_URL
// Next.js: process.env.NEXT_PUBLIC_API_URL
const config = {
  apiUrl: import.meta.env.VITE_API_URL || 'http://localhost:3000', // adjust accessor + prefix to the project's bundler
  appName: import.meta.env.VITE_APP_NAME || 'My App'
}

Security (Client-side Constraints)

  • CRITICAL: All frontend code is public and visible in browser
  • All secrets stay server-side: Store API keys, tokens, and secrets on the backend only
  • Exclude .env files via .gitignore
  • Limit error messages to non-sensitive context
// Backend manages secrets, frontend accesses via proxy
const response = await fetch('/api/data') // Backend handles API key authentication

Dependency Injection

  • Custom Hooks for dependency injection: Ensure testability and modularity

Asynchronous Processing

  • Promise Handling: Always use async/await
  • Error Handling: Always handle with try-catch or Error Boundary
  • Type Definition: Explicitly define return value types (e.g., Promise<Result>)
  • Effect race/cleanup: guard useEffect data fetches against out-of-order responses and post-unmount state updates — abort or ignore stale results (AbortController or a mounted flag), or use a server-state library (React Query/SWR) that cancels and dedupes. try-catch alone does not cover this

Format Rules

  • Semicolon omission (follow Biome settings)
  • Types in PascalCase, variables/functions in camelCase
  • Imports use absolute paths (src/)

Clean Code Principles

  • Delete unused code immediately
  • Delete debug console.log()
  • Delete commented-out code (retrieve from version control when needed)
  • Comments explain "why" (not "what")

Error Handling

Absolute Rule: Every caught error must be logged with context and either re-thrown to Error Boundary, returned as a Result error variant, or displayed as user-facing error state.

Fail-Fast Principle: Fail quickly on errors to prevent continued processing in invalid states

catch (error) {
  logger.error('Processing failed', error)
  throw error // Handle with Error Boundary or higher layer
}

Result Type Pattern: Express errors with types for explicit handling

type Result<T, E> = { ok: true; value: T } | { ok: false; error: E }

// Example: Express error possibility with types
function parseUser(data: unknown): Result<User, ValidationError> {
  if (!isValid(data)) return { ok: false, error: new ValidationError() }
  return { ok: true, value: data as User }
}

Custom Error Classes

export class AppError extends Error {
  constructor(message: string, public readonly code: string, public readonly statusCode = 500) {
    super(message)
    this.name = this.constructor.name
  }
}
// Purpose-specific: ValidationError(400), ApiError(502), NotFoundError(404)

Layer-Specific Error Handling (React)

  • Error Boundary: Catch React component errors, display fallback UI
  • Custom Hook: Detect business rule violations, propagate AppError as-is
  • API Layer: Convert fetch errors to domain errors

Structured Logging and Sensitive Information Protection Redact sensitive fields (password, token, apiKey, secret, creditCard) before logging

Asynchronous Error Handling in React

  • Error Boundary setup mandatory: Catch rendering errors
  • Use try-catch with all async/await in event handlers
  • Always log and re-throw errors or display error state

Refactoring Techniques

Basic Policy

  • Small Steps: Maintain always-working state through gradual improvements
  • Safe Changes: Minimize the scope of changes at once
  • Behavior Guarantee: Ensure existing behavior remains unchanged while proceeding

Implementation Procedure: Understand Current State → Gradual Changes → Behavior Verification → Final Validation

Priority: Duplicate Code Removal > Large Function Division > Complex Conditional Branch Simplification > Type Safety Improvement

Performance Optimization

  • Automatic memoization: when React Compiler is enabled, rely on it; reach for manual React.memo/useMemo/useCallback only as a profiler- or identity-justified escape hatch (a measured bottleneck, or stable reference identity for third-party APIs / effect dependencies)
  • State Optimization: Minimize re-renders with proper state structure
  • Lazy Loading: Use React.lazy and Suspense for code splitting
  • Bundle Size: Monitor via the build script against the project's budget

Non-functional Requirements

  • Browser Compatibility: Chrome/Firefox/Safari/Edge (latest 2 versions)
  • Rendering Time: Within 5 seconds for major pages
提供技术决策标准、反模式检测及故障快速回退设计原则。用于识别代码异味、避免技术债务,确保错误可见性与可追溯性,指导高质量代码开发与质量保障工作流。
进行技术架构或方案决策时 检测代码异味或潜在反模式 执行代码质量保证与审查 设计错误处理与容错机制
dev-workflows-fullstack/skills/ai-development-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill ai-development-guide -g -y
SKILL.md
Frontmatter
{
    "name": "ai-development-guide",
    "description": "Technical decision criteria, anti-pattern detection, debugging techniques, and quality check workflow. Use when making technical decisions, detecting code smells, or performing quality assurance."
}

AI Developer Guide - Technical Decision Criteria and Anti-pattern Collection

Technical Anti-patterns (Red Flag Patterns)

Immediately stop and reconsider design when detecting the following patterns:

Code Quality Anti-patterns

  1. Writing similar code 3 or more times - Violates Rule of Three
  2. Multiple responsibilities mixed in a single file - Violates Single Responsibility Principle (SRP)
  3. Defining same content in multiple files - Violates DRY principle
  4. Making changes without checking dependencies - Potential for unexpected impacts
  5. Disabling code with comments - Should use version control
  6. Error suppression - Hiding problems creates technical debt
  7. Bypassing safety mechanisms (type systems, validation, contracts) - Circumventing language's correctness guarantees

Design Anti-patterns

  • "Make it work for now" thinking - Accumulation of technical debt
  • Patchwork implementation - Unplanned additions to existing code
  • Optimistic implementation of uncertain technology - Designing unknown elements assuming "it'll probably work"
  • Symptomatic fixes - Surface-level fixes that don't solve root causes
  • Unplanned large-scale changes - Lack of incremental approach

Fail-Fast Fallback Design Principles

Core Principle

Make all errors visible and traceable with full context. Prioritize primary code reliability over fallback implementations. Excessive fallback mechanisms mask errors and make debugging difficult.

Implementation Guidelines

Default Approach

  • Propagate all errors explicitly unless a Design Doc specifies a fallback
  • Make failures explicit: Errors should be visible and traceable
  • Preserve error context: Include original error information when re-throwing

When Fallbacks Are Acceptable

  • Only with explicit Design Doc approval: Document why fallback is necessary
  • Business-critical continuity: When partial functionality is better than none
  • Graceful degradation paths: Clearly defined degraded service levels

Layer Responsibilities

  • Infrastructure Layer:

    • Always throw errors upward
    • No business logic decisions
    • Provide detailed error context
  • Application Layer:

    • Make business-driven error handling decisions
    • Implement fallbacks only when specified in requirements
    • Log all fallback activations for monitoring

Error Masking Detection

Review Triggers (require design review):

  • Writing 3rd error handler in the same feature
  • Multiple error handling blocks in single function/method
  • Nested error handling structures
  • Error handlers that return default values without logging

Before Implementing Any Fallback:

  1. Verify Design Doc explicitly defines this fallback
  2. Document the business justification
  3. Ensure error is logged with full context
  4. Add monitoring/alerting for fallback activation

Implementation Pattern

AVOID: Silent fallback that hides errors
    <handle error>:
        return DEFAULT_VALUE  // Error hidden, debugging impossible

PREFERRED: Explicit failure with context
    <handle error>:
        log_error('Operation failed', context, error)
        <propagate error>  // Re-throw exception, return Error, return error tuple

Adaptation: Use language-appropriate error handling (exceptions, Result types, error tuples, etc.)

Rule of Three - Criteria for Code Duplication

How to handle duplicate code based on Martin Fowler's "Refactoring":

Duplication Count Action Reason
1st time Inline implementation Cannot predict future changes
2nd time Consider future consolidation Pattern beginning to emerge
3rd time Implement commonalization Pattern established

Criteria for Commonalization

Cases for Commonalization

  • Business logic duplication
  • Complex processing algorithms
  • Areas likely requiring bulk changes
  • Validation rules

Cases to Avoid Commonalization

  • Accidental matches (coincidentally same code)
  • Possibility of evolving in different directions
  • Significant readability decrease from commonalization
  • Simple helpers in test code

Common Failure Patterns and Avoidance Methods

Pattern 1: Error Fix Chain

Symptom: Fixing one error causes new errors Cause: Surface-level fixes without understanding root cause Avoidance: Identify root cause with 5 Whys before fixing

Pattern 2: Circumventing Correctness Guarantees

Symptom: Bypassing safety mechanisms (type systems, validation, contracts) Cause: Impulse to avoid correctness errors Avoidance: Use language-appropriate safety mechanisms (static checking, runtime validation, contracts, assertions)

Pattern 3: Implementation Without Sufficient Testing

Symptom: Many bugs after implementation Cause: Ignoring Red-Green-Refactor process Avoidance: Always start with failing tests

Pattern 4: Ignoring Technical Uncertainty

Symptom: Frequent unexpected errors when introducing new technology Cause: Assuming "it should work according to official documentation" without prior investigation Avoidance:

  • Record certainty evaluation at the beginning of task files
    Certainty: low (Reason: no working examples found for this integration)
    Exploratory implementation: true
    Fallback: use established alternative approach
    
  • For low certainty cases, create minimal verification code first

Pattern 5: Insufficient Existing Code Investigation

Symptom: Duplicate implementations, architecture inconsistency, integration failures, adopting outdated patterns Cause: Insufficient understanding of existing code before implementation; referencing only nearby files without verifying representativeness Avoidance Methods:

  • Before implementation, always search for similar functionality (using domain, responsibility, configuration patterns as keywords)
  • Similar functionality found → Use that implementation (do not create new implementation)
  • Similar functionality is technical debt → Create ADR improvement proposal before implementation
  • No similar functionality exists → Implement new functionality following existing design philosophy
  • Record all decisions and rationale in "Existing Codebase Analysis" section of Design Doc
  • Reference representativeness check: When adopting a pattern or dependency from nearby code, verify it is representative across the repository before adopting — nearby files alone are an insufficient basis

Debugging Techniques

1. Error Analysis Procedure

  1. Read error message (first line) accurately
  2. Focus on first and last of stack trace
  3. Identify first line where your code appears

2. 5 Whys - Root Cause Analysis

Trace the failure through repeated "why" questions until the root cause is actionable.

3. Minimal Reproduction Code

To isolate problems, attempt reproduction with minimal code:

  • Remove unrelated parts
  • Replace external dependencies with mocks
  • Create minimal configuration that reproduces problem

4. Debug Log Output

Include operation context, relevant input data, current state, and timestamp.

Quality Assurance Mechanism Awareness

Before executing quality checks, identify what quality mechanisms exist for the change area:

  • Primary detection: inspect the change area's file types, project manifest, and configuration to identify applicable quality tools
    • Check CI pipeline definitions for checks that cover the affected paths
    • Check for domain-specific linter or validator configurations (e.g., schema validators, API spec validators, configuration file linters)
    • Check for domain-specific constraints in project configuration (naming rules, length limits, format requirements)
  • Supplementary hint: IF task file specifies Quality Assurance Mechanisms → use them as additional hints for which domain-specific checks to look for
  • Include discovered domain-specific checks alongside standard quality phases below

Quality Check Workflow

Universal quality assurance phases applicable to all languages:

Phase 1: Static Analysis

  1. Code Style Checking: Verify adherence to style guidelines
  2. Code Formatting: Ensure consistent formatting
  3. Unused Code Detection: Identify dead code and unused imports/variables
  4. Static Type Checking: Verify type correctness (for statically typed languages)
  5. Static Analysis: Detect potential bugs, security issues, code smells

Phase 2: Build Verification

  1. Compilation/Build: Verify code builds successfully (for compiled languages)
  2. Dependency Resolution: Ensure all dependencies are available and compatible
  3. Resource Validation: Check configuration files, assets are valid

Phase 3: Testing

  1. Unit Tests: Run all unit tests
  2. Integration Tests: Run integration tests
  3. Test Coverage: Measure and verify coverage meets standards
  4. E2E Tests: Run end-to-end tests

Phase 4: Final Quality Gate

All checks must pass before proceeding:

  • Zero static analysis errors
  • Build succeeds
  • All tests pass
  • Coverage meets project-configured threshold

Quality Check Pattern (Language-Agnostic)

Workflow:
1. Format check → 2. Lint/Style → 3. Static analysis →
4. Build/Compile → 5. Unit tests → 6. Coverage check →
7. Integration tests → 8. Final gate

Auto-fix capabilities (when available):
- Format auto-fix
- Lint auto-fix
- Dependency/import organization
- Simple code smell corrections

Situations Requiring Technical Decisions

Timing of Abstraction

  • Extract patterns after writing concrete implementation 3 times
  • Be conscious of YAGNI, implement only currently needed features
  • Prioritize current simplicity over future extensibility

Performance vs Readability

  • Prioritize readability unless profiling identifies a measurable bottleneck (e.g., response time exceeding SLA, memory exceeding allocation)
  • Measure before optimizing
  • Document reason with comments when optimizing

Granularity of Contracts and Interfaces

  • Overly detailed contracts reduce maintainability
  • Design interfaces where each method maps to a single domain operation and parameter types use domain vocabulary
  • Use abstraction mechanisms to reduce duplication

Scope Expansion

  • Apply implementation/edit instructions to the user's or task's specified scope. Escalate before expanding it.
  • Treat explicit quantities and targets ("one", "this file", "only X") as boundaries
  • Copy/move/mirror requests preserve content verbatim; edit content only when requested
  • Port/translation requests preserve intent and behavior; adapt only what the destination context requires
  • Before changing related files, symmetric locations, adjacent behavior, or adding helpful extras, escalate with the proposed expansion

Implementation Completeness Assurance

Impact Analysis: Mandatory 3-Stage Process

Complete these stages sequentially before any implementation:

1. Discovery - Identify all affected code:

  • Implementation references (imports, calls, instantiations)
  • Interface dependencies (contracts, types, data structures)
  • Test coverage
  • Configuration (build configs, env settings, feature flags)
  • Documentation (comments, docs, diagrams)

2. Understanding - Analyze each discovered location:

  • Role and purpose in the system
  • Dependency direction (consumer or provider)
  • Data flow (origin → transformations → destination)
  • Coupling strength

3. Identification - Produce structured report:

## Impact Analysis
### Direct Impact
- [Unit]: [Reason and modification needed]

### Indirect Impact
- [System]: [Integration path → reason]

### Data Flow
[Source] → [Transformation] → [Consumer]

### Risk Assessment
- High: [Complex dependencies, fragile areas]
- Medium: [Moderate coupling, test gaps]
- Low: [Isolated, well-tested areas]

### Implementation Order
1. [Start with lowest risk or deepest dependency]
2. [...]

Critical: Do not implement until all 3 stages are documented

Unused Code Deletion

When unused code is detected:

  • Will it be used in this work? Yes → Implement now | No → Delete now (Git preserves)
  • Applies to: Code, tests, docs, configs, assets

Existing Code Modification

In use? No → Delete
       Yes → Working? No → Delete + Reimplement
                     Yes → Fix/Extend

Principle: Prefer clean implementation over patching broken code

提供语言无关的编码原则,强调可维护性、简洁性和代码质量。适用于功能实现、重构和代码审查,指导命名、函数设计、错误处理及持续改进。
实现新功能 重构现有代码 进行代码质量审查
dev-workflows-fullstack/skills/coding-principles/SKILL.md
npx skills add shinpr/claude-code-workflows --skill coding-principles -g -y
SKILL.md
Frontmatter
{
    "name": "coding-principles",
    "description": "Language-agnostic coding principles for maintainability, readability, and quality. Use when implementing features, refactoring code, or reviewing code quality."
}

Language-Agnostic Coding Principles

Core Philosophy

  1. Maintainability over Speed: Prioritize long-term code health over initial development velocity
  2. Simplicity First: Choose the simplest solution that meets requirements (YAGNI principle)
  3. Minimum Surface for Required Coverage: When introducing maintenance-surface-bearing elements (persistent state, public-contract or cross-boundary fields/props, behavioral modes/flags/variants, reusable abstractions, or component splits), select the smallest design surface that covers the current user-visible requirements and accepted technical constraints (audit, data integrity, compatibility, security, performance, accessibility). Adoption is justified by naming a current requirement or constraint that smaller alternatives fail to cover; value-based arguments serve as tiebreakers. Distinct from YAGNI (time-axis judgment of present vs. future need), this principle governs surface-area minimization at a fixed coverage point.
  4. Explicit over Implicit: Make intentions clear through code structure and naming
  5. Delete over Comment: Remove unused code instead of commenting it out

Code Quality

Continuous Improvement

  • Refactor related code within each change set — address style, naming, or structure issues in the files being modified
  • Improve code structure incrementally
  • Keep the codebase lean and focused
  • Delete unused code immediately

Readability

  • Use meaningful, descriptive names drawn from the problem domain
  • Use full words in names; abbreviations are acceptable only when widely recognized in the domain
  • Use descriptive names; single-letter names are acceptable only for loop counters or well-known conventions (i, j, x, y)
  • Extract magic numbers and strings into named constants
  • Keep code self-documenting where possible

Function Design

Parameter Management

  • Recommended: 0-2 parameters per function
  • For 3+ parameters: Use objects, structs, or dictionaries to group related parameters
  • Example (conceptual):
    // Instead of: createUser(name, email, age, city, country)
    // Use: createUser(userData)
    

Single Responsibility

  • Each function should do one thing well
  • Keep functions small and focused (typically < 50 lines)
  • Extract complex logic into separate, well-named functions
  • Functions should have a single level of abstraction

Function Organization

  • Pure functions when possible (no side effects)
  • Separate data transformation from side effects
  • Use early returns to reduce nesting
  • Keep nesting to a maximum of 3 levels; use early returns or extracted functions to flatten deeper nesting

Error Handling

Error Management Principles

  • Always handle errors: Log with context or propagate explicitly
  • Log appropriately: Include context for debugging
  • Protect sensitive data: Mask or exclude passwords, tokens, PII from logs
  • Fail fast: Detect and report errors as early as possible

Error Propagation

  • Use language-appropriate error handling mechanisms
  • Propagate errors to appropriate handling levels
  • Provide meaningful error messages
  • Include error context when re-throwing

Dependency Management

Loose Coupling via Parameterized Dependencies

  • Inject external dependencies as parameters (constructor injection for classes, function parameters for procedural/functional code)
  • Depend on abstractions, not concrete implementations
  • Minimize inter-module dependencies
  • Facilitate testing through mockable dependencies

Reference Representativeness

Verifying References Before Adoption

When adopting patterns, APIs, or dependencies from existing code:

  • IF referencing only 2-3 nearby files → THEN confirm the pattern is representative by checking usage across the repository before adopting
  • IF multiple approaches coexist in the repository → THEN identify the majority pattern and make a deliberate choice — selecting whichever is nearest is insufficient
  • IF adopting an external dependency (library, plugin, SDK) → THEN verify repository-wide usage distribution for the same dependency; if the appropriate version cannot be determined from repository state alone, escalate
  • IF following an existing pattern → THEN state the reason for following it when an alternative exists (e.g., consistency with surrounding code, avoiding breaking changes, pending coordinated update)

Principle

Nearby code is a starting point for investigation, not a sufficient basis for adoption. Verify that what you reference is representative of the repository's conventions and current best practices before using it as a model.

Performance Considerations

Optimization Approach

  • Measure first: Profile before optimizing
  • Focus on algorithms: Algorithmic complexity > micro-optimizations
  • Use appropriate data structures: Choose based on access patterns
  • Resource management: Handle memory, connections, and files properly

When to Optimize

  • After identifying actual bottlenecks through profiling
  • When performance issues are measurable
  • Optimize only after measurable bottlenecks are identified, not during initial development

Code Organization

Structural Principles

  • Group related functionality: Keep related code together
  • Separate concerns: Domain logic, data access, presentation
  • Consistent naming: Follow project conventions
  • Module cohesion: High cohesion within modules, low coupling between

File Organization

  • One primary responsibility per file
  • Logical grouping of related functions/classes
  • Clear folder structure reflecting architecture
  • Avoid "god files" (files > 500 lines)

Commenting Principles

Default: code first

Names, types, and structure are the primary medium. A comment earns its place only by carrying information the code itself cannot express. When in doubt, improve the name instead of adding a comment.

The test for every comment

A comment is justified only if it answers one of these:

  • Why: reasoning, trade-off, or constraint behind a non-obvious decision
  • Limitation / edge case: a boundary a reader cannot infer from the code
  • Public API contract: behavior, inputs, outputs of an exported interface

One comment per decision. If a comment restates what the names and control flow already show, delete it and rename instead.

Comment Scope

  • Comment the why, limits, and public contracts (per the test above); let names and structure carry everything else, including the "how"
  • Record historical context in version control commit messages, not in comments
  • Delete commented-out code (retrieve from git history when needed)

Comment Quality

  • Write comments that remain accurate regardless of future code changes; avoid references to dates, versions, or temporary state
  • Update comments when changing code
  • Use proper grammar and formatting
  • Write for future maintainers

Refactoring Approach

Safe Refactoring

  • Small steps: Make one change at a time
  • Maintain working state: Keep tests passing
  • Verify behavior: Run tests after each change
  • Incremental improvement: Don't aim for perfection immediately

Refactoring Triggers

  • Code duplication (DRY principle)
  • Functions > 50 lines
  • Complex conditional logic
  • Unclear naming or structure

Testing Considerations

Testability

  • Write testable code from the start
  • Avoid hidden dependencies
  • Keep side effects explicit
  • Design for parameterized dependencies

Test-Driven Development

  • Write tests before implementation when appropriate
  • Keep tests simple and focused
  • Test behavior, not implementation
  • Maintain test quality equal to production code

Security Principles

Secure Defaults

  • Store credentials and secrets through environment variables or dedicated secret managers
  • Use parameterized queries (prepared statements) for all database access
  • Use established cryptographic libraries provided by the language or framework
  • Generate security-critical values (tokens, IDs, nonces) with cryptographically secure random generators
  • Encrypt sensitive data at rest and in transit using standard protocols

Input and Output Boundaries

  • Validate all external input at system entry points for expected format, type, and length
  • Encode output appropriately for its rendering context (HTML, SQL, shell, URL)
  • Return only information necessary for the caller in error responses; log detailed diagnostics server-side

Access Control

  • Apply authentication to all entry points that handle user data or trigger state changes
  • Verify authorization for each resource access, not only at the entry point
  • Grant only the permissions required for the operation (files, database connections, API scopes)

Knowledge Cutoff Supplement (2026-03)

  • OWASP Top 10:2025 shifted from symptoms to root causes; added "Software Supply Chain Failures" (A03) and "Mishandling of Exceptional Conditions" (A10)
  • Recent research indicates AI-generated code shows elevated rates of access control gaps — treat authentication and authorization as high-priority review targets
  • OpenSSF published "Security-Focused Guide for AI Code Assistant Instructions" — recommends language-specific, actionable constraints over generic advice
  • For detailed detection patterns, see references/security-checks.md

Documentation

Code Documentation

  • Document public APIs and interfaces
  • Include usage examples for complex functionality
  • Maintain README files for modules
  • Update documentation in the same commit that changes the corresponding behavior

Architecture Documentation

  • Document high-level design decisions
  • Explain integration points
  • Clarify data flows and boundaries
  • Record trade-offs and alternatives considered

Version Control Practices

Commit Practices

  • Make atomic, focused commits
  • Write clear, descriptive commit messages
  • Commit working code (passes tests)
  • Commit only production-ready code; store secrets in environment variables or secret managers

Code Review Readiness

  • Self-review before requesting review
  • Keep changes focused and reviewable
  • Provide context in pull request descriptions
  • Respond to feedback constructively

Language-Specific Adaptations

While these principles are language-agnostic, adapt them to your specific programming language:

  • Static typing: Use strong types when available
  • Dynamic typing: Add runtime validation
  • OOP languages: Apply SOLID principles
  • Functional languages: Prefer pure functions and immutability
  • Concurrency: Follow language-specific patterns for thread safety
提供PRD、ADR、设计文档等模板及创建标准。通过决策矩阵根据变更类型和文件数量确定所需文档,并定义ADR触发条件(如契约或架构变更),指导技术文档的规范创建与审查。
需要创建或审查PRD、ADR、设计文档等工作计划 判断特定代码变更是否需要生成架构决策记录(ADR) 根据项目复杂度确定技术文档的最小必要集合
dev-workflows-fullstack/skills/documentation-criteria/SKILL.md
npx skills add shinpr/claude-code-workflows --skill documentation-criteria -g -y
SKILL.md
Frontmatter
{
    "name": "documentation-criteria",
    "description": "Documentation creation criteria including PRD, ADR, Design Doc, and Work Plan requirements with templates. Use when creating or reviewing technical documents, or determining which documents are required."
}

Documentation Creation Criteria

Templates

Creation Decision Matrix

Condition Required Documents Creation Order
New Feature Addition (backend) PRD → [ADR] → Design Doc → Work Plan After PRD approval
New Feature Addition (frontend/fullstack) PRD → UI Spec → [ADR] → Design Doc → Work Plan UI Spec before Design Doc
ADR Conditions Met (see below) ADR → Design Doc → Work Plan Start immediately
6+ Files [ADR if conditions apply] → Design Doc → Work Plan (Design Doc + Work Plan required) Start immediately
3-5 Files Design Doc → Work Plan (Required) Start immediately
1-2 Files None Direct implementation

ADR Creation Conditions (Required if Any Apply)

1. Contract System Changes

  • Adding nested contracts with 3+ levels: Contract A { Contract B { Contract C { field: T } } }
    • Rationale: Deep nesting has high complexity and wide impact scope
  • Changing/deleting contracts used in 3+ locations
    • Rationale: Multiple location impacts require careful consideration
  • Contract responsibility changes (e.g., DTO→Entity, Request→Domain)
    • Rationale: Conceptual model changes affect design philosophy

2. Data Flow Changes

  • Storage location changes (DB→File, Memory→Cache)
  • Processing order changes with 3+ steps
    • Example: "Input→Validation→Save" to "Input→Save→Async Validation"
  • Data passing method changes (parameter passing→shared state, direct reference→event-based communication)

3. Architecture Changes

  • Layer addition, responsibility changes, component relocation

4. External Dependency Changes

  • Library/framework/external API introduction or replacement

5. Complex Implementation Logic (Regardless of Scale)

  • Managing 3+ states
  • Coordinating 5+ asynchronous processes

Detailed Document Definitions

PRD (Product Requirements Document)

Purpose: Define business requirements and user value

Includes:

  • Business requirements and user value
  • Success metrics and KPIs (each metric specifies a numeric target and measurement method)
  • User stories and use cases
  • MoSCoW prioritization (Must/Should/Could/Won't)
  • Acceptance criteria with sequential IDs (AC-001, AC-002, ...) for downstream traceability
  • MVP and Future phase separation
  • User journey diagram (required)
  • Scope boundary diagram (required)

Scope: Business requirements, user value, success metrics, user stories, and prioritization only. Implementation details belong in Design Doc, technical selection rationale in ADR, phases and task breakdown in Work Plan.

ADR (Architecture Decision Record)

Purpose: Record technical decision rationale and background

Includes:

  • Decision (what was selected)
  • Rationale (why that selection was made)
  • Option comparison (minimum 3 options) and trade-offs
  • Architecture impact
  • Principled implementation guidelines (e.g., "Use dependency injection")

Scope: Decision, rationale, option comparison, architecture impact, and principled guidelines only. Implementation procedures and code examples belong in Design Doc, schedule and resource assignments in Work Plan.

UI Specification

Purpose: Define UI structure, screen transitions, component decomposition, and interaction design for frontend features

Includes:

  • Screen list and transition conditions
  • Component decomposition with state x display matrix (default/loading/empty/error/partial)
  • Interaction definitions linked to PRD acceptance criteria (EARS format)
  • Prototype management (code-based prototypes as attachments, not source of truth)
  • AC traceability from PRD to screens/components
  • Existing component reuse map and design tokens
  • Visual acceptance criteria (golden states, layout constraints)
  • Accessibility requirements (keyboard, screen reader, contrast)

Scope: Screen structure, transitions, component decomposition, interaction design, and visual acceptance criteria only. Technical implementation and API contracts belong in Design Doc, test implementation in test skeleton generation output, schedule in Work Plan.

Required Structural Elements:

  • At least one component with state x display matrix and interaction table
  • AC traceability table mapping PRD ACs to screens/states
  • Screen list with transition conditions
  • Existing component reuse map (reuse/extend/new decisions)

Prototype Code Handling:

  • Prototype code provided by user is placed in docs/ui-spec/assets/{feature-name}/
  • Prototype is an attachment to UI Spec, never the source of truth
  • UI Spec + Design Doc are the canonical specifications

Design Document

Purpose: Define technical implementation methods in detail

Includes:

  • Existing codebase analysis (required)
    • Implementation path mapping (both existing and new)
    • Integration point clarification (connection points with existing code even for new implementations)
  • Technical implementation approach (vertical/horizontal/hybrid)
  • Technical dependencies and implementation constraints (required implementation order)
  • Interface and contract definitions
  • Data flow and component design
  • Acceptance criteria (each criterion specifies a verifiable condition with pass/fail threshold)
  • Change impact map (clearly specify direct impact/indirect impact/no ripple effect)
  • Complete enumeration of integration points
  • Data contract clarification
  • Agreement checklist (agreements with stakeholders)
  • Code inspection evidence (inspected files/functions during investigation)
  • Field propagation map (when fields cross component boundaries)
  • Data representation decision (when introducing new structures)
  • Applicable standards (explicit/implicit classification)
  • Prerequisite ADRs (including common ADRs)
  • Verification Strategy (required)
    • Correctness proof method (what "correct" means for this change, how it's verified, when)
    • Early verification point (first target to prove the approach works, success criteria, failure response)

Required Structural Elements:

Change Impact Map:
  Change Target: [Component/Feature]
  Direct Impact: [Files/Functions]
  Indirect Impact: [Data format/Processing time]
  No Ripple Effect: [Unaffected features]

Interface Change Matrix:
  Existing: [Function/method/operation name]
  New: [Function/method/operation name]
  Conversion Required: [Yes/No]
  Compatibility Method: [Approach]

Scope: Technical implementation methods, interfaces, data flow, acceptance criteria, and verification strategy only. Technology selection rationale belongs in ADR, schedule and assignments in Work Plan.

Work Plan

Purpose: Implementation task management and progress tracking

Includes:

  • Task breakdown and dependencies (maximum 2 levels)
  • Schedule and duration estimates
  • Include test skeleton file paths produced for this work plan (integration and E2E)
  • Verification Strategy summary (extracted from Design Doc)
  • Final Quality Assurance Phase (required)
  • Progress records (checkbox format)

Scope: Task breakdown, dependencies, schedule, verification strategy summary, and progress tracking only. Technical rationale belongs in ADR, design details in Design Doc.

Phase Division Criteria (adapt to implementation approach from Design Doc):

When Vertical Slice selected:

  • Each phase = one value unit (feature, component, or migration target)
  • Each phase includes its own implementation + verification per Verification Strategy

When Horizontal Slice selected:

  1. Phase 1: Foundation Implementation - Contract definitions, interfaces/signatures, test preparation
  2. Phase 2: Core Feature Implementation - Business logic, unit tests
  3. Phase 3: Integration Implementation - External connections, presentation layer

When Hybrid selected:

  • Combine vertical and horizontal as defined in Design Doc implementation approach

All approaches: Final phase is always Quality Assurance (acceptance criteria achievement, all tests passing, quality checks). Each phase's verification method follows Verification Strategy from Design Doc.

Three Elements of Task Completion Definition:

  1. Implementation Complete: Code is functional
  2. Quality Complete: Tests, static checks, linting pass
  3. Integration Complete: Verified connection with other components

Creation Process

  1. Problem Analysis: Change scale assessment, ADR condition check
    • Identify explicit and implicit project standards before investigation
  2. ADR Option Consideration (ADR only): Compare 3+ options, specify trade-offs
  3. Creation: Use templates, include measurable conditions
  4. Approval: "Accepted" after review enables implementation

Storage Locations

Document Path Naming Convention Template
PRD docs/prd/ [feature-name]-prd.md prd-template.md
ADR docs/adr/ ADR-[4-digits]-[title].md adr-template.md
UI Spec docs/ui-spec/ [feature-name]-ui-spec.md ui-spec-template.md
UI Spec Assets docs/ui-spec/assets/{feature-name}/ Prototype code files -
Design Doc docs/design/ [feature-name]-design.md design-template.md
Work Plan docs/plans/ YYYYMMDD-{type}-{description}.md plan-template.md
Task File docs/plans/tasks/ {plan-name}-task-{number}.md task-template.md

*Note: Work plans are excluded by .gitignore

ADR Status

ProposedAcceptedDeprecated/Superseded/Rejected

AI Automation Rules

  • 6+ files: Suggest ADR creation
  • Contract/data flow change detected: ADR mandatory
  • Check existing ADRs before implementation

Diagram Requirements

Required diagrams for each document (using mermaid notation):

Document Required Diagrams Purpose
PRD User journey diagram, Scope boundary diagram Clarify user experience and scope
ADR Option comparison diagram (when needed) Visualize trade-offs
UI Spec Screen transition diagram, Component tree diagram Clarify screen flow and component structure
Design Doc Architecture diagram, Data flow diagram Understand technical structure
Work Plan Phase structure diagram, Task dependency diagram Clarify implementation order

Common ADR Relationships

  1. At creation: Identify common technical areas (logging, error handling, async processing, etc.), reference existing common ADRs
  2. When missing: Consider creating necessary common ADRs
  3. Design Doc: Specify common ADRs in "Prerequisite ADRs" section
  4. Compliance check: Verify design aligns with common ADR decisions
捕获并持久化外部资源(如设计源、API、IaC等)的访问方式,确保下游工作可确定性获取。适用于依赖外部资源或提及特定资源类型的场景。
工作依赖外部资源 用户提及设计源、设计系统、API schema、IaC源或密钥存储
dev-workflows-fullstack/skills/external-resource-context/SKILL.md
npx skills add shinpr/claude-code-workflows --skill external-resource-context -g -y
SKILL.md
Frontmatter
{
    "name": "external-resource-context",
    "description": "Captures and persists access methods for resources outside the repository (design source, design system, API schema, IaC source, secret store) so downstream work can reach them deterministically. Use when work depends on external resources, or when the user mentions design source, design system, API schema, IaC source, secret store, or canonical source."
}

External Resource Context

Purpose

AI agents understand the codebase but not the external resources surrounding it. This skill captures, in a deterministic location, the access methods to resources outside the repository so downstream work (design, planning, implementation, review) can reach them without re-asking the user.

Resources covered: design origin (where the canonical visual specification lives), design system (component library and tokens), guidelines (usage docs, accessibility rules), visual verification environment (how to confirm rendering), database schema source, migration history, secret store location, API schema source (OpenAPI / proto / GraphQL SDL), mock environment, IaC source, environment configuration.

Scope Boundaries

In scope: hearing protocol, storage location, single-source-of-truth ownership rule, reference protocol for downstream consumers.

Out of scope: enforcing that captured resources are correct or current — verification belongs to the agent that consumes the resource. Generating the resources themselves (e.g., creating a DESIGN.md from scratch).

Storage Locations (Two-Tier)

Tier Location Holds Update Frequency
Project docs/project-context/external-resources.md Environment-stable facts: which resources exist for this project and how to access them (URL, MCP name, file path, command) Rare — only when the project's environment changes
Feature ## External Resources Used section inside the relevant UI Spec or Design Doc The subset of project-tier resources actually used by this feature, plus feature-specific identifiers (e.g., a specific node id within the design tool, a specific endpoint path) Per feature

Single Source of Truth Rule

The project tier owns environment facts. Feature-tier sections list only feature-specific identifiers (node id within the design source, specific endpoint path within the API, specific IaC module name) and reference project-tier entries by label; URLs, MCP names, and access commands remain in the project-tier file. When the environment changes, only the project-tier file is updated.

Example feature-tier entry uses the table format defined in references/template.md: a row with the project-tier label in the first column and the feature-specific identifier in the second column.

Hearing Protocol

When to Hear

Condition Action
docs/project-context/external-resources.md does not exist Run full hearing for the relevant domain(s)
File exists Ask the user via AskUserQuestion: "Update external-resources.md? (no / yes-full / yes-diff-only)". On yes-full run full hearing. On yes-diff-only ask the user which axes changed, hear only those. On no skip hearing

Domain Routing

Load the domain reference matching the current task:

Task type References to load
Frontend (UI work) references/frontend.md
Backend (server / data work) references/backend.md
API contract work references/api.md
Infrastructure / deployment references/infra.md
Fullstack All of the above; per-axis "Not applicable" answers are expected

Each domain reference defines the axes and the question template.

Two-Phase Hearing

  1. Structured hearing — for each axis defined in the domain reference, present the user with AskUserQuestion using the choices listed there (always include "Not applicable" as an option). For each non-N/A axis, follow up with an access-method question (URL / MCP name / file path / command).

  2. Self-declaration — after the structured axes, present a single AskUserQuestion: "Are there any other external resources for this work that the structured questions did not cover? If yes, describe them in your next message." If the user describes additional resources, append them to the storage file under an "Additional resources" subsection.

The two phases are sequential. Self-declaration runs even if the user answered "Not applicable" to every structured axis.

Storage Protocol

After hearing completes:

  1. Build the project-tier content from the answers. Use references/template.md as the structure.
  2. Write to docs/project-context/external-resources.md. Create the directory if absent.
  3. When the calling workflow has a target UI Spec or Design Doc, also append or update the document's ## External Resources Used section with the feature-tier subset (label references + feature-specific identifiers only).
  4. Report the file paths back to the calling workflow.

Reference Protocol (For Downstream Consumers)

Agents that load this skill consult resources in this order:

  1. Read docs/project-context/external-resources.md first (if present) to learn what is available and how to access it.
  2. Read the target UI Spec or Design Doc's ## External Resources Used section for feature-specific identifiers.
  3. Use the access method declared in the project tier (e.g., the named MCP, the URL, the file path) to fetch the actual resource content.

Agents that only need to consult the saved file as input data (not actively hear) can read it directly without loading this skill — frontmatter declaration is reserved for agents that may need to trigger hearing or interpret the protocol semantics.

Output Format

The project-tier file follows the structure in references/template.md. The project-tier file's heading levels and section names are fixed so downstream agents can locate sections deterministically.

For feature-tier sections inside UI Spec or Design Doc, the heading text "External Resources Used" is fixed; the heading level matches the parent document's natural structure (h2 in UI Spec where it is a sibling of other top-level sections, h3 in Design Doc where it sits under Background and Context).

Quality Checklist

  • Each axis answered has both a presence indicator and an access method, or is marked "Not applicable"
  • Self-declaration phase ran even when all structured axes were "Not applicable"
  • Project-tier file does not contain feature-specific identifiers
  • Feature-tier sections reference project-tier entries by label, not by duplicating URLs / MCP names
  • When the project file already existed, the update decision (no / yes-full / yes-diff-only) was confirmed before any write

References

提供前端技术决策标准、反模式识别及调试技巧。用于在做出前端技术选择或执行质量保证时,检测代码与设计中的不良实践,遵循失败快速原则和三次规则,确保代码质量与可维护性。
进行前端技术架构设计 审查前端代码质量 处理组件复用与重构决策 排查前端技术债务
dev-workflows-fullstack/skills/frontend-ai-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill frontend-ai-guide -g -y
SKILL.md
Frontmatter
{
    "name": "frontend-ai-guide",
    "description": "Frontend-specific technical decision criteria, anti-patterns, debugging techniques, and quality check workflow. Use when making frontend technical decisions or performing quality assurance."
}

AI Developer Guide - Technical Decision Criteria and Anti-pattern Collection (Frontend)

Technical Anti-patterns (Red Flag Patterns)

Immediately stop and reconsider design when detecting the following patterns:

Code Quality Anti-patterns

  1. Writing similar code 3 or more times - Violates Rule of Three
  2. Multiple responsibilities mixed in a single component - Violates Single Responsibility Principle (SRP)
  3. Defining same content in multiple components - Violates DRY principle
  4. Making changes without checking dependencies - Potential for unexpected impacts
  5. Disabling code with comments - Should use version control
  6. Error suppression - Hiding problems creates technical debt
  7. Excessive use of type assertions (as) - Abandoning type safety
  8. Prop drilling through 3+ levels - Should use Context API or state management
  9. Massive components (300+ lines) - Split into smaller components

Design Anti-patterns

  • "Make it work for now" thinking - Accumulation of technical debt
  • Patchwork implementation - Unplanned additions to existing components
  • Optimistic implementation of uncertain technology - Designing unknown elements assuming "it'll probably work"
  • Symptomatic fixes - Surface-level fixes that don't solve root causes
  • Unplanned large-scale changes - Lack of incremental approach

Fallback Design Principles

Core Principle: Fail-Fast

Design philosophy that prioritizes improving primary code reliability over fallback implementations.

Criteria for Fallback Implementation

  • Fallback rule: Implement fallbacks only when explicitly defined in Design Doc
  • Layer Responsibilities:
    • Component Layer: Use Error Boundary for error handling
    • Hook Layer: Implement decisions based on business requirements

Detection of Excessive Fallbacks

  • Require design review when writing the 3rd catch statement in the same feature
  • Verify Design Doc definition before implementing fallbacks
  • Properly log errors and make failures explicit

Rule of Three - Criteria for Code Duplication

How to handle duplicate code based on Martin Fowler's "Refactoring":

Duplication Count Action Reason
1st time Inline implementation Cannot predict future changes
2nd time Consider future consolidation Pattern beginning to emerge
3rd time Implement commonalization Pattern established

Criteria for Commonalization

Cases for Commonalization

  • Business logic duplication
  • Complex processing algorithms
  • Component patterns (form fields, cards, etc.)
  • Custom hooks
  • Validation rules

Cases to Avoid Commonalization

  • Accidental matches (coincidentally same code)
  • Possibility of evolving in different directions
  • Significant readability decrease from commonalization
  • Simple helpers in test code

Implementation Example

// 1st-2nd occurrence: keep separate, no commonalization yet
function UserEmailInput() { /* ... */ }
function ContactEmailInput() { /* ... */ }

// Commonalize on 3rd occurrence
function EmailInput({ context }: { context: 'user' | 'contact' | 'admin' }) { /* ... */ }

Common Failure Patterns and Avoidance Methods

Pattern 1: Error Fix Chain

Symptom: Fixing one error causes new errors Cause: Surface-level fixes without understanding root cause Avoidance: Identify root cause with 5 Whys before fixing

Pattern 2: Abandoning Type Safety

Symptom: Excessive use of any type or as Cause: Impulse to avoid type errors Avoidance: Handle safely with unknown type and type guards

Pattern 3: Implementation Without Sufficient Testing

Symptom: Many bugs after implementation Cause: Ignoring Red-Green-Refactor process Avoidance: Always start with failing tests

Pattern 4: Ignoring Technical Uncertainty

Symptom: Frequent unexpected errors when introducing new technology Cause: Assuming "it should work according to official documentation" without prior investigation Avoidance:

  • Record certainty evaluation at the beginning of task files
    Certainty: low (Reason: new experimental feature with limited production examples)
    Exploratory implementation: true
    Fallback: use established patterns
    
  • For low certainty cases, create minimal verification code first

Pattern 5: Insufficient Existing Code Investigation

Symptom: Duplicate implementations, architecture inconsistency, integration failures Cause: Insufficient understanding of existing code before implementation Avoidance Methods:

  • Before implementation, always search for similar functionality (using domain, responsibility, component patterns as keywords)
  • Similar functionality found → Use that implementation (do not create new implementation)
  • Similar functionality is technical debt → Create ADR improvement proposal before implementation
  • No similar functionality exists → Implement new functionality following existing design philosophy
  • Record all decisions and rationale in "Existing Codebase Analysis" section of Design Doc

Debugging Techniques

1. Error Analysis Procedure

  1. Read error message (first line) accurately
  2. Focus on first and last of stack trace
  3. Identify first line where your code appears
  4. Check React DevTools for component hierarchy

2. 5 Whys - Root Cause Analysis

Symptom: Component not rendering
Why1: Props are undefined → Why2: Parent component didn't pass props
Why3: Parent using old prop names → Why4: Component interface was updated
Why5: No update to parent after refactoring
Root cause: Incomplete refactoring, missing call-site updates

3. Minimal Reproduction Code

To isolate problems, attempt reproduction with minimal code:

  • Remove unrelated components
  • Replace API calls with mocks
  • Create minimal configuration that reproduces problem
  • Use React DevTools to inspect component tree

4. Debug Log Output (temporary)

Add structured debug logs to isolate the issue, then remove them before commit (per "Delete debug console.log()" in typescript-rules):

console.log('DEBUG:', {
  context: 'user-form-submission',
  props: { email, name },
  state: currentState,
  timestamp: new Date().toISOString()
})

Quality Check Workflow

Read package.json scripts and run them with the project's package manager (packageManager field). Map the project's actual script names to the phases below — do not assume fixed names.

Phases (run in order)

  1. Lint/format — the project's formatter + linter (e.g., Biome, or ESLint + Prettier)
  2. Type check — type check without emit
  3. Build — production build
  4. Test — unit/integration tests
  5. Coverage — coverage run when the task added or changed behavior

Troubleshooting

  • Port already in use — stop the stale dev/preview/test process holding the port
  • Stale cache — re-run with the project's fresh/clean-cache option
  • Dependency errors — clean reinstall dependencies

Situations Requiring Technical Decisions

Timing of Abstraction

  • Extract patterns after writing concrete implementation 3 times
  • Be conscious of YAGNI, implement only currently needed features
  • Prioritize current simplicity over future extensibility

Performance vs Readability

  • Prioritize readability unless React DevTools Profiler identifies a measurable bottleneck (e.g., render time exceeding 16ms, unnecessary re-renders)
  • Measure before optimizing with React DevTools Profiler
  • Document reason with comments when optimizing

Granularity of Component/Type Definitions

  • Overly detailed components/types reduce maintainability
  • Design components that appropriately express UI patterns
  • Use composition over inheritance

Implementation Completeness Assurance

Required Procedure for Impact Analysis

Completion Criteria: Complete all 3 stages

1. Discovery

Grep -n "ComponentName\|hookName" -o content
Grep -n "importedFunction" -o content
Grep -n "propsType\|StateType" -o content

2. Understanding

Mandatory: Read all discovered files and include necessary parts in context:

  • Caller's purpose and context
  • Component hierarchy
  • Data flow: Props → State → Event handlers → Callbacks

3. Identification

Structured impact report (mandatory):

## Impact Analysis
### Direct Impact: ComponentA, ComponentB (with reasons)
### Indirect Impact: FeatureX, PageY (with integration paths)
### Processing Flow: Props → Render → Events → Callbacks

Important: Execute all 3 stages to completion

Unused Code Deletion Rule

When unused code is detected → Will it be used?

  • Yes → Implement immediately (no deferral allowed)
  • No → Delete immediately (remains in Git history)

Target: Components, hooks, utilities, documentation, configuration files

Existing Code Deletion Decision Flow

In use? No → Delete immediately (remains in Git history)
       Yes → Working? No → Delete + Reimplement
                     Yes → Fix
该技能提供实施策略选择框架,用于规划实现方案、选择开发方法或定义验证标准。通过现状分析、策略探索、风险评估及约束验证四个阶段,结合元认知思维与多种设计模式,辅助制定最优技术实施路径。
规划系统实施策略 选择软件开发方法 定义技术验证标准 评估重构或迁移风险
dev-workflows-fullstack/skills/implementation-approach/SKILL.md
npx skills add shinpr/claude-code-workflows --skill implementation-approach -g -y
SKILL.md
Frontmatter
{
    "name": "implementation-approach",
    "description": "Implementation strategy selection framework. Use when planning implementation strategy, selecting development approach, or defining verification criteria."
}

Implementation Strategy Selection Framework (Meta-cognitive Approach)

Meta-cognitive Strategy Selection Process

Phase 1: Comprehensive Current State Analysis

Core Question: "What does the existing implementation look like?"

Analysis Framework

Architecture Analysis: Responsibility separation, data flow, dependencies, technical debt
Implementation Quality Assessment: Code quality, test coverage, performance, security
Historical Context Understanding: Current form rationale, past decision validity, constraint changes, requirement evolution

Meta-cognitive Question List

  • What is the true responsibility of this implementation?
  • Which parts are business essence and which derive from technical constraints?
  • What dependencies or implicit preconditions are unclear from the code?
  • What benefits and constraints does the current design bring?

Phase 2: Strategy Exploration and Creation

Core Question: "When determining before → after, what implementation patterns or strategies should be referenced?"

Strategy Discovery Process

Research and Exploration: Tech stack examples (WebSearch), similar projects, OSS references, literature/blogs
Creative Thinking: Strategy combinations, constraint-based design, phase division, extension point design

Reference Strategy Patterns (Creative Combinations Encouraged)

Legacy Handling Strategies:

  • Strangler Pattern: Gradual migration through phased replacement
  • Facade Pattern: Complexity hiding through unified interface
  • Adapter Pattern: Bridge with existing systems

New Development Strategies:

  • Feature-driven Development: Vertical implementation prioritizing user value
  • Foundation-driven Development: Foundation-first construction prioritizing stability
  • Risk-driven Development: Prioritize addressing maximum risk elements

Integration/Migration Strategies:

  • Proxy Pattern: Transparent feature extension
  • Decorator Pattern: Phased enhancement of existing features
  • Bridge Pattern: Flexibility through abstraction

Important: The optimal solution is discovered through creative thinking according to each project's context.

Phase 3: Risk Assessment and Control

Core Question: "What risks arise when applying this to existing implementation, and what's the best way to control them?"

Risk Analysis Matrix

Technical Risks: System impact, data consistency, performance degradation, integration complexity
Operational Risks: Service availability, deployment downtime, process changes, rollback procedures
Project Risks: Schedule delays, learning costs, quality achievement, team coordination

Risk Control Strategies

Preventive Measures: Phased migration, parallel operation verification, integration/regression tests, monitoring setup
Incident Response: Rollback procedures, log/metrics preparation, communication system, service continuation procedures

Phase 4: Constraint Compatibility Verification

Core Question: "What are this project's constraints?"

Constraint Checklist

Technical Constraints: Library compatibility, resource capacity, mandatory requirements, numerical targets
Temporal Constraints: Deadlines/priorities, dependencies, milestones, learning periods
Resource Constraints: Team/skills, work hours/systems, budget, external contracts
Business Constraints: Market launch timing, customer impact, regulatory compliance

Phase 5: Implementation Approach Decision

Select optimal solution from basic implementation approaches (creative combinations encouraged):

Vertical Slice (Feature-driven)

Characteristics: Vertical implementation across all layers by feature unit Application Conditions: Features share fewer than 2 data models, each feature is independently deliverable, changes touch 3+ architecture layers Verification Method: End-user value delivery at each feature completion

Horizontal Slice (Foundation-driven)

Characteristics: Phased construction by architecture layer Application Conditions: 3+ features depend on a common foundation layer, foundation changes require stability verification before consumers can proceed Verification Method: Integrated operation verification when all foundation layers complete

Hybrid (Creative Combination)

Characteristics: Flexible combination according to project characteristics Application Conditions: Unclear requirements, need to change approach per phase, transition from prototyping to full implementation Verification Method: Verify at appropriate L1/L2/L3 levels according to each phase's goals

Phase 6: Decision Rationale Documentation

Design Doc Documentation: Record in the Design Doc's implementation approach section:

  1. Selected strategy name and characteristics
  2. Alternatives considered and reason for rejection
  3. Risk mitigation plan (from Phase 3)
  4. Constraint compliance summary (from Phase 4)
  5. Verification level (L1/L2/L3) and integration point definition

Verification Level Definitions

Priority for completion verification of each task:

  • L1: Functional Operation Verification - Operates as end-user feature (e.g., search executable)
  • L2: Test Operation Verification - New tests added and passing
  • L3: Build Success Verification - Code builds/runs without errors

Priority: L1 > L2 > L3 in order of verifiability importance

Integration Point Definitions

Define integration points according to selected strategy:

  • Strangler-based: When switching between old and new systems for each feature
  • Feature-driven: When users can actually use the feature
  • Foundation-driven: When all architecture layers are ready and E2E tests pass
  • Hybrid: When individual goals defined for each phase are achieved

Quality Checks

  1. Verify at least one strategy combination beyond listed patterns was considered
  2. Confirm Phase 1 analysis framework is complete before selecting strategy
  3. Confirm Phase 3 risk analysis matrix is populated before implementation starts
  4. Confirm Phase 4 constraint checklist is reviewed before strategy decision
  5. Confirm Phase 6 documentation template is filled with selection rationale

Guidelines for Meta-cognitive Execution

  1. Leverage Known Patterns: Use as starting point, explore creative combinations
  2. Active WebSearch Use: Research implementation examples from similar tech stacks
  3. Apply 5 Whys: Pursue root causes to grasp essence
  4. Multi-perspective Evaluation: Comprehensively evaluate from each Phase 1-4 perspective
提供集成与端到端测试的设计原则、ROI计算模型及审查标准。指导用户根据业务价值选择测试类型(如fixture-e2e),确定预算上限,并优先覆盖高回报的用户可见行为,以优化测试质量与效率。
设计集成测试方案 规划E2E测试用例 评估测试ROI优先级 审查测试代码质量
dev-workflows-fullstack/skills/integration-e2e-testing/SKILL.md
npx skills add shinpr/claude-code-workflows --skill integration-e2e-testing -g -y
SKILL.md
Frontmatter
{
    "name": "integration-e2e-testing",
    "description": "Integration and E2E test design principles, ROI calculation, test skeleton specification, and review criteria. Use when designing integration tests, E2E tests, or reviewing test quality."
}

Integration and E2E Testing Principles

References

E2E test design: See references/e2e-design.md for UI Spec-driven E2E test candidate selection and browser test architecture. The reference uses Playwright as the default browser harness; substitute the project's standard when different.

Test Type Definition and Limits

Test Type Purpose Scope External Deps Limit per Feature Implementation Timing
Integration Verify component interactions in-process Partial system integration (in-process modules; for UI components, the framework's in-process renderer e.g., RTL+MSW for React/TS) Mocked or in-process MAX 3 Created alongside implementation
fixture-e2e Verify UI behavior in a browser with deterministic fixtures Full UI flow with mocked backend / fixture-driven state Mocked / fixture only — no live services MAX 3 Created alongside the UI feature
service-integration-e2e Verify critical user journeys against a running local stack Full system across services Live local services or stubs MAX 1-2 Executed only in the final phase

Lane selection (E2E only):

  • Default lane for user-facing UI journeys is fixture-e2e — it runs a real browser against deterministic fixtures, catches the bugs that unit/integration tests miss (button no-op, state never updates, navigation breaks), and runs in CI without infrastructure setup
  • Add service-integration-e2e only when the journey's correctness depends on real cross-service behavior (data persistence, transactional consistency, external service contracts) that cannot be faked safely

The two E2E lanes are budgeted independently — having a fixture-e2e for a journey does not consume the service-integration-e2e budget and vice versa.

Behavior-First Principle

Include (High ROI)

  • Business logic correctness (calculations, state transitions, data transformations)
  • Data integrity and persistence behavior
  • User-visible functionality completeness
  • Error handling behavior (what user sees/experiences)

Redirect to Other Test Types

  • External service connections → Verify via contract/interface tests
  • Performance metrics → Verify via dedicated load testing
  • Implementation details → Verify observable behavior instead
  • UI layout specifics → Verify information availability instead

Principle: Test = User-observable behavior verifiable in isolated CI environment

ROI Calculation

ROI is used to rank candidates within the same test type (integration candidates against each other, E2E candidates against each other). Cross-type comparison is unnecessary because integration and E2E budgets are selected independently.

ROI Score = Business Value × User Frequency + Legal Requirement × 10 + Defect Detection
              (range: 0–120)

Higher ROI Score = higher priority within its test type. No normalization or capping is applied — the raw score is used directly for ranking. Deduplication is a separate step that removes candidates entirely; it does not modify scores.

ROI Thresholds by Lane

The two E2E lanes have very different ownership costs and use independent thresholds.

Lane ROI threshold Rationale
fixture-e2e ROI ≥ 20 (beyond reserved slot) Cost is comparable to integration tests once the harness exists; the floor avoids filling MAX 3 with low-signal tests when fewer would suffice
service-integration-e2e ROI > 50 (beyond reserved slot) Creation, execution, and maintenance cost is 3-10× higher than integration; reserve for journeys whose value cannot be proven any other way

Reserved slot rules (see Multi-Step User Journey Definition below) apply per lane and override the threshold (the reserved candidate is emitted regardless of its ROI score). Below-floor candidates beyond the reserved slot are not emitted, leaving budget intentionally unfilled rather than padding with low-value tests.

ROI Calculation Examples

Scenario BV Freq Legal Defect ROI Score Test Type Selection Outcome
Core checkout UI flow 10 9 true 9 109 fixture-e2e Selected (reserved slot: user-facing multi-step journey, browser-level verification with fixtures)
Core checkout against live payment service 10 9 true 9 109 service-integration-e2e Selected (real-service correctness above ROI threshold)
Dismiss button updates UI state 6 7 false 8 50 fixture-e2e Selected (rank 2 of 3 fixture-e2e budget)
Payment error message display 5 4 false 7 27 fixture-e2e Selected (rank 3 of 3 fixture-e2e budget)
Optional filter toggle 3 4 false 2 14 fixture-e2e Not selected (rank 4, budget full)
Payment retry against real provider 8 3 false 7 31 service-integration-e2e Below ROI threshold (31 < 50), not selected
DB persistence check 8 8 false 8 72 Integration Selected (rank 1 of 3)
Pure data transformation 5 3 false 4 19 Integration Selected (rank 2 of 3)

Multi-Step User Journey Definition

A feature qualifies as containing a multi-step user journey when ALL of the following are true:

  1. 2+ distinct interaction boundaries are traversed in sequence to complete a user goal. What counts as a boundary depends on the system type:
    • Web: distinct routes/pages
    • Mobile native: distinct screens/views
    • CLI: distinct command invocations or interactive prompts
    • API: distinct API calls forming a transaction (e.g., create → confirm → finalize)
  2. State carries across steps — data produced or actions taken in one step affect what the next step accepts or displays
  3. The journey has a completion point — a final state the user or caller reaches (e.g., confirmation page, saved record, API success response, completed workflow)

User-Facing vs Service-Internal Journeys

Multi-step journeys are classified for reserved-slot eligibility:

Classification Condition Reserved Slot Eligibility Example
User-facing A human user directly triggers and observes the steps (via UI, CLI, or direct API interaction) Eligible — defaults to fixture-e2e reserved slot. Add a service-integration-e2e reserved slot only when the journey's correctness depends on real cross-service behavior Web checkout flow, CLI setup wizard, mobile onboarding
Service-internal Steps are triggered by backend services without direct user interaction Not eligible for reserved slot — use integration tests. Service-integration-e2e through normal ROI > 50 path is still valid when full-system verification is warranted Async job pipeline, service-to-service saga, scheduled batch processing

This classification applies only to the reserved-slot rule and the E2E Gap Check. Other selection follows lane-specific ROI rules above.

Use this definition when evaluating E2E test candidates and E2E gap detection.

Test Skeleton Specification

Required Comment Patterns

Each test MUST include the following annotations:

AC: [Original acceptance criteria text]
Behavior: [Trigger] → [Process] → [Observable Result]
@category: core-functionality | integration | edge-case | fixture-e2e | service-integration-e2e
@lane: integration | fixture-e2e | service-integration-e2e
@dependency: none | [component names] | full-system
@complexity: low | medium | high
ROI: [score]

@lane selection rule:

  • integration — Component interaction in-process, no browser (e.g., RTL+MSW for React/TS, in-process module/handler integration in any language)
  • fixture-e2e — Browser-level UI verification with mocked backend / fixture-driven state
  • service-integration-e2e — Browser-level or end-to-end verification against running local services or stubs

Use the project's comment syntax to wrap these annotations (e.g., // for C-family, # for Python/Ruby/Shell).

Verification Items (Optional)

When verification points need explicit enumeration:

Verification items:
- [Item 1]
- [Item 2]

EARS Format Mapping

EARS Keyword Test Type Generation Approach
When Event-driven Trigger event → verify outcome
While State condition Setup state → verify behavior
If-then Branch coverage Both condition paths verified
(none) Basic functionality Direct invocation → verify result

Test File Naming Convention

  • Integration tests: *.int.test.* or *.integration.test.*
  • fixture-e2e tests: *.fixture.e2e.test.* (or organize under tests/e2e/fixture/)
  • service-integration-e2e tests: *.service.e2e.test.* (or organize under tests/e2e/service/)

The test runner or framework in the project determines the appropriate file extension. Repos that already use a single *.e2e.test.* convention may keep it as long as each file declares @lane: in its header — the lane annotation is the source of truth for routing and budget accounting.

Review Criteria

Skeleton and Implementation Consistency

Check Failure Condition
Behavior Verification No assertion for "observable result" in the implemented test
Verification Item Coverage Listed items not all covered by assertions
Mock Boundary Internal components mocked in integration test

Implementation Quality

Check Failure Condition
AAA Structure Arrange/Act/Assert separation unclear
Independence State sharing between tests, order dependency
Reproducibility Date/random dependency, varying results
Readability Test name doesn't match verification content

Quality Standards

Required

  • Each test verifies one behavior
  • Clear AAA (Arrange-Act-Assert) structure
  • No test interdependencies
  • Deterministic execution
规范LLM友好型上下文编写,通过明确指令、具体标准、输出格式及不确定性处理,消除歧义,确保下游代理能准确执行任务。适用于提示词优化、交接文档及计划制定。
编写或修改面向LLM的提示词 创建代理间交接文档 生成执行计划或报告 审查指令清晰度
dev-workflows-fullstack/skills/llm-friendly-context/SKILL.md
npx skills add shinpr/claude-code-workflows --skill llm-friendly-context -g -y
SKILL.md
Frontmatter
{
    "name": "llm-friendly-context",
    "description": "Clarifies inputs, outputs, success criteria, decisions, and unresolved conditions so downstream agents can execute without guessing. Use when writing or revising LLM-facing prompts, handoffs, planning artifacts, reviews, reports, or generated instructions."
}

LLM-Friendly Context

The goal is stable downstream execution: the next agent should know what to read, what to do, what counts as success, and when to stop or escalate.

Core Rules

  1. Use positive, executable instructions

    • State what the next agent should do.
    • Convert quality policies into positive criteria.
    • Example: "Preserve existing public API behavior across the documented compatibility cases."
  2. Make vague instructions concrete

    • Replace subjective terms with observable conditions, paths, commands, schemas, examples, or decision rules.
    • Terms that often need clarification when they leave a decision to the next agent: appropriate, proper, related, existing behavior, optional, as needed, if needed, per convention, unresolved alternatives, TBD, placeholder.
  3. Specify output shape

    • Define required sections, fields, table columns, JSON keys, or checklist items.
    • For handoffs, include paths to produced artifacts and the exact status fields the caller must inspect.
  4. Provide necessary context

    • Include the purpose, source artifacts, hard constraints, accepted decisions, and unresolved conditions.
    • Prefer concrete file paths and section hints over broad module names.
  5. Decompose complex work into verifiable steps

    • Split work with 3+ objectives or sequential dependencies into ordered steps.
    • Each step needs a checkpoint: what evidence proves it is complete.
  6. Permit uncertainty explicitly

    • If the source material is missing, contradictory, or not verifiable, state the uncertainty and the required escalation.
    • Record unknown business, product, security, or compatibility decisions as blocking unresolved items with the input needed to resolve them.
  7. Keep constraints proportionate

    • Add only constraints that reduce ambiguity or preserve a real requirement.
    • Keep simple downstream tasks lightweight when the target action, context, and success criteria are already clear.

Rewrite Patterns

Use these rewrites before treating a prompt, handoff, or artifact as complete.

Ambiguous form Rewrite as
optional used as an unresolved choice Required, omitted, or required only under a named condition
Multiple alternatives that the next agent must choose between The selected option, or a deterministic decision rule
as needed / if needed The triggering condition and required action
per convention The file, function, test, or documented convention to follow
related files Specific paths, globs, or search hints
existing behavior The observable behavior, source file, test, API response, or UI state to preserve
placeholder Exact temporary value/behavior, allowed dependencies, and verification expectation
TBD used as a placeholder for required information A blocking unresolved item with owner, required input, or escalation condition
appropriate / proper A measurable criterion or checklist

Handoff Checklist

Before sending a prompt or artifact to another agent, verify:

  • The target action is explicit.
  • Required input paths and source artifacts are named.
  • Accepted decisions and constraints are stated once, without alternate wording.
  • Output format or expected status fields are specified.
  • Success criteria are observable.
  • Ambiguous expressions have been rewritten or marked as unresolved.
  • The next agent can complete its scope with explicit choices, decision rules, or blocking unresolved items.

Generated Artifact Checklist

Before writing or finalizing a generated document:

  • Each requirement, claim, task, test skeleton, or review finding has enough source context to trace why it exists.
  • Every executable instruction names the target, action, and expected result.
  • Verification steps say what to run or observe and what result proves success.
  • If an artifact is derived from another artifact, copied decisions stay consistent in wording and meaning.
  • If downstream work is blocked by missing information, the artifact records the missing input and escalation condition.
通过设计文档为现有代码库添加集成/E2E测试。协调发现文档、生成骨架、创建任务文件,并委托子代理执行实现与审查,确保测试质量。
需要为现有后端或前端功能添加集成测试 需要基于设计文档自动生成端到端测试用例
dev-workflows-fullstack/skills/recipe-add-integration-tests/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-add-integration-tests -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-add-integration-tests",
    "description": "Add integration\/E2E tests to existing codebase using Design Docs",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Test addition workflow for existing implementations (backend, frontend, or fullstack)

Orchestrator Definition

Core Identity: "I am an orchestrator."

First Action: Register Steps 0-8 using TaskCreate before any execution.

Why Delegate: Orchestrator's context is shared across all steps. Direct implementation consumes context needed for review and quality check phases. Task files create context boundaries. Subagents work in isolated context.

Execution Method:

  • Skeleton generation → delegate to acceptance-test-generator
  • Task file creation → orchestrator creates directly (minimal context usage)
  • Test implementation → delegate to task-executor
  • Test review → delegate to integration-test-reviewer
  • Quality checks → delegate to quality-fixer

Document paths: $ARGUMENTS

Prerequisites

  • At least one Design Doc must exist (created manually or via reverse-engineer)
  • Existing implementation to test

Execution Flow

Step 0: Execute Skill

Execute Skill: documentation-criteria (for task file template in Step 3)

Step 1: Discover and Validate Documents

# Verify at least one document path was provided
test -n "$ARGUMENTS" || { echo "ERROR: No document paths provided"; exit 1; }

# Verify provided paths exist
ls $ARGUMENTS

# Discover additional documents
ls docs/design/*.md 2>/dev/null | grep -v template
ls docs/ui-spec/*.md 2>/dev/null

Classify discovered documents by filename:

  • Filename contains backendDesign Doc (backend)
  • Filename contains frontendDesign Doc (frontend)
  • Located in docs/ui-spec/UI Spec (optional)
  • None of the above → treat as single-layer Design Doc

Step 2: Skeleton Generation

Invoke acceptance-test-generator using Agent tool:

  • subagent_type: "dev-workflows-fullstack:acceptance-test-generator"
  • description: "Generate test skeletons"
  • prompt: List only the documents that exist from Step 1:
    Generate test skeletons from the following documents:
    - Design Doc (backend): [path]    ← include only if exists
    - Design Doc (frontend): [path]   ← include only if exists
    - UI Spec: [path]                 ← include only if exists
    

Expected output: generatedFiles containing integration and e2e paths

Step 3: Create Task Files [GATE]

Create one task file per layer, using the monorepo-flow.md naming convention for deterministic agent routing:

  • Backend skeletons exist → docs/plans/tasks/integration-tests-backend-task-YYYYMMDD.md
  • Frontend skeletons exist → docs/plans/tasks/integration-tests-frontend-task-YYYYMMDD.md
  • Single-layer (no backend/frontend distinction) → docs/plans/tasks/integration-tests-backend-task-YYYYMMDD.md

Template (per task file):

---
name: Implement [layer] integration tests for [feature name]
type: test-implementation
---

## Objective

Implement test cases defined in skeleton files.

## Target Files

- Skeleton: [layer-specific paths from Step 2 generatedFiles]
- Design Doc: [layer-specific Design Doc from Step 1]

## Tasks

- [ ] Implement each test case in skeleton
- [ ] Verify all tests pass
- [ ] Ensure coverage meets requirements

## Acceptance Criteria

- All skeleton test cases implemented
- All tests passing
- quality-fixer reports approved

Output: "Task file(s) created at [path(s)]. Ready for Step 4."

Step 4: Test Implementation

For each task file from Step 3, invoke task-executor routed by filename pattern (per monorepo-flow.md):

  • *-backend-task-*subagent_type: "dev-workflows-fullstack:task-executor"
  • *-frontend-task-*subagent_type: "dev-workflows-fullstack:task-executor-frontend"
  • description: "Implement integration tests"
  • prompt: "Task file: [task file path from Step 3]. Implement tests following the task file."

Execute one task file at a time through Steps 4→5→6→7 before starting the next.

Expected output: status, testsAdded

Step 5: Test Review

Invoke integration-test-reviewer using Agent tool:

  • subagent_type: "dev-workflows-fullstack:integration-test-reviewer"
  • description: "Review test quality"
  • prompt: "Review test quality. Test files: [paths from Step 4 testsAdded]. Skeleton files: [layer-specific paths from Step 2 generatedFiles matching current task's layer]"

Expected output: status (approved/needs_revision), requiredFixes

Step 6: Apply Review Fixes

Check Step 5 result:

  • status: approved → Mark complete, proceed to Step 7
  • status: needs_revision → Invoke task-executor with requiredFixes, then return to Step 5

Invoke task-executor routed by task filename pattern:

  • *-backend-task-*subagent_type: "dev-workflows-fullstack:task-executor"
  • *-frontend-task-*subagent_type: "dev-workflows-fullstack:task-executor-frontend"
  • description: "Fix review findings"
  • prompt: "Fix the following issues in test files: [requiredFixes from Step 5]"

Step 7: Quality Check

Invoke quality-fixer routed by task filename pattern:

  • *-backend-task-*subagent_type: "dev-workflows-fullstack:quality-fixer"
  • *-frontend-task-*subagent_type: "dev-workflows-fullstack:quality-fixer-frontend"
  • description: "Final quality assurance"
  • prompt: "Final quality assurance for test files added in this workflow. Run all tests and verify coverage."

Expected output: status (approved/stub_detected/blocked)

Check quality-fixer response:

  • stub_detected → Return to Step 4 with incompleteImplementations[] details, then re-execute Steps 4→5→6→7
  • blocked → Escalate to user
  • approved → Proceed to Step 8

Step 8: Commit

On approved from quality-fixer:

  • Commit test files using Bash with message format: "test: add [layer] integration tests for [feature name]"

Step 9: Final Cleanup

After all task files have been processed and committed, delete the task files this recipe created. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file matching docs/plans/tasks/integration-tests-backend-task-*.md and docs/plans/tasks/integration-tests-frontend-task-*.md created during this run

If task files cannot be deleted (filesystem error), report the failure but do not block completion.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.
自主执行分解任务的编排技能。通过解析工作计划和任务文件,遵循四步循环(执行、检查、修复、提交),协调子代理完成开发任务,确保质量并清理已消耗的任务文件。
用户提供包含现有任务文件的执行指令 需要自主批量审批和执行分解的开发任务
dev-workflows-fullstack/skills/recipe-build/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-build -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-build",
    "description": "Execute decomposed tasks in autonomous execution mode",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Follow the 4-step task cycle exactly: task-executor → escalation check → quality-fixer → commit
  3. Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
  4. Scope: Complete when all tasks are committed or escalation occurs

CRITICAL: Run quality-fixer before every commit.

Work plan: $ARGUMENTS

Pre-execution Prerequisites

Work Plan Resolution

Before any task processing, locate the work plan. Resolution rule:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md. Layer-aware fullstack tasks ({plan-name}-backend-task-*.md / {plan-name}-frontend-task-*.md) are excluded here so a stale fullstack run does not redirect this recipe to the wrong work plan
  2. From the matched files, also exclude every file matching any of these patterns — they originate from other workflow phases and are not implementation tasks for this run's plan: *-task-prep-*.md (readiness preflight tasks), _overview-*.md (decomposition overview file), *-phase*-completion.md (per-phase completion files), review-fixes-*.md (post-implementation review fixes), integration-tests-*-task-*.md (integration-test add-on scaffolding)
  3. For each remaining file, extract the {plan-name} prefix as the segment that appears before -task-
  4. When at least one task file matches, the work plan is docs/plans/{plan-name}.md for the prefix that has the most recent task-file mtime; ties broken by the lexicographically last {plan-name}
  5. When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template .md in docs/plans/

Consumed Task Set

Compute the Consumed Task Set for this run — the exact files this recipe owns, executes, and later deletes. Use the same restricted pattern as Work Plan Resolution:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md for the {plan-name} resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded
  2. Exclude every file matching: *-task-prep-*.md, _overview-*.md, *-phase*-completion.md, review-fixes-*.md, integration-tests-*-task-*.md (these originate from other workflow phases)

Every subsequent reference to "task files" in this recipe — Task Generation Decision Flow, Task Execution Cycle iteration, and Final Cleanup — uses this set, not the unrestricted docs/plans/tasks/*.md glob.

Task Generation Decision Flow

Analyze the Consumed Task Set and determine the action required:

State Criteria Next Action
Tasks exist Consumed Task Set is non-empty User's execution instruction serves as batch approval → Enter autonomous execution immediately
No tasks + plan exists Consumed Task Set is empty but the resolved work plan exists Confirm with user → run task-decomposer
Neither exists + Design Doc exists No plan, no Consumed Task Set, but docs/design/*.md exists Invoke work-planner to create work plan from Design Doc, then run document-reviewer (dev-workflows-fullstack:document-reviewer, doc_type: WorkPlan); branch on the reviewer's verdict.decision — on needs_revision, re-invoke work-planner (update) and re-review until approved/approved_with_conditions, then present the reviewed plan for batch approval before task decomposition; on rejected, stop before task decomposition and escalate to the user
Neither exists No plan, no Consumed Task Set, no Design Doc Report missing prerequisites to user and stop

Task Decomposition Phase (Conditional)

When the Consumed Task Set is empty:

1. User Confirmation

No task files in the Consumed Task Set.
Work plan: docs/plans/[plan-name].md

Generate tasks from the work plan? (y/n):

2. Task Decomposition (if approved)

Invoke task-decomposer using Agent tool:

  • subagent_type: "dev-workflows-fullstack:task-decomposer"
  • description: "Decompose work plan"
  • prompt: "Read work plan at docs/plans/[plan-name].md and decompose into atomic tasks. Output: Individual task files in docs/plans/tasks/. Granularity: 1 task = 1 commit = independently executable"

3. Verify Generation

Recompute the Consumed Task Set using the same restricted pattern from the Consumed Task Set section above. Confirm it is now non-empty. If it is still empty, escalate to the user — task-decomposer either failed silently or produced files that don't match the expected pattern.

Flow: Task generation → Consumed Task Set recompute → Autonomous execution (in this order)

Pre-execution Checklist

  • Confirmed Consumed Task Set is non-empty (computed in the Consumed Task Set section above)
  • Identified task execution order within the Consumed Task Set (dependencies)
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Task Execution Cycle (4-Step Cycle)

MANDATORY EXECUTION CYCLE: task-executor → escalation check → quality-fixer → commit

For EACH task in the Consumed Task Set, YOU MUST:

  1. Register tasks using TaskCreate: Register work steps. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON"
  2. Agent tool (subagent_type: "dev-workflows-fullstack:task-executor") → Pass task file path in prompt, receive structured response
  3. CHECK task-executor response:
    • status: "escalation_needed" or "blocked" → STOP and escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 2 with requiredFixes
      • approved → Proceed to step 4
    • readyForQualityCheck: true → Proceed to step 4
  4. INVOKE quality-fixer: Execute all quality checks and fixes. Always pass the current task file path as task_file
  5. CHECK quality-fixer response:
    • stub_detected → Return to step 2 with incompleteImplementations[] details
    • blocked → STOP and escalate to user
    • approved → Proceed to step 6
  6. COMMIT on approval: Execute git commit

CRITICAL: Parse every sub-agent response for status fields. Execute the matching branch in the 4-step cycle. Proceed to next task only after quality-fixer returns approved.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Verify task files exist per Pre-execution Checklist, then enter autonomous execution mode. When requirement changes are detected during execution, escalate to the user with the change summary before continuing.

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows-fullstack:code-verifier") → doc_type: design-doc, Design Doc path, code_paths: implementation file list (git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows-fullstack:security-reviewer") → Design Doc path, implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute task-executor with consolidated fixes → quality-fixer
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file in the Consumed Task Set
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer for this {plan-name})
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Completion Report Contract

Final report must include:

  • Task decomposition status
  • Implemented task count
  • Quality check result
  • Commit count
  • Cleanup result
  • Escalation or blocking summary, if any
该技能用于代码库分析到设计文档创建的编排。通过委派子代理执行范围引导、代码分析、技术设计、验证及审查流程,并在关键节点等待用户批准,最终产出获批的ADR或设计文档。
需要创建架构决策记录(ADR) 需要生成技术设计文档 从代码库分析启动设计阶段
dev-workflows-fullstack/skills/recipe-design/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-design -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-design",
    "description": "Execute from codebase analysis to design document creation",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the design phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results. The one exception is the Step 1 scope bootstrap, a recipe-local orchestrator task limited to locating seed files.
  2. Run the design flow below in order:
    • Execute: scope bootstrap → codebase-analyzer → [Stop: Scope confirmation] → technical-designer → code-verifier → document-reviewer → design-sync
    • code-verifier and design-sync apply when the design output is a Design Doc; both are skipped for ADR-only
    • Stop at every [Stop: ...] marker → Wait for user approval before proceeding
  3. Scope: Complete when design documents receive approval

subagents-orchestration-guide usage: Reference the guide only for orchestration principles (Delegation Boundary, Decision precedence, permitted tools), the Scale Determination table, and handoff contracts HC-02 onward. This recipe defines its own start order and subagent prompts. The guide's requirement-analyzer-origin flow, First Action Rule, HC-01, and Call Examples do not apply to this recipe.

CRITICAL: Execute document-reviewer, design-sync (for Design Docs), and all stopping points — each serves as a quality gate. Skipping any step risks undetected inconsistencies.

Workflow Overview

Requirements → scope bootstrap → codebase-analyzer → [Stop: Scope confirmation]
                                                            ↓
                                                    technical-designer
                                                            ↓
                                                    code-verifier → document-reviewer
                                                            ↓
                                                       design-sync → [Stop: Design approval]

Scope Boundaries

Included in this skill:

  • Scope bootstrap: locating seed files so codebase-analyzer receives a populated input
  • Codebase analysis with codebase-analyzer (entry point of the design phase)
  • Scope confirmation with the user, grounded in codebase-analyzer findings
  • ADR creation (if architecture changes, new technology, or data flow changes)
  • Design Doc creation with technical-designer
  • Design Doc verification with code-verifier (before document review)
  • Document review with document-reviewer
  • Design Doc consistency verification with design-sync

Responsibility Boundary: This skill completes with design document (ADR/Design Doc) approval. Work planning and beyond are outside scope.

Execution Flow

Requirements: $ARGUMENTS

Step 1: Scope Bootstrap

codebase-analyzer requires a populated requirement_analysis.affectedFiles. Build that seed with a lightweight, orchestrator-local pass — locating files only, with no deep reading and no design decisions:

  1. Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
  2. Search the repository with Bash (rg, or grep when rg is unavailable) for files matching those keywords.
  3. Collect the matched file paths as the seed affectedFiles.
  4. When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as affectedFiles before invoking codebase-analyzer. If the user confirms no related code exists, report that codebase-grounded design does not apply and confirm with the user how to proceed.
  5. When the search returns more than ~20 files: the keywords are too broad for a focused design scope. Present the most relevant candidates to the user (AskUserQuestion) and confirm the seed affectedFiles before invoking codebase-analyzer.

This step locates seed files only. Reading files in full, tracing dependencies, and analysis remain codebase-analyzer's responsibility.

Step 2: Codebase Analysis

Invoke codebase-analyzer with its existing schema. The orchestrator constructs requirement_analysis from the Step 1 seed.

  • Invoke codebase-analyzer using Agent tool
    • subagent_type: "dev-workflows-fullstack:codebase-analyzer", description: "Codebase analysis"
    • prompt: include
      • requirements: the user requirements verbatim
      • requirement_analysis: a JSON object with all four fields — affectedFiles (Step 1 seed), purpose (the user requirements), scale (provisional value from the Scale Determination table applied to the seed file count), technicalConsiderations ({ constraints: [], risks: [], dependencies: [] } — the bootstrap performs no analysis, so the object is present with empty lists)
      • Expected action: analyze the seed files and produce design guidance

Step 3: Scope Confirmation

After codebase-analyzer returns, confirm the design scope with the user before any design work. This is a recipe-local confirmation step. Use AskUserQuestion.

Present, sourced from the codebase-analyzer JSON:

  • Target files/modules: analysisScope.filesAnalyzed and the modules they belong to
  • Affected layers: layers touched, derived from analysisScope.categoriesDetected and focusAreas
  • Unknowns/assumptions: limitations plus any assumptions codebase-analyzer recorded
  • Questions before design: open points that need a user answer before design proceeds

Ask the user to choose one:

  • Proceed to design with this scope — continue to Step 4 (Design Doc)
  • Correct the scope and re-run — return to Step 1 with the corrected scope; when the user names the corrected files or modules, use those directly as the Step 1 seed instead of re-deriving them by search
  • Hold additional hearing, then proceed — gather the missing answers, then continue to Step 4
  • Produce an ADR — when the confirmed scope involves architecture changes, new technology, or data flow changes, continue to Step 4 with technical-designer in ADR mode

After the user confirms the scope, count the confirmed target files and set the scale from the subagents-orchestration-guide Scale Determination table. This confirmed scale supersedes the Step 2 provisional value and determines the design document.

[STOP]: Wait for the user's choice before proceeding.

Step 4: Design Document Creation

Pass the full codebase-analyzer JSON to technical-designer (handoff contract HC-02). technical-designer presents at least two design alternatives with trade-offs for each.

  • Invoke technical-designer using Agent tool
    • For Design Doc: subagent_type: "dev-workflows-fullstack:technical-designer", description: "Design Doc creation", prompt: "Create Design Doc based on the requirements. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. Confirmed scope: [Step 3 confirmed scope]. Apply the code: prefix to codebase-analyzer fact_ids when filling the Fact Disposition Table. Present at least two architecture alternatives with trade-offs."
    • For ADR: subagent_type: "dev-workflows-fullstack:technical-designer", description: "ADR creation", prompt: "Create ADR for [technical decision]. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. Confirmed scope: [Step 3 confirmed scope]. Present at least two alternatives with trade-offs."
  • (Design Doc only) Invoke code-verifier to verify the Design Doc against existing code. Skip for ADR.
    • subagent_type: "dev-workflows-fullstack:code-verifier", description: "Design Doc verification", prompt: "doc_type: design-doc document_path: [Design Doc path] Verify Design Doc against existing code."
  • Invoke document-reviewer to verify consistency (pass code-verifier results for Design Doc; omit for ADR)
    • subagent_type: "dev-workflows-fullstack:document-reviewer", description: "Document review", prompt: "Review [document path] for consistency and completeness. codebase_analysis: [codebase-analyzer JSON from Step 2]. code_verification: [code-verifier output from this step] (Design Doc only)"
  • (Design Doc only) Invoke design-sync to verify consistency across design documents. Skip for ADR-only.
    • subagent_type: "dev-workflows-fullstack:design-sync", description: "Design consistency check", prompt: "Check consistency across all Design Docs in docs/design/. Report conflicts and overlaps."

[STOP]: Present the design document, plus design-sync results for a Design Doc, and obtain user approval.

Completion Criteria

  • Built the Step 1 scope bootstrap seed (or obtained target files from the user when the search returned none)
  • Executed codebase-analyzer with a populated requirement_analysis
  • Confirmed the design scope with the user and set the scale from the confirmed target files
  • Created appropriate design document (ADR or Design Doc) with technical-designer
  • Executed code-verifier on Design Doc and passed results to document-reviewer (skip for ADR-only)
  • Executed document-reviewer and addressed feedback
  • Executed design-sync for consistency verification (skip for ADR-only)
  • Obtained user approval for design document

Output Example

Design phase completed.

  • Design document: docs/design/[document-name].md or docs/adr/[document-name].md
  • Approval status: User approved
该技能用于系统化诊断问题,通过编排调查、验证和求解子代理识别根因并生成解决方案。支持变更失败与新发现分类,结合规则顾问分析核心本质,结构化传递数据以高效定位问题。
需要排查系统故障或错误原因 用户报告异常行为且需推导修复方案 涉及代码或配置变更后的问题归因
dev-workflows-fullstack/skills/recipe-diagnose/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-diagnose -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-diagnose",
    "description": "Investigate problem, verify findings, and derive solutions",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Diagnosis flow to identify root cause and present solutions

Target problem: $ARGUMENTS

Orchestrator Definition

Core Identity: "I am not a worker. I am an orchestrator."

Execution Method:

  • Investigation → performed by investigator
  • Verification → performed by verifier
  • Solution derivation → performed by solver

Orchestrator invokes sub-agents and passes structured JSON between them.

Task Registration: Register execution steps using TaskCreate and proceed systematically. Update status using TaskUpdate.

Step 0: Problem Structuring (Before investigator invocation)

0.1 Problem Type Determination

Type Criteria
Change Failure Indicates some change occurred before the problem appeared
New Discovery No relation to changes is indicated

If uncertain, ask the user whether any changes were made right before the problem occurred.

0.2 Information Supplementation for Change Failures

If the following are unclear, ask with AskUserQuestion before proceeding:

  • What was changed (cause change)
  • What broke (affected area)
  • Relationship between both (shared components, etc.)

0.3 Problem Essence Understanding

Invoke rule-advisor via Agent tool:

subagent_type: rule-advisor
description: "Problem essence analysis"
prompt: Identify the essence and required rules for this problem: [Problem reported by user]

Confirm from rule-advisor output:

  • taskAnalysis.mainFocus: Primary focus of the problem
  • mandatoryChecks.taskEssence: Root problem beyond surface symptoms
  • selectedRules: Applicable rule sections
  • warningPatterns: Patterns to avoid

0.4 Reflecting in investigator Prompt

Include the following in investigator prompt:

  1. Problem essence (taskEssence)
  2. Key applicable rules summary (from selectedRules)
  3. Investigation focus (investigationFocus): Convert warningPatterns to "points prone to confusion or oversight in this investigation"
  4. For change failures, additionally include:
    • Detailed analysis of the change content
    • Commonalities between cause change and affected area
    • Determination of whether the change is a "correct fix" or "new bug" with comparison baseline selection

Diagnosis Flow Overview

Problem → investigator → verifier → solver ─┐
                 ↑                          │
                 └── coverage insufficient ─┘
                      (max 2 iterations)

coverage sufficient → Report

Context Separation: Pass only structured JSON output to each step. Each step starts fresh with the JSON data only.

Execution Steps

Register the following using TaskCreate and execute:

Step 1: Investigation (investigator)

Agent tool invocation:

subagent_type: investigator
description: "Investigate problem"
prompt: |
  Comprehensively collect information related to the following phenomenon.

  Phenomenon: [Problem reported by user]

  Problem essence: [taskEssence from Step 0.3]
  Investigation focus: [investigationFocus from Step 0.4]

  [For change failures, additionally include:]
  Change details: [What was changed]
  Affected area: [What broke]
  Shared components: [Commonalities between cause and effect]

Expected output: pathMap (execution paths per symptom), failurePoints (faults found at each node), impactAnalysis per failure point, unexplored areas, investigation limitations

Step 2: Investigation Quality Check

Review investigation output:

Quality Check (verify JSON output contains the following):

  • pathMap exists with at least one symptom, and each symptom has at least one path with nodes listed
  • Each failure point has: location, upstreamDependency, symptomExplained, causalChain (reaching a stop condition), checkStatus, evidence with a source citing a specific file or location
  • Each failure point has comparisonAnalysis (normalImplementation found or explicitly null)
  • causeCategory for each failure point is one of: typo / logic_error / missing_constraint / design_gap / external_factor
  • investigationSources covers at least 3 distinct source types (code, history, dependency, config, document, external)
  • Investigation covers investigationFocus items (when provided in Step 0.4)
  • All nodes on mapped paths have been checked (no path was abandoned after finding the first fault)

If quality insufficient: Re-run investigator specifying missing items explicitly:

prompt: |
  Re-investigate with focus on the following gaps:
  - Missing: [list specific missing items from quality check]

  Previous investigation results (for context, do not re-investigate covered areas):
  [Previous investigation JSON]

design_gap Escalation:

When investigator output contains causeCategory: design_gap or recurrenceRisk: high:

  1. Insert user confirmation before verifier execution
  2. Use AskUserQuestion: "A design-level issue was detected. How should we proceed?"
    • A: Attempt fix within current design
    • B: Include design reconsideration
  3. If user selects B, pass includeRedesign: true to solver

Proceed to verifier once quality is satisfied.

Step 3: Verification (verifier)

Agent tool invocation:

subagent_type: verifier
description: "Verify investigation results"
prompt: Verify the following investigation results.

Investigation results: [Investigation JSON output]

Expected output: Coverage check (missing paths, unchecked nodes), Devil's Advocate evaluation per failure point, failure point evaluation with checkStatus, coverage assessment

Coverage Criteria:

  • sufficient: Main paths traced, all critical nodes checked, each failure point individually evaluated
  • partial: Main paths traced, some nodes unchecked or some failure points at blocked/not_reached
  • insufficient: Significant paths untraced, or critical nodes not investigated

Step 4: Solution Derivation (solver)

Agent tool invocation:

subagent_type: solver
description: "Derive solutions"
prompt: Derive solutions based on the following verified failure points.

Confirmed failure points: [verifier's conclusion.confirmedFailurePoints]
Refuted failure points: [verifier's conclusion.refutedFailurePoints]
Failure point relationships: [verifier's conclusion.failurePointRelationships]
Impact analysis: [investigator's impactAnalysis]
Coverage assessment: [sufficient/partial/insufficient]

Expected output: Multiple solutions (at least 3), tradeoff analysis, recommendation and implementation steps, residual risks

Completion condition: coverageAssessment=sufficient

When not reached:

  1. Return to Step 1 with unchecked areas identified by verifier as investigation targets
  2. Maximum 2 additional investigation iterations
  3. After 2 iterations without reaching sufficient, present user with options:
    • Continue additional investigation
    • Execute solution at current coverage level

Step 5: Final Report Creation

Prerequisite: coverageAssessment=sufficient achieved

After diagnosis completion, report to user in the following format:

## Diagnosis Result Summary

### Identified Failure Points
[Confirmed failure points from verification results]
- Per failure point: location, symptom explained, finalStatus

### Verification Process
- Path coverage: [Paths traced and nodes checked]
- Additional investigation iterations: [0/1/2]
- Coverage assessment: [sufficient/partial/insufficient]

### Recommended Solution
[Solution derivation recommendation]

Rationale: [Selection rationale]

### Implementation Steps
1. [Step 1]
2. [Step 2]
...

### Alternatives
[Alternative description]

### Residual Risks
[solver's residualRisks]

### Post-Resolution Verification Items
- [Verification item 1]
- [Verification item 2]

Completion Criteria

  • Executed investigator and obtained pathMap, failurePoints, and impactAnalysis
  • Performed investigation quality check and re-ran if insufficient
  • Executed verifier and obtained coverage assessment
  • Executed solver
  • Achieved coverageAssessment=sufficient (or obtained user approval after 2 additional iterations)
  • Presented final report to user
用于在会话内调整已实现UI的技能。通过委托子代理获取资源与分析代码,主会话执行编辑、设计源验证及质量检查循环,直至修改提交且通过测试,确保UI变更与设计一致。
需要对已实现的UI进行微调或修正 要求基于设计稿验证并迭代UI调整结果
dev-workflows-fullstack/skills/recipe-front-adjust/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-adjust -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-adjust",
    "description": "Adjust an already-implemented UI in-session with verification against the design source",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: UI adjustment on already-implemented features. The verification loop (edit → check against the design source → refine) runs in the parent session.

Execution Pattern

Core Identity: "I am a guided executor. I run the adjustment and the verification loop myself; subagents handle one-shot tasks."

Execution Protocol:

  1. Delegate to subagents (one-shot calls): ui-analyzer, work-planner, quality-fixer-frontend.
  2. Run in the parent session (multi-step loops and user dialogs): external-resource hearing via AskUserQuestion, write-set confirmation, scale judgment, adjustment edits, verification against the design source, iteration until acceptance.
  3. Stop at every [Stop: ...] marker before proceeding.

Initial Mandatory Tasks

Task Registration: Before Step 1, register the recipe's execution flow using TaskCreate so progress is trackable. Register Steps 1-7 below as individual tasks plus a final task "Verify completion against Completion Criteria". Update status using TaskUpdate as each step starts and completes.

Workflow Overview

Adjustment request → external resource hearing (parent session, AskUserQuestion)
                                  ↓
                     ui-analyzer (subagent: fetch external sources + analyze code + propose candidateWriteSet)
                                  ↓
                     write-set confirmation (parent session, AskUserQuestion)
                                  ↓
                     scale judgment on confirmed write set (documentation-criteria matrix)
                                  ↓
            ┌────────────────────┴────────────────────┐
            ↓                                          ↓
   (1-2 files: inline)                  (3-5 files: work-planner subagent → [Stop])
            ↓                                          ↓
            └─→ adjustment + verification (parent session) ←──┘
                                  ↓
                     quality-fixer-frontend (subagent: typecheck/lint/test)
                                  ↓
                     commit

Scope Boundaries

Included in this skill:

  • External resource hearing per the external-resource-context skill
  • UI fact gathering via ui-analyzer
  • Scale judgment via documentation-criteria's Creation Decision Matrix
  • Optional work plan creation via work-planner
  • Adjustment edits and verification against the design source (run in this session)
  • Quality verification via quality-fixer-frontend
  • Commit per adjustment unit

Responsibility Boundary: This skill completes when the adjustment is committed and quality has passed. Adjustment work is end-to-end within this recipe; parent session owns edits, verification loops, quality-result routing, and commits.

Escalation Boundary: Escalate to the full frontend design phase when the request requires PRD, UI Spec, Design Doc, new architecture, multi-screen redesign, or any ADR Creation Condition from documentation-criteria.

Adjustment request: $ARGUMENTS

Execution Flow

Step 1: External Resource Hearing

Run the hearing protocol per the external-resource-context skill (frontend domain).

Step 2: UI Fact Gathering

  • Invoke ui-analyzer using Agent tool
    • subagent_type: "dev-workflows-fullstack:ui-analyzer"
    • description: "UI fact gathering for adjustment"
    • prompt: "requirement_analysis: { affectedFiles: [files inferred from the adjustment request], scale: 'small', purpose: 'UI adjustment', technicalConsiderations: [] }. requirements: [adjustment request]. target_components: [components named in the request]. ui_spec_path: [path if an existing UI Spec covers the affected components, else absent]. Read docs/project-context/external-resources.md, fetch external UI sources via the declared access methods, and analyze the existing UI codebase. Populate candidateWriteSet[] with the files most likely to require modification."

Step 3: Scale Judgment

Execute Skill: documentation-criteria (loads the Creation Decision Matrix and ADR Creation Conditions used in this step and in the Escalation Boundary).

  1. Read candidateWriteSet[] from ui-analyzer output.
  2. Present the candidate list to the user via AskUserQuestion: "Confirmed write set for this adjustment? (a) accept high-confidence entries / (b) accept all entries / (c) edit list manually". On c, send a follow-up plain message asking the user to paste the edited file list, then proceed with that list.
  3. Apply the Creation Decision Matrix from the documentation-criteria skill to the confirmed write set count:
    • 0 files: The adjustment request did not map to any existing file. Escalate to the user with the message "No write target identified from the adjustment request. Please clarify which component(s) should change, or run the full frontend design phase if this is a new feature." Stop this recipe.
    • 1-2 files: Direct adjustment, no work plan.
    • 3-5 files: Work plan required.
    • 6+ files OR any ADR Creation Condition triggered (architecture changes, contract changes affecting 3+ locations, complex multi-state logic, etc.): Adjustment scope exceeded. Escalate the user to the full frontend design phase. Stop this recipe.

Step 4: Plan Creation (Conditional)

Branch on the scale outcome.

Branch A — 1-2 files

No work plan. Build a minimal adjustment context for the parent session:

  • Adjustment request (verbatim)
  • ui-analyzer focusAreas[] (raw fact_id; the ui: prefix is only applied when merging with codebase-analysis facts in a Fact Disposition Table, which Branch A does not do)
  • Affected files list
  • External resources fetched_summary and access methods that the verification loop will use

Present the adjustment context to the user for review.

  • [STOP]: User confirms the adjustment context covers the work.

Branch B — 3-5 files

Create a right-sized work plan. Invoke work-planner using Agent tool:

  • subagent_type: "dev-workflows-fullstack:work-planner"
  • description: "Adjustment work plan"
  • prompt: "Create a work plan for this UI adjustment. Adjustment request: [verbatim]. ui_analysis: [ui-analyzer JSON]. External resources: docs/project-context/external-resources.md. Scale: 3-5 files (no Design Doc, no ADR). Each phase should be implementable as 1-3 commits. Include a quality checklist matched to the affected components: visual verification, accessibility, i18n parity, generated artifact regeneration when relevant. Output path: docs/plans/[YYYYMMDD]-adjust-[short-description].md."

After work-planner returns:

  • Present the work plan to the user.
  • [STOP]: Wait for plan approval or revision request. If the user requests changes, re-invoke work-planner with revised guidance.

Step 5: Adjustment + Verification (parent session)

For each adjustment unit (per file in Branch A; per work plan phase in Branch B):

  1. Plan the edit based on ui-analyzer focusAreas and the relevant external resource (e.g., design origin's fetched_summary).
  2. Apply the edit using Edit / Write / MultiEdit on the affected files.
  3. Verify against external sources using whichever access method docs/project-context/external-resources.md declares for each axis:
    • Design origin: compare current rendering against the design source via the declared access method (e.g., design-tool MCP, WebFetch from a public URL, file read from a specification path)
    • Visual rendering: capture screenshot or run a smoke check via the declared visual verification method (e.g., browser MCP, E2E test runner CLI invoked via Bash, dev-server URL inspection, Storybook URL)
    • Design system tokens / variants: confirm against the declared design system source (e.g., design-system MCP, package import, Storybook URL, internal documentation path)
  4. Refine and re-verify until the adjustment matches the design source, or matches the user-confirmed adjustment target when no separate design source exists.
  5. When the adjustment unit converges, proceed to Step 6 for that unit.

When the project-tier file declares no automated verification mechanism for an axis, ask the user to confirm the result manually, or use file-based comparison when a specification file is available.

Step 6: Quality Verification (per adjustment unit)

  • Invoke quality-fixer-frontend using Agent tool
    • subagent_type: "dev-workflows-fullstack:quality-fixer-frontend"
    • description: "Quality verification for adjustment unit"
    • Build the prompt by branch. Scope is always filesModified; task_file (when passed) is a supplementary hint that quality-fixer-frontend may use to read the document's "Quality Assurance Mechanisms" section.
      • Branch A (1-2 files): omit task_file. Pass filesModified: [list of files edited in this adjustment unit].
      • Branch B (3-5 files): pass task_file: <work plan path> (supplementary hint) AND filesModified: [list of files edited in this adjustment unit] (primary scope).
    • Example (Branch A): prompt: "filesModified: [src/components/Card/Card.tsx, src/components/Card/Card.module.css]. Run quality checks across the listed files."
    • Example (Branch B): prompt: "task_file: docs/plans/[plan-name].md. filesModified: [src/components/Card/Card.tsx, src/components/Card/Card.module.css]. Run quality checks across the listed files."
  • Route the quality-fixer-frontend response by status:
    • approved → proceed to Step 7
    • stub_detected → return to Step 5 to complete the implementation for this unit, then re-invoke quality-fixer-frontend
    • blocked → read reason. When "Cannot determine due to unclear specification", surface blockingIssues[] to the user and stop. When "Execution prerequisites not met", surface missingPrerequisites[] with resolutionSteps to the user and stop

Step 7: Commit (per adjustment unit)

Commit the adjustment unit on quality approval. Include the affected files and any regenerated artifacts (CSS module typings, message catalog typings, etc.) flagged by ui-analyzer's generatedArtifacts section.

Then loop back to Step 5 for the next unit (Branch B work plan phase, or next file in Branch A) until all units are committed.

Completion Criteria

  • External resource hearing executed (project-tier file written or update explicitly skipped)
  • ui-analyzer returned a JSON output, including externalResources fetch_status per axis and candidateWriteSet
  • Write set confirmed by the user before scale judgment
  • Scale judgment applied to the confirmed write set; 6+ files or ADR conditions escalated to the design phase
  • Branch A: adjustment context presented and confirmed; Branch B: work plan approved
  • All adjustment units edited and verified using the project's declared verification mechanism (manual confirmation when no automated mechanism is declared)
  • Each adjustment unit passed quality-fixer-frontend with explicit filesModified scoping
  • Each adjustment unit committed

Output Example

Frontend adjustment completed.
- External resources: docs/project-context/external-resources.md (updated|unchanged)
- UI fact gathering: ui-analyzer focused on [N] components, [M] focus areas, external sources [fetched|partial|not_recorded]
- Scale: <1-2 files | 3-5 files>
- Work plan: <path | not required>
- Adjustment units committed: [count]
- Quality status: all passed
前端构建编排技能,用于自主执行前端实现。通过解析任务文件确定工作流,严格遵循4步循环(执行、检查、修复、提交),自动筛选有效任务并排除其他阶段文件,确保代码质量与流程规范。
用户下达包含现有任务文件的执行指令 需要自主完成前端代码实现并提交
dev-workflows-fullstack/skills/recipe-front-build/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-build -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-build",
    "description": "Execute frontend implementation in autonomous execution mode",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Follow the 4-step task cycle exactly: task-executor-frontend → escalation check → quality-fixer-frontend → commit
  3. Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
  4. Scope: Complete when all tasks are committed or escalation occurs

CRITICAL: Run quality-fixer-frontend before every commit.

Work plan: $ARGUMENTS

Pre-execution Prerequisites

Work Plan Resolution

Before any task processing, locate the work plan. Resolution rule:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md. Layer-aware fullstack tasks ({plan-name}-backend-task-*.md / {plan-name}-frontend-task-*.md) are excluded here so a stale fullstack run does not redirect this recipe to the wrong work plan
  2. From the matched files, also exclude every file matching any of these patterns — they originate from other workflow phases and are not implementation tasks for this run's plan: *-task-prep-*.md (readiness preflight tasks), _overview-*.md (decomposition overview file), *-phase*-completion.md (per-phase completion files), review-fixes-*.md (post-implementation review fixes), integration-tests-*-task-*.md (integration-test add-on scaffolding)
  3. For each remaining file, extract the {plan-name} prefix as the segment that appears before -task-
  4. When at least one task file matches, the work plan is docs/plans/{plan-name}.md for the prefix that has the most recent task-file mtime; ties broken by the lexicographically last {plan-name}
  5. When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template .md in docs/plans/

Consumed Task Set

Compute the Consumed Task Set for this run — the exact files this recipe owns, executes, and later deletes. Use the same restricted pattern as Work Plan Resolution:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md for the {plan-name} resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded
  2. Exclude every file matching: *-task-prep-*.md, _overview-*.md, *-phase*-completion.md, review-fixes-*.md, integration-tests-*-task-*.md (these originate from other workflow phases)

Every subsequent reference to "task files" in this recipe — Task Generation Decision Flow, Task Execution Cycle iteration, and Final Cleanup — uses this set, not the unrestricted docs/plans/tasks/*.md glob.

Task Generation Decision Flow

Analyze the Consumed Task Set and determine the action required:

State Criteria Next Action
Tasks exist Consumed Task Set is non-empty User's execution instruction serves as batch approval → Enter autonomous execution immediately
No tasks + plan exists Consumed Task Set is empty but the resolved work plan exists Confirm with user → run task-decomposer
Neither exists + Design Doc exists No plan, no Consumed Task Set, but docs/design/*.md exists Invoke work-planner to create work plan from Design Doc, then run document-reviewer (dev-workflows-fullstack:document-reviewer, doc_type: WorkPlan); branch on the reviewer's verdict.decision — on needs_revision, re-invoke work-planner (update) and re-review until approved/approved_with_conditions, then present the reviewed plan for batch approval before task decomposition; on rejected, stop before task decomposition and escalate to the user
Neither exists No plan, no Consumed Task Set, no Design Doc Report missing prerequisites to user and stop

Task Decomposition Phase (Conditional)

When the Consumed Task Set is empty:

1. User Confirmation

No task files in the Consumed Task Set.
Work plan: docs/plans/[plan-name].md

Generate tasks from the work plan? (y/n):

2. Task Decomposition (if approved)

Invoke task-decomposer using Agent tool:

  • subagent_type: "dev-workflows-fullstack:task-decomposer"
  • description: "Decompose work plan"
  • prompt: "Read work plan at docs/plans/[plan-name].md and decompose into atomic tasks. Output: Individual task files in docs/plans/tasks/. Granularity: 1 task = 1 commit = independently executable"

3. Verify Generation

Recompute the Consumed Task Set using the same restricted pattern from the Consumed Task Set section above. Confirm it is now non-empty. If it is still empty, escalate to the user — task-decomposer either failed silently or produced files that don't match the expected pattern.

Flow: Task generation → Consumed Task Set recompute → Autonomous execution (in this order)

Pre-execution Checklist

  • Confirmed Consumed Task Set is non-empty (computed in the Consumed Task Set section above)
  • Identified task execution order within the Consumed Task Set (dependencies)
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Task Execution Cycle (4-Step Cycle)

MANDATORY EXECUTION CYCLE: task-executor-frontend → escalation check → quality-fixer-frontend → commit

For EACH task in the Consumed Task Set, YOU MUST:

  1. Register tasks using TaskCreate: Register work steps. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON"
  2. Agent tool (subagent_type: "dev-workflows-fullstack:task-executor-frontend") → Pass task file path in prompt, receive structured response
  3. CHECK task-executor-frontend response:
    • status: "escalation_needed" or "blocked" → STOP and escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 2 with requiredFixes
      • approved → Proceed to step 4
    • readyForQualityCheck: true → Proceed to step 4
  4. INVOKE quality-fixer-frontend: Execute all quality checks and fixes. Always pass the current task file path as task_file
  5. CHECK quality-fixer-frontend response:
    • stub_detected → Return to step 2 with incompleteImplementations[] details
    • blocked → STOP and escalate to user
    • approved → Proceed to step 6
  6. COMMIT on approval: Execute git commit

CRITICAL: Parse every sub-agent response for status fields. Execute the matching branch in the 4-step cycle. Proceed to next task only after quality-fixer-frontend returns approved.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Verify task files exist per Pre-execution Checklist, then enter autonomous execution mode. When requirement changes are detected during execution, escalate to the user with the change summary before continuing.

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows-fullstack:code-verifier") → doc_type: design-doc, Design Doc path, code_paths: implementation file list (git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows-fullstack:security-reviewer") → Design Doc path, implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute task-executor-frontend with consolidated fixes → quality-fixer-frontend
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file in the Consumed Task Set
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer for this {plan-name})
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Completion Report Contract

Final report must include:

  • Task decomposition status
  • Implemented task count
  • Quality check result
  • Commit count
  • Cleanup result
  • Escalation or blocking summary, if any
该技能用于前端设计阶段,通过编排子代理执行从代码库分析到设计文档生成的完整流程。包含范围引导、UI分析、技术设计及验证等步骤,并在关键节点暂停以获取用户审批,确保设计质量与一致性。
需要生成前端设计文档 进行前端架构或UI规格设计
dev-workflows-fullstack/skills/recipe-front-design/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-design -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-design",
    "description": "Execute from codebase analysis to frontend design document creation",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the frontend design phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results. The one exception is the Step 1 scope bootstrap, a recipe-local orchestrator task limited to locating seed files.
  2. Run the frontend design flow below in order (this recipe covers medium/large frontend):
    • Execute: scope bootstrap → codebase-analyzer → [Stop: Scope confirmation] → external resource hearing → ui-analyzer → ui-spec-designer → technical-designer-frontend → code-verifier → document-reviewer → design-sync
    • ui-spec-designer, code-verifier, and design-sync apply when the design output is a Design Doc; all are skipped for ADR-only
    • Stop at every [Stop: ...] marker → Wait for user approval before proceeding
  3. Scope: Complete when design documents receive approval

subagents-orchestration-guide usage: Reference the guide only for orchestration principles (Delegation Boundary, Decision precedence, permitted tools), the Scale Determination table, and handoff contracts HC-02 onward. This recipe defines its own start order and subagent prompts. The guide's requirement-analyzer-origin flow, First Action Rule, HC-01, and Call Examples do not apply to this recipe.

CRITICAL: Execute document-reviewer, design-sync (for Design Docs), and all stopping points — each serves as a quality gate. Skipping any step risks undetected inconsistencies.

Workflow Overview

Requirements → scope bootstrap → codebase-analyzer → [Stop: Scope confirmation]
                                                            ↓
                                          external resource hearing (frontend domain)
                                                            ↓
                                                       ui-analyzer
                                                            ↓
                                              ui-spec-designer → [Stop: UI Spec approval]
                                                            ↓
                                              technical-designer-frontend
                                                            ↓
                                              code-verifier → document-reviewer
                                                            ↓
                                                 design-sync → [Stop: Design approval]

Scope Boundaries

Included in this skill:

  • Scope bootstrap: locating seed files so codebase-analyzer receives a populated input
  • Codebase analysis with codebase-analyzer (entry point of the frontend design phase)
  • Scope confirmation with the user, grounded in codebase-analyzer findings
  • External resource hearing per the external-resource-context skill
  • UI fact gathering with ui-analyzer
  • UI Specification creation with ui-spec-designer (prototype code inquiry included)
  • ADR creation (if architecture changes, new technology, or data flow changes)
  • Design Doc creation with technical-designer-frontend
  • Design Doc verification with code-verifier (before document review)
  • Document review with document-reviewer
  • Design Doc consistency verification with design-sync

Responsibility Boundary: This skill completes with frontend design document (UI Spec/ADR/Design Doc) approval. Work planning and beyond are outside scope.

Execution Flow

Requirements: $ARGUMENTS

Step 1: Scope Bootstrap

codebase-analyzer requires a populated requirement_analysis.affectedFiles. Build that seed with a lightweight, orchestrator-local pass — locating files only, with no deep reading and no design decisions:

  1. Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
  2. Search the repository with Bash (rg, or grep when rg is unavailable) for files matching those keywords.
  3. Collect the matched file paths as the seed affectedFiles.
  4. When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as affectedFiles before invoking codebase-analyzer. If the user confirms no related code exists, report that codebase-grounded design does not apply and confirm with the user how to proceed.
  5. When the search returns more than ~20 files: the keywords are too broad for a focused design scope. Present the most relevant candidates to the user (AskUserQuestion) and confirm the seed affectedFiles before invoking codebase-analyzer.

This step locates seed files only. Reading files in full, tracing dependencies, and analysis remain codebase-analyzer's responsibility.

Step 2: Codebase Analysis

Invoke codebase-analyzer with its existing schema. The orchestrator constructs requirement_analysis from the Step 1 seed.

  • Invoke codebase-analyzer using Agent tool
    • subagent_type: "dev-workflows-fullstack:codebase-analyzer", description: "Codebase analysis"
    • prompt: include
      • requirements: the user requirements verbatim
      • requirement_analysis: a JSON object with all four fields — affectedFiles (Step 1 seed), purpose (the user requirements), scale (provisional value from the Scale Determination table applied to the seed file count), technicalConsiderations ({ constraints: [], risks: [], dependencies: [] } — the bootstrap performs no analysis, so the object is present with empty lists)
      • Expected action: analyze the seed files for frontend design guidance (data, contracts, dependencies, quality assurance mechanisms)

Step 3: Scope Confirmation

After codebase-analyzer returns, confirm the design scope with the user before any design work. This is a recipe-local confirmation step. Use AskUserQuestion.

Present, sourced from the codebase-analyzer JSON:

  • Target files/modules: analysisScope.filesAnalyzed and the modules they belong to
  • Affected layers: layers touched, derived from analysisScope.categoriesDetected and focusAreas
  • Unknowns/assumptions: limitations plus any assumptions codebase-analyzer recorded
  • Questions before design: open points that need a user answer before design proceeds

Ask the user to choose one:

  • Proceed to design with this scope — continue to Step 4
  • Correct the scope and re-run — return to Step 1 with the corrected scope; when the user names the corrected files or modules, use those directly as the Step 1 seed instead of re-deriving them by search
  • Hold additional hearing, then proceed — gather the missing answers, then continue to Step 4
  • Produce an ADR — when the confirmed scope involves architecture changes, new technology, or data flow changes, continue through the flow with an ADR as the design document; Step 6 (UI Specification) is skipped for ADR

After the user confirms the scope, count the confirmed target files and set the scale from the subagents-orchestration-guide Scale Determination table. This confirmed scale supersedes the Step 2 provisional value and determines the design document.

[STOP]: Wait for the user's choice before proceeding.

Step 4: External Resource Hearing

Run the hearing protocol per the external-resource-context skill (frontend domain). The orchestrator owns this step because it requires AskUserQuestion. The skill defines file-existence branching, two-phase hearing (structured axes + self-declaration), and persistence to docs/project-context/external-resources.md.

Step 5: UI Fact Gathering

Invoke ui-analyzer to gather UI facts. It reads the project-tier external-resources file, fetches external UI sources via the inherited MCP/URL access methods, then analyzes the UI codebase. Its output complements the codebase-analyzer output from Step 2 (data, contracts, dependencies, quality assurance mechanisms).

  • Invoke ui-analyzer using Agent tool
    • subagent_type: "dev-workflows-fullstack:ui-analyzer", description: "UI fact gathering"
    • prompt: include
      • requirements: the user requirements
      • requirement_analysis: a JSON object with all four fields — affectedFiles (analysisScope.filesAnalyzed from Step 2 codebase-analyzer), purpose (the user requirements), scale (the Step 3 confirmed scale), technicalConsiderations ({ constraints: [], risks: [], dependencies: [] })
      • Expected action: read docs/project-context/external-resources.md, fetch external UI sources via the declared access methods, and analyze the existing UI codebase

Both outputs (codebase-analyzer JSON from Step 2 and ui-analyzer JSON from Step 5) are reused by ui-spec-designer in Step 6 and by technical-designer-frontend in Step 7.

Step 6: UI Specification Phase

When the design document is a Design Doc (this step is skipped for ADR-only): after Step 5 output is received, ask the user about prototype code:

Ask the user: "Do you have prototype code for this feature? If so, please provide the path to the code. The prototype will be placed in docs/ui-spec/assets/ as reference material for the UI Spec."

  • [STOP]: Wait for user response about prototype code availability

Then create the UI Specification:

  • Invoke ui-spec-designer using Agent tool
    • subagent_type: "dev-workflows-fullstack:ui-spec-designer"
    • description: "UI Spec creation"
    • Build the prompt by including:
      • Source: an existing PRD in docs/prd/ when one exists for this feature; otherwise the user requirements with the Step 2 codebase-analyzer JSON and the Step 3 confirmed scope
      • ui_analysis: ui-analyzer JSON from Step 5 (includes externalResources fetched_summary and componentStructure / propsPatterns / cssLayout / etc.)
      • Prototype path when provided
    • Example (existing PRD): prompt: "Create UI Spec from PRD at [path]. ui_analysis: [JSON from Step 5 ui-analyzer]. Prototype code is at [user-provided path]. Place prototype in docs/ui-spec/assets/{feature-name}/."
    • Example (no PRD): prompt: "Create UI Spec from these requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. Confirmed scope: [Step 3 confirmed scope]. ui_analysis: [JSON from Step 5 ui-analyzer]. Prototype code is at [user-provided path]. Place prototype in docs/ui-spec/assets/{feature-name}/."
  • Invoke document-reviewer to verify UI Spec
    • subagent_type: "dev-workflows-fullstack:document-reviewer", description: "UI Spec review", prompt: "doc_type: UISpec target: [ui-spec path] Review for consistency and completeness"
  • [STOP]: Present UI Spec for user approval

Step 7: Design Document Creation Phase

technical-designer-frontend presents at least two architecture alternatives (technology selection, data flow design) with trade-offs for each. Pass the Step 2 codebase-analyzer output and the Step 5 ui-analyzer output:

  • Invoke technical-designer-frontend using Agent tool
    • For ADR: subagent_type: "dev-workflows-fullstack:technical-designer-frontend", description: "ADR creation", prompt: "Create ADR for [technical decision]. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. UI analysis: [ui-analyzer JSON from Step 5]. Confirmed scope: [Step 3 confirmed scope]. Present at least two alternatives with trade-offs."
    • For Design Doc: subagent_type: "dev-workflows-fullstack:technical-designer-frontend", description: "Design Doc creation", prompt: "Create Design Doc based on the requirements. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. UI analysis: [ui-analyzer JSON from Step 5]. UI Spec is at [ui-spec path]. Inherit component structure and state design from UI Spec. Apply code: prefix to codebase-analyzer fact_ids and ui: prefix to ui-analyzer fact_ids when filling the Fact Disposition Table. Present at least two architecture alternatives with trade-offs."
  • (Design Doc only) Invoke code-verifier to verify Design Doc against existing code. Skip for ADR.
    • subagent_type: "dev-workflows-fullstack:code-verifier", description: "Design Doc verification", prompt: "doc_type: design-doc document_path: [Design Doc path] Verify Design Doc against existing code."
  • Invoke document-reviewer to verify consistency (pass code-verifier results for Design Doc; omit for ADR)
    • subagent_type: "dev-workflows-fullstack:document-reviewer", description: "Document review", prompt: "Review [document path] for consistency and completeness. codebase_analysis: [codebase-analyzer JSON from Step 2]. ui_analysis: [ui-analyzer JSON from Step 5]. code_verification: [code verification output from this step] (Design Doc only)"

Step 8: Design Consistency Verification

  • (Design Doc only) Invoke design-sync using Agent tool. Skip for ADR-only.
    • subagent_type: "dev-workflows-fullstack:design-sync", description: "Design consistency check", prompt: "Check consistency across all Design Docs in docs/design/. Report conflicts and overlaps."
  • [STOP]: Present the design document, plus design-sync results for a Design Doc, and obtain user approval

Completion Criteria

  • Built the Step 1 scope bootstrap seed (or obtained target files from the user when the search returned none)
  • Executed codebase-analyzer with a populated requirement_analysis
  • Confirmed the design scope with the user and set the scale from the confirmed target files
  • Executed external resource hearing per the external-resource-context skill (file written or update explicitly skipped by user)
  • Executed ui-analyzer; codebase-analyzer (Step 2) and ui-analyzer (Step 5) outputs reused by ui-spec-designer and technical-designer-frontend
  • Created UI Specification with ui-spec-designer (when applicable) — its External Resources Used section is filled
  • Created appropriate design document (ADR or Design Doc) with technical-designer-frontend — its External Resources Used subsection is filled when present
  • Executed code-verifier on Design Doc and passed results to document-reviewer (skip for ADR-only)
  • Executed document-reviewer and addressed feedback
  • Executed design-sync for consistency verification (skip for ADR-only)
  • Obtained user approval for design document

Output Example

Frontend design phase completed.

  • UI Specification: docs/ui-spec/[feature-name]-ui-spec.md
  • Design document: docs/design/[document-name].md or docs/adr/[document-name].md
  • Approval status: User approved
根据设计文档生成前端工作计划并获取审批。通过协调子代理完成测试骨架生成、计划创建及审查,确保在最终批准前停止执行,适用于前端规划阶段的工作流编排。
用户要求基于设计文档制定前端开发计划 用户请求前端工作流编排或计划审批
dev-workflows-fullstack/skills/recipe-front-plan/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-plan -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-plan",
    "description": "Create frontend work plan from design document and obtain plan approval",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the frontend planning phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
  2. Follow subagents-orchestration-guide skill planning flow:
    • Execute steps defined below
    • Stop and obtain approval for plan content before completion
  3. Scope: See Scope Boundaries below

CRITICAL: When the user requests test generation, always execute acceptance-test-generator first — it provides the test skeleton that work-planner depends on.

Scope Boundaries

Included in this skill:

  • Design document selection
  • Test skeleton generation with acceptance-test-generator
  • Work plan creation with work-planner
  • Work plan review with document-reviewer
  • Plan approval obtainment

Responsibility Boundary: This skill completes with work plan approval.

Follow the planning process below:

Execution Process

Step 1: Design Document Selection

! ls -la docs/design/*.md | head -10

  • Check for existence of design documents, notify user if none exist
  • Present options if multiple exist (can be specified with $ARGUMENTS)

Step 2: Test Skeleton Generation Confirmation

  • Confirm with user whether to generate test skeletons (integration + fixture-e2e + service-integration-e2e) first
  • If user wants generation: acceptance-test-generator generates skeletons across all applicable lanes
    • Invoke acceptance-test-generator using Agent tool:
      • subagent_type: "dev-workflows-fullstack:acceptance-test-generator"
      • description: "Test skeleton generation"
      • If UI Spec exists: prompt: "Generate test skeletons from Design Doc at [path]. UI Spec at [ui-spec path]."
      • If no UI Spec: prompt: "Generate test skeletons from Design Doc at [path]."
  • Pass integration test file path, fixture-e2e and service-integration-e2e file paths (or null per lane), and e2eAbsenceReason (per lane) to work-planner according to subagents-orchestration-guide "acceptance-test-generator → work-planner" section

Step 3: Work Plan Creation

Invoke work-planner using Agent tool:

  • subagent_type: "dev-workflows-fullstack:work-planner"

  • description: "Work plan creation"

  • If test skeletons were generated in Step 2, build the prompt by listing every lane's status:

    • Always include: "Integration test file: [path or 'not generated']"
    • For each E2E lane (fixtureE2e, serviceE2e):
      • When generatedFiles.<lane> is not null: "[lane] test file: [path]"
      • When generatedFiles.<lane> is null: "No [lane] skeleton generated (reason: [e2eAbsenceReason.])"
    • Append placement guidance: "Integration tests are created simultaneously with each phase implementation. fixture-e2e tests are created alongside the UI feature phase. service-integration-e2e tests are executed only in the final phase."
  • If test skeletons were not generated: prompt: "Create work plan from Design Doc at [path]."

  • Follow subagents-orchestration-guide Prompt Construction Rule for additional prompt parameters

Step 4: Work Plan Review

Invoke document-reviewer to review the work plan:

  • subagent_type: "dev-workflows-fullstack:document-reviewer"
  • description: "Work plan review"
  • prompt: "doc_type: WorkPlan target: docs/plans/[plan-name].md. Review semantic traceability to the Design Doc, early verification placement, real-boundary verification coverage, Failure Mode Checklist, and Review Scope."
  • The work plan is a derivation of the Design Doc, so plan-fidelity findings are resolved without user input. Branch on the reviewer's verdict.decision: on needs_revision, re-invoke work-planner in update mode with the findings and re-review, repeating until approved or approved_with_conditions. On rejected, escalate to the user.

Step 5: Present for Approval

  • Present the reviewed work plan to the user for batch approval. If the user requests changes, re-invoke work-planner with revised parameters and re-run Step 4.
  • Highlight steps with unclear scope or external dependencies and ask the user to confirm

Response at Completion

Recommended: End with the following standard response after plan content approval

Frontend planning phase completed.
- Work plan: docs/plans/[plan-name].md
- Status: Approved

Please provide separate instructions for implementation.
针对React/TypeScript前端的实现后质量保证技能。通过代码审查员和安全审查员验证设计文档合规性与安全性,根据结果自动选择代码修复或设计文档更新路径,确保项目质量与安全标准。
需要验证前端代码与设计文档的一致性时 执行前端实施后的质量和安全审计时 发现代码与设计文档存在差异需决定修复方向时
dev-workflows-fullstack/skills/recipe-front-review/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-review -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-review",
    "description": "Design Doc compliance and security validation with optional auto-fixes",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Post-implementation quality assurance for React/TypeScript frontend

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

First Action: Register Steps 1-11 using TaskCreate before any execution.

Execution Method

  • Compliance validation → performed by code-reviewer
  • Security validation → performed by security-reviewer
  • Code-side fix path: Fix implementation → task-executor-frontend; Quality checks → quality-fixer-frontend; Re-validation → code-reviewer / security-reviewer
  • Design-side update path: DD revision → technical-designer-frontend (update mode); DD review → document-reviewer; cross-DD consistency → design-sync (when multiple DDs exist); Re-validation → code-reviewer

The design-side path applies when the discrepancy reflects code that was correct but the Design Doc became stale, rather than code that violated the Design Doc.

Design Doc (uses most recent if omitted): $ARGUMENTS

Execution Flow

Step 1: Prerequisite Check

# Identify Design Doc
ls docs/design/*.md | grep -v template | tail -1

# Check implementation files
git diff --name-only main...HEAD

Step 2: Execute code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows-fullstack:code-reviewer"
  • description: "Code compliance review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review mode: full. Validate Design Doc compliance and return structured JSON report."

Store output as: $STEP_2_OUTPUT

Step 3: Execute security-reviewer

Invoke security-reviewer using Agent tool:

  • subagent_type: "dev-workflows-fullstack:security-reviewer"
  • description: "Security review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review security compliance."

Store output as: $STEP_3_OUTPUT

Step 4: Verdict and Response

If security-reviewer returned blocked: Stop immediately. Report the blocked finding and escalate to user. Do not proceed to fix steps.

Code compliance criteria (considering project stage):

  • Prototype: Pass at 70%+
  • Production: 90%+ recommended

Security criteria:

  • approved or approved_with_notes → Pass
  • needs_revision → Fail

Report both results independently using subagent output fields only:

Before presenting to the user, the orchestrator computes a recommended route per finding using the rule below (this rule is internal — do not include it in the user-facing prompt):

Finding pattern Recommended route
dd_violation where the code intent matches the original requirement but the Design Doc captured a different design d (Design-side update)
dd_violation where the code drifted from a still-correct Design Doc c (Code-side fix)
reliability / security / maintainability findings c (Code-side fix)

Then present to the user (label each finding with its recommended route, grouped by route):

Code Compliance: [complianceRate from code-reviewer]
  Verdict: [verdict from code-reviewer]
  Identifier Match Rate: [identifierMatchRate from code-reviewer]
  Acceptance Criteria:
  - [fulfilled] [item] (confidence: [high/medium/low])
  - [partially_fulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  - [unfulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  Identifier Mismatches:
  - [identifier]: DD=[designDocValue] Code=[codeValue] at [location] [recommended: c | d]
  Quality Findings:
  - [category] [location]: [description] — [rationale] [recommended: c]

Security Review: [status from security-reviewer]
  Findings by category:
  - [confirmed_risk] [location]: [description] — [rationale] [recommended: c]
  - [defense_gap] [location]: [description] — [rationale] [recommended: c]
  - [hardening] [location]: [description] — [rationale] [recommended: c]
  - [policy] [location]: [description] — [rationale] [recommended: c]
  Notes: [notes from security-reviewer, if present]

Resolve discrepancies — confirm or override the recommended route per finding:
  c) Code-side fix       — code violates Design Doc; modify code to match
  d) Design-side update  — code is correct; Design Doc is stale, revise it
  s) Skip                — accept current state without changes

Use AskUserQuestion. The default offer is "accept all recommended routes" — a single confirmation for the typical case where the orchestrator's recommendations are correct. When the user wants to override, collect per-finding c/d/s decisions instead. If the user selects s for everything: skip Steps 5-10, proceed to Step 11.

Step 5: Execute Skill

Execute Skill: documentation-criteria (for task file template)

Step 5d: Design-Side Update

Run this step only when the user routed at least one finding to d. When all routes are c or s, skip directly to Step 6.

  1. Invoke technical-designer-frontend in update mode using Agent tool:

    • subagent_type: "dev-workflows-fullstack:technical-designer-frontend"
    • description: "Design Doc update from review findings"
    • prompt: "Update Design Doc at [path] in update mode. The implementation has diverged in the following ways that the team has decided to ratify in the design rather than in the code: [list of d-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
  2. Invoke document-reviewer to verify the updated Design Doc:

    • subagent_type: "dev-workflows-fullstack:document-reviewer"
    • description: "Document review of updated Design Doc"
    • prompt: "Review updated Design Doc at [path] for consistency and completeness."
  3. When multiple Design Docs exist (ls docs/design/*.md | grep -v template | wc -l > 1), invoke design-sync:

    • subagent_type: "dev-workflows-fullstack:design-sync"
    • description: "Cross-DD consistency check"
    • prompt: "source_design: [updated DD path]. Detect conflicts across all Design Docs after the update."
    • When sync_status: conflicts_found: present conflicts to the user; resolution requires re-invoking technical-designer-frontend for affected DDs.
  4. After Step 5d completes:

    • If the user selected d for all findings (no c routes) → skip Steps 6-8, proceed to Step 9 for re-validation
    • If the user selected both d and c → re-evaluate the c-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remaining c findings

Step 6: Create Task File

Create task file at docs/plans/tasks/review-fixes-YYYYMMDD.md Include both code compliance issues and security requiredFixes.

Step 7: Execute Fixes

Invoke task-executor-frontend using Agent tool:

  • subagent_type: "dev-workflows-fullstack:task-executor-frontend"
  • description: "Execute review fixes"
  • prompt: "Task file: docs/plans/tasks/review-fixes-YYYYMMDD.md. Apply staged fixes (stops at 5 files)."

Step 8: Quality Check

Invoke quality-fixer-frontend using Agent tool:

  • subagent_type: "dev-workflows-fullstack:quality-fixer-frontend"
  • description: "Quality gate check"
  • prompt: "Confirm quality gate passage for fixed files."

Step 9: Re-validate code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows-fullstack:code-reviewer"
  • description: "Re-validate compliance"
  • prompt: "Re-validate Design Doc compliance after fixes. Design Doc: [path]. Implementation files: [file list]. Prior compliance issues: $STEP_2_OUTPUT. Verify each prior issue is resolved (whether resolved code-side or design-side)."

Step 10: Re-validate security-reviewer

Invoke security-reviewer using Agent tool (only if security fixes were applied):

  • subagent_type: "dev-workflows-fullstack:security-reviewer"
  • description: "Re-validate security"
  • prompt: "Re-validate security after fixes. Prior findings: $STEP_3_OUTPUT. Design Doc: [path]. Implementation files: [file list]."

Step 11: Final Cleanup and Report

Delete the review-fix task file this recipe created (if any). Its work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete docs/plans/tasks/review-fixes-YYYYMMDD.md if it exists

If the file cannot be deleted (filesystem error), report the failure but do not block the final report.

Then present the final report:

Code Compliance:
  Initial: [X]%
  Final: [Y]% (if fixes executed)

Security Review:
  Initial: [status]
  Final: [status] (if fixes executed)
  Notes: [notes from approved_with_notes, if any]

Remaining issues:
- [items requiring manual intervention]

Cleanup: review-fixes task file removed

Auto-fixable Items (code-side path)

  • Simple unimplemented acceptance criteria
  • Error handling additions
  • Contract definition fixes
  • Function splitting (length/complexity improvements)
  • Security confirmed_risk and defense_gap fixes (input validation, auth checks, output encoding)

Non-fixable Items

  • Fundamental business logic changes
  • Architecture-level modifications
  • Committed secrets (blocked → human intervention)

Design-Side Update Triggers

Discrepancies suitable for the design-side path (code is correct, DD became stale):

  • Identifier renames where the new identifier reflects the team's current naming
  • Behavioral changes that match the original requirement intent better than what the DD captured
  • Component splits or merges where the new structure is sound and the DD documented the prior structure
  • New ACs that the implementation already satisfies but the DD never enumerated

Scope: Design Doc compliance validation, security review, code-side auto-fixes, and design-side update routing.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the review scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.
全栈任务编排技能,通过智能路由将后端和前端任务分配给对应子代理。严格遵循工作流解析、四层执行周期及质量修复流程,实现自动化构建与提交。
需要执行分解后的全栈开发任务 用户指令包含现有任务文件且需批量处理 涉及前后端分离的代码生成与质量修复
dev-workflows-fullstack/skills/recipe-fullstack-build/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-fullstack-build -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-fullstack-build",
    "description": "Execute decomposed fullstack tasks with layer-aware agent routing",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Required Reference

MANDATORY: Read references/monorepo-flow.md from subagents-orchestration-guide skill BEFORE proceeding. Follow the Extended Task Cycle and Agent Routing defined there.

Execution Protocol

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Route agents by task filename pattern (see monorepo-flow.md reference):
    • *-backend-task-* → task-executor + quality-fixer
    • *-frontend-task-* → task-executor-frontend + quality-fixer-frontend
  3. Follow the 4-step task cycle exactly: executor → escalation check → quality-fixer → commit
  4. Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
  5. Scope: Complete when all tasks are committed or escalation occurs

CRITICAL: Run layer-appropriate quality-fixer(s) before every commit.

Work plan: $ARGUMENTS

Pre-execution Prerequisites

Work Plan Resolution

Before any task processing, locate the work plan. Resolution rule:

  1. List task files in docs/plans/tasks/ matching the layer-aware patterns {plan-name}-backend-task-*.md and {plan-name}-frontend-task-*.md only. Single-layer tasks ({plan-name}-task-*.md) are excluded here so a stale single-layer run does not redirect this recipe to the wrong work plan
  2. From the matched files, also exclude every file matching any of these patterns — they originate from other workflow phases and are not implementation tasks for this run's plan: *-task-prep-*.md (readiness preflight tasks), _overview-*.md (decomposition overview file), *-phase*-completion.md (per-phase completion files), review-fixes-*.md (post-implementation review fixes), integration-tests-*-task-*.md (integration-test add-on scaffolding)
  3. For each remaining file, extract the {plan-name} prefix as the segment that appears before -backend-task- or -frontend-task-
  4. When at least one task file matches, the work plan is docs/plans/{plan-name}.md for the prefix that has the most recent task-file mtime; ties broken by the lexicographically last {plan-name}
  5. When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template .md in docs/plans/

Consumed Task Set

Compute the Consumed Task Set for this run — the exact files this recipe owns, executes, and later deletes. Use the same restricted pattern as Work Plan Resolution:

  1. List task files in docs/plans/tasks/ matching the layer-aware patterns {plan-name}-backend-task-*.md and {plan-name}-frontend-task-*.md for the {plan-name} resolved by Work Plan Resolution. Single-layer tasks are excluded
  2. Exclude every file matching: *-task-prep-*.md, _overview-*.md, *-phase*-completion.md, review-fixes-*.md, integration-tests-*-task-*.md (these originate from other workflow phases)

Every subsequent reference to "task files" in this recipe — Task Generation Decision Flow, Task Execution Cycle iteration, and Final Cleanup — uses this set, not the unrestricted docs/plans/tasks/*.md glob.

Task Generation Decision Flow

Analyze the Consumed Task Set and determine the action required:

State Criteria Next Action
Tasks exist Consumed Task Set is non-empty User's execution instruction serves as batch approval → Enter autonomous execution immediately
No tasks + plan exists Consumed Task Set is empty but the resolved work plan exists Confirm with user → run task-decomposer
Neither exists + Design Doc exists No plan, no Consumed Task Set, but docs/design/*.md exists Invoke work-planner to create work plan from Design Doc(s), then run document-reviewer (dev-workflows-fullstack:document-reviewer, doc_type: WorkPlan); branch on the reviewer's verdict.decision — on needs_revision, re-invoke work-planner (update) and re-review until approved/approved_with_conditions, then present the reviewed plan for batch approval before task decomposition; on rejected, stop before task decomposition and escalate to the user
Neither exists No plan, no Consumed Task Set, no Design Doc Report missing prerequisites to user and stop

Task Decomposition Phase (Conditional)

When the Consumed Task Set is empty:

1. User Confirmation

No task files in the Consumed Task Set.
Work plan: docs/plans/[plan-name].md

Generate tasks from the work plan? (y/n):

2. Task Decomposition (if approved)

Invoke task-decomposer using Agent tool:

  • subagent_type: "dev-workflows-fullstack:task-decomposer"
  • description: "Decompose work plan"
  • prompt: "Read work plan at docs/plans/[plan-name].md and decompose into atomic tasks. Output: Individual task files in docs/plans/tasks/. Granularity: 1 task = 1 commit = independently executable. Use layer-aware naming: {plan}-backend-task-{n}.md, {plan}-frontend-task-{n}.md based on Target files paths."

3. Verify Generation

Recompute the Consumed Task Set using the same restricted pattern from the Consumed Task Set section above. Confirm it is now non-empty. If it is still empty, escalate to the user — task-decomposer either failed silently or produced files that don't match the expected pattern.

Pre-execution Checklist

  • Confirmed Consumed Task Set is non-empty (computed in the Consumed Task Set section above)
  • Identified task execution order within the Consumed Task Set (dependencies)
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Task Execution Cycle (Filename-Pattern-Based)

MANDATORY: For each task in the Consumed Task Set, route agents by task filename pattern from monorepo-flow.md reference.

Agent Routing Table

Filename Pattern Executor Quality Fixer
*-backend-task-* dev-workflows-fullstack:task-executor dev-workflows-fullstack:quality-fixer
*-frontend-task-* dev-workflows-fullstack:task-executor-frontend dev-workflows-fullstack:quality-fixer-frontend
*-task-* (no layer prefix) dev-workflows-fullstack:task-executor dev-workflows-fullstack:quality-fixer (default)

Task Execution (4-Step Cycle)

For EACH task, YOU MUST:

  1. Register tasks using TaskCreate: Register work steps. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON"
  2. Agent tool (subagent_type per routing table) → Pass task file path in prompt, receive structured response
  3. CHECK executor response:
    • status: "escalation_needed" or "blocked" → STOP and escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 2 with requiredFixes
      • approved → Proceed to step 4
    • readyForQualityCheck: true → Proceed to step 4
  4. INVOKE quality-fixer: Execute all quality checks and fixes (layer-appropriate per routing table). Always pass the current task file path as task_file
  5. CHECK quality-fixer response:
    • stub_detected → Return to step 2 with incompleteImplementations[] details
    • blocked → STOP and escalate to user
    • approved → Proceed to step 6
  6. COMMIT on approval: Execute git commit

CRITICAL: Parse every sub-agent response for status fields. Execute the matching branch in the 4-step cycle. Proceed to next task only after layer-appropriate quality-fixer returns approved.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Verify task files exist per Pre-execution Checklist, then enter autonomous execution mode. When requirement changes are detected during execution, escalate to the user with the change summary before continuing.

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows-fullstack:code-verifier") → invoke once per Design Doc (doc_type: design-doc, single document_path, code_paths: implementation file list from git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows-fullstack:security-reviewer") → Design Doc path(s), implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute layer-appropriate task-executor with consolidated fixes → quality-fixer
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file in the Consumed Task Set
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer for this {plan-name})
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Completion Report Contract

Final report must include:

  • Task decomposition status
  • Implemented task count, including backend/frontend counts
  • Quality check result
  • Commit count
  • Cleanup result
  • Escalation or blocking summary, if any
全栈实施编排技能,管理从需求到QA的全周期。通过子代理协调前后端,遵循monorepo流程进行设计、规划与实现。支持新需求启动、流程延续及错误修复,确保跨层一致性与结构化交付。
需要执行全栈功能开发或重构 请求启动或继续复杂的全栈项目工作流 涉及前后端协同的设计与实施任务
dev-workflows-fullstack/skills/recipe-fullstack-implement/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-fullstack-implement -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-fullstack-implement",
    "description": "Orchestrate full-cycle implementation across backend and frontend layers",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Full-cycle fullstack implementation management (Requirements Analysis → Design (backend + frontend) → Planning → Implementation → Quality Assurance)

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Required Reference

MANDATORY: Read references/monorepo-flow.md from subagents-orchestration-guide skill BEFORE proceeding. Follow the Fullstack Flow defined there instead of the standard single-layer flow.

Execution Protocol

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Follow monorepo-flow.md for the design phase (multiple Design Docs, design-sync, vertical slicing)
  3. Follow subagents-orchestration-guide skill for all other orchestration rules (stop points, structured responses, escalation)
  4. Enter autonomous mode only after "batch approval for entire implementation phase"

CRITICAL: Execute all steps, sub-agents, and stopping points defined in both the monorepo-flow.md reference and subagents-orchestration-guide skill.

Execution Decision Flow

1. Current Situation Assessment

Instruction Content: $ARGUMENTS

Assess the current situation:

Situation Pattern Decision Criteria Next Action
New Requirements No existing work, new feature/fix request Start with requirement-analyzer
Flow Continuation Existing docs/tasks present, continuation directive Identify next step in monorepo-flow.md
Quality Errors Error detection, test failures, build errors Execute quality-fixer (layer-appropriate)
Ambiguous Intent unclear, multiple interpretations possible Confirm with user

2. Progress Verification for Continuation

When continuing existing flow, verify:

  • Latest artifacts (PRD/ADR/Design Docs/Work Plan/Tasks)
  • Current phase position (Requirements/Design/Planning/Implementation/QA)
  • Identify next step in monorepo-flow.md

3. Design through Planning Phase

Follow monorepo-flow.md for the complete design-through-planning flow (Steps 1-16 for Large scale, Steps 1-14 for Medium scale). The flow table in that reference defines every step, agent invocation, parallelization rule, and stop point.

Key points to enforce as the orchestrator runs the flow:

  • Create separate Design Docs per layer (see monorepo-flow.md "Layer Context in Design Doc Creation")
  • Frontend Design Doc references the approved UI Spec (pass UI Spec path to technical-designer-frontend) and reuses the ui-analyzer output produced earlier in the flow
  • Execute document-reviewer once per Design Doc (separate invocations)
  • Run design-sync for cross-layer consistency verification
  • Pass all Design Docs to work-planner (subagent_type: "dev-workflows-fullstack:work-planner") with vertical slicing instruction

4. Register All Flow Steps Using TaskCreate (MANDATORY)

After scale determination, register all steps of the monorepo-flow.md using TaskCreate:

  • First task: "Map preloaded skills to applicable concrete rules"
  • Register each step as individual task
  • Set currently executing step to in_progress using TaskUpdate
  • Complete task registration before invoking subagents

After requirement-analyzer [Stop]

When user responds to questions:

  • If response matches any scopeDependencies.question → Check impact for scale change
  • If scale changes → Re-execute requirement-analyzer with updated context
  • If confidence: "confirmed" or no scale change → Proceed to next step

Subagents Orchestration Guide Compliance Execution

Pre-execution Checklist (MANDATORY):

  • Read monorepo-flow.md reference
  • Confirmed relevant flow steps
  • Identified current progress position
  • Clarified next step
  • Recognized stopping points
  • codebase-analyzer included before each Design Doc creation
  • code-verifier included before document-reviewer for each Design Doc
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Required Flow Compliance:

  • Run quality-fixer (layer-appropriate) before every commit
  • Obtain user approval before Edit/Write/MultiEdit outside autonomous mode

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Mandatory Orchestrator Responsibilities

Task Execution Quality Cycle (Filename-Pattern-Based)

Agent routing by task filename (see monorepo-flow.md reference):

*-backend-task-*   → dev-workflows-fullstack:task-executor + dev-workflows-fullstack:quality-fixer
*-frontend-task-*  → dev-workflows-fullstack:task-executor-frontend + dev-workflows-fullstack:quality-fixer-frontend

Rules:

  1. Execute ONE task completely before starting next (each task goes through the full 4-step cycle via Agent tool, using the correct executor per filename pattern)
  2. Check executor status before quality-fixer (escalation check)
  3. Quality-fixer MUST run after each executor before proceeding to commit. Always pass the current task file path as task_file
  4. Check quality-fixer response:
    • stub_detected → Return to executor with incompleteImplementations[] details
    • blocked → Escalate to user
    • approved → Proceed to commit

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows-fullstack:code-verifier") → invoke once per Design Doc (doc_type: design-doc, single document_path, code_paths: implementation file list from git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows-fullstack:security-reviewer") → Design Doc path(s), implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute layer-appropriate task-executor with consolidated fixes → quality-fixer
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file matching docs/plans/tasks/{plan-name}-backend-task-*.md and docs/plans/tasks/{plan-name}-frontend-task-*.md (the {plan-name} derived from the work plan path used in this run)
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer)
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Test Information Communication

After acceptance-test-generator execution, when invoking work-planner (subagent_type: "dev-workflows-fullstack:work-planner"), communicate:

  • Generated integration test file path (from generatedFiles.integration)
  • Generated fixture-e2e test file path or null (from generatedFiles.fixtureE2e)
  • Generated service-integration-e2e test file path or null (from generatedFiles.serviceE2e)
  • Per-lane E2E absence reason (from e2eAbsenceReason.fixtureE2e and e2eAbsenceReason.serviceE2e, when each lane is null)
  • Explicit note: integration tests are created simultaneously with implementation, fixture-e2e tests are created alongside the UI feature phase, service-integration-e2e tests are executed only in the final phase

Execution Method

All work is executed through sub-agents. Sub-agent selection follows monorepo-flow.md reference and subagents-orchestration-guide skill.

全周期实施编排技能,管理从需求到部署的流程。通过子代理协调分析、设计、计划、实现及质检步骤,严格遵循流程指南,在关键节点暂停确认,确保高质量交付。
启动新功能或修复请求的实施 继续已有的项目实施流程 处理质量错误、测试失败或构建错误
dev-workflows-fullstack/skills/recipe-implement/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-implement -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-implement",
    "description": "Orchestrate the complete implementation lifecycle from requirements to deployment",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Full-cycle implementation management (Requirements Analysis → Design → Planning → Implementation → Quality Assurance)

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Follow subagents-orchestration-guide skill flows exactly:
    • Execute one step at a time in the defined flow (Large/Medium/Small scale)
    • When flow specifies "Execute document-reviewer" → Execute it immediately
    • Stop at every [Stop: ...] marker → Use AskUserQuestion for confirmation and wait for approval before proceeding
  3. Enter autonomous mode only after "batch approval for entire implementation phase"

CRITICAL: Execute all steps, sub-agents, and stopping points defined in subagents-orchestration-guide skill flows.

Execution Decision Flow

1. Current Situation Assessment

Instruction Content: $ARGUMENTS

Assess the current situation:

Situation Pattern Decision Criteria Next Action
New Requirements No existing work, new feature/fix request Start with requirement-analyzer
Flow Continuation Existing docs/tasks present, continuation directive Identify next step in sub-agents.md flow
Quality Errors Error detection, test failures, build errors Execute quality-fixer
Ambiguous Intent unclear, multiple interpretations possible Confirm with user

2. Progress Verification for Continuation

When continuing existing flow, verify:

  • Latest artifacts (PRD/ADR/Design Doc/Work Plan/Tasks)
  • Current phase position (Requirements/Design/Planning/Implementation/QA)
  • Identify next step in subagents-orchestration-guide skill corresponding flow

3. Next Action Execution

MANDATORY subagents-orchestration-guide skill reference:

  • Verify scale-based flow (Large/Medium/Small scale)
  • Confirm autonomous execution mode conditions
  • Recognize mandatory stopping points
  • Invoke next sub-agent defined in flow

After requirement-analyzer [Stop]

When user responds to questions:

  • If response matches any scopeDependencies.question → Check impact for scale change
  • If scale changes → Re-execute requirement-analyzer with updated context
  • If confidence: "confirmed" or no scale change → Proceed to next step

4. Register All Flow Steps Using TaskCreate (MANDATORY)

After scale determination, register all steps of the applicable flow using TaskCreate:

  • First task: "Map preloaded skills to applicable concrete rules"
  • Register each step as individual task
  • Set currently executing step to in_progress using TaskUpdate
  • Complete task registration before invoking subagents

Subagents Orchestration Guide Compliance Execution

Pre-execution Checklist (MANDATORY):

  • Confirmed relevant subagents-orchestration-guide skill flow
  • Identified current progress position
  • Clarified next step
  • Recognized stopping points
  • codebase-analyzer included before Design Doc creation (Medium/Large scale)
  • code-verifier included before document-reviewer for Design Doc review (Medium/Large scale)
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Required Flow Compliance:

  • Run quality-fixer before every commit
  • Obtain user approval before Edit/Write/MultiEdit outside autonomous mode

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Mandatory Orchestrator Responsibilities

Task Execution Quality Cycle (4-Step Cycle per Task)

Per-task cycle (complete each task before starting next):

  1. Agent tool (subagent_type: "dev-workflows-fullstack:task-executor") → Pass task file path in prompt, receive structured response
  2. Check task-executor response:
    • status: escalation_needed or blocked → Escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 1 with requiredFixes
      • approved → Proceed to step 3
    • Otherwise → Proceed to step 3
  3. quality-fixer → Quality check and fixes. Always pass the current task file path as task_file
    • stub_detected → Return to step 1 with incompleteImplementations[] details
    • blocked → Escalate to user
    • approved → Proceed to step 4
  4. git commit → Execute with Bash (on approved)

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows-fullstack:code-verifier") → doc_type: design-doc, Design Doc path, code_paths: implementation file list (git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows-fullstack:security-reviewer") → Design Doc path, implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute task-executor with consolidated fixes → quality-fixer
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file matching docs/plans/tasks/{plan-name}-task-*.md (the {plan-name} derived from the work plan path used in this run)
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer)
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Test Information Communication

After acceptance-test-generator execution, when invoking work-planner (subagent_type: "dev-workflows-fullstack:work-planner"), communicate:

  • Generated integration test file path (from generatedFiles.integration)
  • Generated fixture-e2e test file path or null (from generatedFiles.fixtureE2e)
  • Generated service-integration-e2e test file path or null (from generatedFiles.serviceE2e)
  • Per-lane E2E absence reason (from e2eAbsenceReason.fixtureE2e and e2eAbsenceReason.serviceE2e, when each lane is null)
  • Explicit note: integration tests are created simultaneously with implementation, fixture-e2e tests are created alongside the UI feature phase, service-integration-e2e tests are executed only in the final phase

Execution Method

All work is executed through sub-agents. Sub-agent selection follows subagents-orchestration-guide skill.

该技能用于基于设计文档创建工作执行计划并获取审批。它协调子代理完成设计文档选择、测试骨架生成、计划创建与审查,最终在获得用户批准前停止,确保规划流程规范且可追溯。
需要基于设计文档制定详细的工作执行计划 请求生成工作流规划并获得管理层或用户的正式批准
dev-workflows-fullstack/skills/recipe-plan/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-plan -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-plan",
    "description": "Create work plan from design document and obtain plan approval",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the planning phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
  2. Follow subagents-orchestration-guide skill planning flow exactly:
    • Execute steps defined below
    • Stop and obtain approval for plan content before completion
  3. Scope: See Scope Boundaries below

CRITICAL: When the user requests test generation, always execute acceptance-test-generator first — it provides the test skeleton that work-planner depends on.

Scope Boundaries

Included in this skill:

  • Design document selection
  • Test skeleton generation with acceptance-test-generator
  • Work plan creation with work-planner
  • Work plan review with document-reviewer
  • Plan approval obtainment

Responsibility Boundary: This skill completes with work plan approval.

Follow the planning process below:

Execution Process

Step 1: Design Document Selection

! ls -la docs/design/*.md | head -10

  • Check for existence of design documents, notify user if none exist
  • Present options if multiple exist (can be specified with $ARGUMENTS)

Step 2: Test Skeleton Generation Confirmation

  • Confirm with user whether to generate test skeletons (integration + E2E lanes) first
  • If user wants generation: invoke acceptance-test-generator
  • Pass generation results to next process according to subagents-orchestration-guide skill coordination specification

Step 3: Work Plan Creation

Invoke work-planner using Agent tool:

  • subagent_type: "dev-workflows-fullstack:work-planner"

  • description: "Work plan creation"

  • If test skeletons were generated in Step 2, build the prompt by listing every lane's status:

    • Always include: "Integration test file: [path or 'not generated']"
    • For each E2E lane (fixtureE2e, serviceE2e):
      • When generatedFiles.<lane> is not null: "[lane] test file: [path]"
      • When generatedFiles.<lane> is null: "No [lane] skeleton generated (reason: [e2eAbsenceReason.])"
    • Append placement guidance: "Integration tests are created simultaneously with each phase implementation. fixture-e2e tests are created alongside the UI feature phase. service-integration-e2e tests are executed only in the final phase."
  • If test skeletons were not generated: prompt: "Create work plan from Design Doc at [path]."

  • Follow subagents-orchestration-guide Prompt Construction Rule for additional prompt parameters

Step 4: Work Plan Review

Invoke document-reviewer to review the work plan:

  • subagent_type: "dev-workflows-fullstack:document-reviewer"
  • description: "Work plan review"
  • prompt: "doc_type: WorkPlan target: docs/plans/[plan-name].md. Review semantic traceability to the Design Doc, early verification placement, real-boundary verification coverage, Failure Mode Checklist, and Review Scope."
  • The work plan is a derivation of the Design Doc, so plan-fidelity findings are resolved without user input. Branch on the reviewer's verdict.decision: on needs_revision, re-invoke work-planner in update mode with the findings and re-review, repeating until approved or approved_with_conditions. On rejected, escalate to the user.

Step 5: Present for Approval

  • Present the reviewed work plan to the user for batch approval. If the user requests changes, re-invoke work-planner with revised parameters and re-run Step 4.
  • Highlight steps with unclear scope or external dependencies and ask the user to confirm

Response at Completion

Recommended: After plan approval, output the standard block below.

Planning phase completed.
- Work plan: docs/plans/[plan-name].md
- Status: Approved

Please provide separate instructions for implementation.

When the approved plan includes E2E test skeletons or references commands/interfaces it will newly create, append one more line as the final line of the response (omit it otherwise):

Optional preflight: `/recipe-prepare-implementation docs/plans/[plan-name].md` verifies these are implementable before build (exits no-op if all resolve).
在工作计划进入构建阶段前,验证端到端可实施性。检查验证策略、E2E环境及UI组件就绪情况,自动修复缺口或无操作退出,确保从第一阶段起即可观测。
提及实现准备就绪或验证就绪 工作流涉及未预检的工作计划且即将开始构建
dev-workflows-fullstack/skills/recipe-prepare-implementation/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-prepare-implementation -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-prepare-implementation",
    "description": "Verifies the work plan is implementable end-to-end and resolves verification-lane \/ fixture \/ E2E-environment gaps before the build phase begins. Use when \"implement-ready\/verification readiness\/lane setup\/E2E environment missing\" is mentioned, or before any build phase begins on a work plan whose readiness has not been preflight-checked.",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Optional readiness phase between work-plan approval and recipe-*-build. Confirms the implementation will be observable from Phase 1 onward and resolves any gaps via Phase 0 tasks. Exits no-op when the readiness criteria already pass, so the recipe is safe to invoke unconditionally.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Self-contained scope: When gaps are found, this recipe BOTH generates resolution tasks AND executes them through the standard 4-step cycle. Recipe completes only when readiness criteria pass or remaining gaps are escalated.
  3. No-op exit: When the readiness scan finds no failing criteria, generate no resolution tasks and exit immediately, presenting the Readiness Report to the user. No files are modified in this branch.

Work plan: $ARGUMENTS

When This Recipe Applies

Run before any recipe-*-build invocation when ANY of the following hold:

  • Work plan was created from a Design Doc whose Verification Strategy references commands, files, functions, or endpoints not yet present in the codebase
  • Work plan includes E2E test skeletons (seed data, auth fixture, environment variables, or external mocks may be unaddressed)
  • Work plan touches UI components without a fixture entry or development route to render their visual states
  • The team has not previously confirmed the local lane runs end-to-end for this feature area

When none of the above hold, the readiness scan in Step 2 will find zero failing criteria and the recipe exits no-op (see Context at the top of this skill).

Readiness Criteria

Each criterion is a measurable check producing pass, fail, or not_applicable with cited evidence.

ID Criterion Pass evidence
R1 Verification Strategy references resolve Every command, file path, function, endpoint, and test referenced in the work plan's Verification Strategy section either exists in the codebase (verified via Glob/Grep) or is the deliverable of a task already in this plan
R2 E2E preconditions addressed When E2E skeletons exist: every precondition mentioned in skeleton comments (seed data, auth fixture, env var, external mock) is present in the codebase or covered by a Phase 0 task in this plan
R3 Phase 1 observability The first implementation phase contains at least one task whose Operation Verification Methods can execute at task completion using only artifacts that exist before the task starts (existing code, prior Phase 0 task deliverables, or the task's own outputs)
R4 UI rendering surface When the plan implements UI components: a fixture entry, dev route, Storybook story, or equivalent rendering surface exists for the impacted components, OR a Phase 0 task adds one
R5 Local lane procedure The work plan or a referenced doc records the commands needed to start the system locally for manual verification (start commands, default ports, seed steps)

R4 and R5 are evaluated only when their triggering signals appear in the work plan; otherwise mark not_applicable.

Pre-execution Prerequisites

# Verify the work plan exists
! ls -la docs/plans/*.md | grep -v template | tail -5

State check:

  • Work plan exists → Proceed to Step 1
  • No work plan → Stop and report: "An approved work plan is required. Complete the upstream planning phase first, then re-invoke this recipe."

Execution Flow

Step 1: Load Inputs

Read the work plan path passed in $ARGUMENTS. Extract:

  • Verification Strategy section (Correctness Proof Method + Early Verification Point)
  • Quality Assurance Mechanisms table
  • Design-to-Plan Traceability table
  • Test skeleton references listed in the plan header
  • Phase structure with each phase's tasks
  • Referenced Design Doc(s) and UI Spec (when present)

Step 2: Readiness Scan

For each criterion R1–R5:

  1. Execute the scan defined in Readiness Criteria using Read / Glob / Grep
  2. Record the result: pass / fail / not_applicable
  3. Cite evidence: file:line for pass, the unresolved reference for fail, the missing trigger signal for not_applicable

Build the Readiness Report (see Output Format) regardless of outcome.

Step 3: No-op Check

When every applicable criterion is pass (zero fail):

  • Present the Readiness Report (see Output Format below) to the user
  • Exit with outcome: ready, gaps_resolved: 0
  • No files are modified in this branch

When one or more criteria are fail → proceed to Step 4.

Step 4: Plan Resolution Tasks

For each fail criterion:

  1. Determine the smallest concrete task that closes the gap (examples: "Add fixture entry for ComponentX covering loading/empty/error states", "Add seed script for E2E user fixtures", "Document local startup commands in docs/run/local.md")

  2. Decide the task's layer by matching every target file path against the markers below:

    • backend when every target file path matches one of: **/api/**, **/server/**, **/services/**, **/backend/**, **/handlers/**, **/repositories/**
    • frontend when every target file path matches one of: **/components/**, **/pages/**, **/web/**, **/frontend/**, **/*.tsx, **/*.jsx
    • mixed (target files span both backend and frontend markers) → escalate to user; ask the user to split the gap into per-layer tasks
    • unrecognized (any target file matches neither backend nor frontend markers — e.g., docs/**, scripts/**, root-level configs, fixture data files outside the markers above) → escalate to user; ask the user to either (a) decide which layer's executor / quality-fixer should run the task, or (b) update the markers if the project uses different paths

    Apply the rules in the order above. The first matching rule wins; "unrecognized" is the final fallback rather than a catch-all that defaults to backend.

  3. Create a Phase 0 task file at docs/plans/tasks/{plan-name}-backend-task-prep-{NN}.md (backend) or docs/plans/tasks/{plan-name}-frontend-task-prep-{NN}.md (frontend) using the task template from documentation-criteria skill. The -task-prep- segment lets recipe-prepare-implementation distinguish prep tasks from implementation tasks while keeping the existing {plan-name}-{layer}-task-* matcher used by other recipes

  4. Update the work plan to insert these tasks as Phase 0 (before Phase 1)

Present the proposed resolution task list to the user with AskUserQuestion. Proceed only after explicit approval — this is the single human gate inside this recipe.

Step 5: Execute Resolution Tasks

For each resolution task, run the standard 4-step cycle (see subagents-orchestration-guide "Task Management: 4-Step Cycle"):

  1. Agent tool — route by filename layer segment:
    • *-backend-task-prep-*subagent_type: "dev-workflows-fullstack:task-executor"
    • *-frontend-task-prep-*subagent_type: "dev-workflows-fullstack:task-executor-frontend"
    • Filename without a recognized layer segment → escalate (the file should not exist; Step 4 prevents this)
  2. Check escalation per orchestration-guide
  3. quality-fixer — route by the same filename layer segment:
    • *-backend-task-prep-*"dev-workflows-fullstack:quality-fixer"
    • *-frontend-task-prep-*"dev-workflows-fullstack:quality-fixer-frontend"
  4. Commit when quality-fixer returns approved

Append the Scope Boundary block (below) to every subagent prompt.

Step 6: Re-scan, Present Readiness Report, Cleanup, Exit

  1. Re-scan: Re-run the Step 2 readiness scan after all resolution tasks are committed.

  2. Present Readiness Report: Present the Readiness Report (see Output Format below) to the user. The report is shown in-session and is not written into the work plan — the durable output of this recipe is the committed Phase 0 resolution tasks, not a persisted report.

  3. Final Cleanup: Delete every prep task file this recipe created for the current {plan-name} (docs/plans/tasks/{plan-name}-backend-task-prep-*.md and docs/plans/tasks/{plan-name}-frontend-task-prep-*.md) AND the phase-completion file generated for prep phases (docs/plans/tasks/{plan-name}-phase0-completion.md when present, since prep tasks live in Phase 0). Prep task files for other plans are out of scope — this recipe deletes only what it created for the current run. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs. The work plan itself is preserved for the downstream recipe--build / recipe--implement.

  4. Exit:

    Re-scan result Action
    All applicable criteria pass Exit with outcome: ready, gaps_resolved: N and final Readiness Report
    One or more fail remain Exit with outcome: escalated — present remaining failures to the user with the next-action recommendation. Treat the re-scan as the terminal evaluation; further resolution requires the user to re-invoke this recipe with updated inputs.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Output Format

Final report presented to the user at exit:

## Implementation Readiness Report

Work plan: [path]
Outcome: ready | escalated
Gaps resolved: [N]

### Readiness Criteria

| ID | Result | Evidence |
|----|--------|----------|
| R1 | pass / fail / not_applicable | [file:line OR "missing: <unresolved reference>"] |
| R2 | ... | ... |
| R3 | ... | ... |
| R4 | ... | ... |
| R5 | ... | ... |

### Resolution Tasks Executed (when gaps_resolved > 0)
- [task file path] — [one-line summary] — committed
- ...

### Remaining Gaps (when outcome is escalated)
- [criterion ID]: [unresolved reference] — Next action: [recommendation]

Completion Criteria

  • Work plan loaded and Verification Strategy / E2E references / Phase structure extracted
  • Readiness scan run with per-criterion result and evidence recorded
  • No-op exit when all pass, OR resolution tasks generated, approved, and executed via the 4-step cycle
  • Re-scan run after the last resolution task commits
  • Prep task files (and Phase 0 phase-completion file when generated) deleted from docs/plans/tasks/
  • Final report presented to the user
该技能通过发现、生成、验证和审查工作流,从现有代码库逆向工程生成PRD和设计文档。支持分阶段配置范围、深度及架构风格,并协调子代理逐步完成PRD与设计文档的自动化产出。
需要从现有代码库生成产品需求文档(PRD) 需要基于代码结构自动生成系统设计文档 启动代码逆向工程以提取技术规格说明
dev-workflows-fullstack/skills/recipe-reverse-engineer/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-reverse-engineer -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-reverse-engineer",
    "description": "Generate PRD and Design Docs from existing codebase through discovery, generation, verification, and review workflow",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Reverse engineering workflow to create documentation from existing code

Target: $ARGUMENTS

Orchestrator Definition

Core Identity: "I am an orchestrator."

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Process one step at a time: Execute steps sequentially within each unit (2 → 3 → 4 → 5). Each step's output is the required input for the next step. Complete all steps for one unit before starting the next
  3. Pass $STEP_N_OUTPUT as-is to sub-agents — the orchestrator bridges data without processing or filtering it

Task Registration: Register phases first using TaskCreate, then steps within each phase as you enter it. Update status using TaskUpdate.

Step 0: Initial Configuration

0.1 Scope Confirmation

Use AskUserQuestion to confirm:

  1. Target path: Which directory/module to document
  2. Depth: PRD only, or PRD + Design Docs
  3. Reference Architecture: layered / mvc / clean / hexagonal / none
  4. Human review: Yes (recommended) / No (fully autonomous)
  5. Fullstack design: Yes / No
    • Yes: For each functional unit, generate backend + frontend Design Docs
    • Note: Requires both agents (technical-designer, technical-designer-frontend)

0.2 Output Configuration

  • PRD output: docs/prd/ or existing PRD directory
  • Design Doc output: docs/design/ or existing design directory
  • Verify directories exist, create if needed

Workflow Overview

Phase 1: PRD Generation
  Step 1: Scope Discovery (unified, single pass → group into PRD units → human review)
  Step 2-5: Per-unit loop (Generation → Verification → Review → Revision)

Phase 2: Design Doc Generation (if requested)
  Step 6: Design Doc Scope Mapping (reuse Step 1 results, no re-discovery)
  Step 7-10: Per-unit loop (Generation → Verification → Review → Revision)
  ※ fullstack=Yes: each unit produces backend + frontend Design Docs

Phase 1: PRD Generation

Register using TaskCreate:

  • Step 1: PRD Scope Discovery
  • Per-unit processing (Steps 2-5 for each unit)

Step 1: PRD Scope Discovery

Agent tool invocation:

subagent_type: dev-workflows-fullstack:scope-discoverer
description: "Discover functional scope"
prompt: |
  Discover functional scope targets in the codebase.

  target_path: $USER_TARGET_PATH
  reference_architecture: $USER_RA_CHOICE
  focus_area: $USER_FOCUS_AREA (if specified)

Store output as: $STEP_1_OUTPUT

Quality Gate:

  • At least one unit discovered → proceed
  • No units discovered → ask user for hints
  • $STEP_1_OUTPUT.prdUnits exists
  • All sourceUnits across prdUnits (flattened, deduplicated) match the set of discoveredUnits IDs — no unit missing, no unit duplicated
  • Each discovered unit's unitInventory has at least one non-empty category (routes, testFiles, or publicExports). Units with all three empty indicate incomplete discovery — re-run scope-discoverer with focus on that unit's relatedFiles

Human Review Point (if enabled): Present $STEP_1_OUTPUT.prdUnits with their source unit mapping. The user confirms, adjusts grouping, or excludes units from scope. This is the most important review point — incorrect grouping cascades into all downstream documents.

Step 2-5: Per-Unit Processing

FOR each unit in $STEP_1_OUTPUT.prdUnits (sequential, one unit at a time):

Step 2: PRD Generation

Agent tool invocation:

subagent_type: dev-workflows-fullstack:prd-creator
description: "Generate PRD"
prompt: |
  Create reverse-engineered PRD for the following feature.

  Operation Mode: reverse-engineer
  External Scope Provided: true

  Feature: $PRD_UNIT_NAME (from $STEP_1_OUTPUT)
  Description: $PRD_UNIT_DESCRIPTION
  Related Files: $PRD_UNIT_COMBINED_RELATED_FILES
  Entry Points: $PRD_UNIT_COMBINED_ENTRY_POINTS

  Use provided scope as investigation starting point.
  If tracing entry points reveals files outside this scope, include them.
  Create final version PRD based on thorough code investigation.

Store output as: $STEP_2_OUTPUT (PRD path)

Step 3: Code Verification

Prerequisite: $STEP_2_OUTPUT (PRD path from Step 2)

Agent tool invocation:

subagent_type: dev-workflows-fullstack:code-verifier
description: "Verify PRD consistency"
prompt: |
  Verify consistency between PRD and code implementation.

  doc_type: prd
  document_path: $STEP_2_OUTPUT
  verbose: false

Note: Omit code_paths — the verifier independently discovers code scope from the document, ensuring independent verification not constrained by scope-discoverer's output.

Store output as: $STEP_3_OUTPUT

Quality Gate:

  • consistencyScore >= 70 AND verifiableClaimCount >= 20 → proceed to review
  • consistencyScore >= 70 BUT verifiableClaimCount < 20 → re-run verifier (investigation too shallow)
  • consistencyScore < 70 → flag for detailed review

Step 4: Review

Required Input: $STEP_3_OUTPUT (verification JSON from Step 3)

Agent tool invocation:

subagent_type: dev-workflows-fullstack:document-reviewer
description: "Review PRD"
prompt: |
  Review the following PRD considering code verification findings.

  doc_type: PRD
  target: $STEP_2_OUTPUT
  mode: composite
  code_verification: $STEP_3_OUTPUT

  ## Additional Review Focus
  - Alignment between PRD claims and verification evidence
  - Resolution recommendations for each discrepancy
  - Completeness of undocumented feature coverage

Store output as: $STEP_4_OUTPUT

Step 5: Revision (conditional)

Trigger Conditions (any one of the following):

  • Review status is "Needs Revision" or "Rejected"
  • Critical discrepancies exist in $STEP_3_OUTPUT
  • consistencyScore < 70

Agent tool invocation:

subagent_type: dev-workflows-fullstack:prd-creator
description: "Revise PRD"
prompt: |
  Update PRD based on review feedback and code verification results.

  Operation Mode: update
  Existing PRD: $STEP_2_OUTPUT

  ## Review Feedback
  $STEP_4_OUTPUT

  ## Code Verification Results
  $STEP_3_OUTPUT

  Address discrepancies by severity. Critical and major items require correction.
  Minor items: correct if straightforward, otherwise leave as-is with rationale.

Loop Control: Maximum 2 revision cycles. After 2 cycles, flag for human review regardless of status.

Unit Completion

  • Review status is "Approved" or "Approved with Conditions"
  • Human review passed (if enabled in Step 0)

Next: Proceed to next unit. After all units → Phase 2.

Phase 2: Design Doc Generation

Execute only if Design Docs were requested in Step 0

Register using TaskCreate:

  • Step 6: Design Doc Scope Mapping
  • Per-unit processing (Steps 7-10 for each unit)

Step 6: Design Doc Scope Mapping

No additional discovery required. Use $STEP_1_OUTPUT.discoveredUnits (implementation-granularity units) for technical profiles. Use $STEP_1_OUTPUT.prdUnits[].sourceUnits to trace which discovered units belong to each PRD unit.

Each PRD unit from Phase 1 maps to Design Doc unit(s):

  • Standard mode (fullstack=No): 1 PRD unit → 1 Design Doc (using technical-designer)
  • Fullstack mode (fullstack=Yes): 1 PRD unit → 2 Design Docs (technical-designer + technical-designer-frontend)

Map $STEP_1_OUTPUT units to Design Doc generation targets, carrying forward:

  • technicalProfile.primaryModules → Primary Files
  • technicalProfile.publicInterfaces → Public Interfaces
  • dependencies → Dependencies
  • relatedFiles → Scope boundary
  • unitInventory → Unit Inventory (routes, test files, public exports)

Store output as: $STEP_6_OUTPUT

Step 7-10: Per-Unit Processing

FOR each unit in $STEP_6_OUTPUT (sequential, one unit at a time):

Step 7: Design Doc Generation

Scope: Document the current architecture exactly as implemented in code.

Standard mode (fullstack=No):

Agent tool invocation:

subagent_type: dev-workflows-fullstack:technical-designer
description: "Generate Design Doc"
prompt: |
  Create Design Doc for the following feature based on existing code.

  Operation Mode: reverse-engineer

  Feature: $UNIT_NAME (from $STEP_6_OUTPUT)
  Description: $UNIT_DESCRIPTION
  Primary Files: $UNIT_PRIMARY_MODULES
  Public Interfaces: $UNIT_PUBLIC_INTERFACES
  Dependencies: $UNIT_DEPENDENCIES
  Unit Inventory: $UNIT_INVENTORY (routes, test files, public exports from scope discovery)

  Parent PRD: $APPROVED_PRD_PATH

  Document current architecture as-is. Use Unit Inventory as a completeness baseline — all routes and exports should be accounted for in the Design Doc.

Store output as: $STEP_7_OUTPUT

Fullstack mode (fullstack=Yes):

For each unit, invoke 7a then 7b sequentially (7b depends on 7a output):

7a. Backend Design Doc:

subagent_type: dev-workflows-fullstack:technical-designer
description: "Generate backend Design Doc"
prompt: |
  Create a backend Design Doc for the following feature based on existing code.

  Operation Mode: reverse-engineer

  Feature: $UNIT_NAME (from $STEP_6_OUTPUT)
  Description: $UNIT_DESCRIPTION
  Primary Files: $UNIT_PRIMARY_MODULES
  Public Interfaces: $UNIT_PUBLIC_INTERFACES
  Dependencies: $UNIT_DEPENDENCIES
  Unit Inventory: $UNIT_INVENTORY

  Parent PRD: $APPROVED_PRD_PATH

  Focus on: API contracts, data layer, business logic, service architecture.
  Document current architecture as-is. Use Unit Inventory as completeness baseline.

Store output as: $STEP_7a_OUTPUT

7b. Frontend Design Doc:

subagent_type: dev-workflows-fullstack:technical-designer-frontend
description: "Generate frontend Design Doc"
prompt: |
  Create a frontend Design Doc for the following feature based on existing code.

  Operation Mode: reverse-engineer

  Feature: $UNIT_NAME (from $STEP_6_OUTPUT)
  Description: $UNIT_DESCRIPTION
  Primary Files: $UNIT_PRIMARY_MODULES
  Public Interfaces: $UNIT_PUBLIC_INTERFACES
  Dependencies: $UNIT_DEPENDENCIES
  Unit Inventory: $UNIT_INVENTORY

  Parent PRD: $APPROVED_PRD_PATH
  Backend Design Doc: $STEP_7a_OUTPUT

  Reference backend Design Doc for API contracts.
  Focus on: component hierarchy, state management, UI interactions, data fetching.
  Document current architecture as-is. Use Unit Inventory as completeness baseline.

Store output as: $STEP_7b_OUTPUT

Step 8: Code Verification

Standard mode: Verify $STEP_7_OUTPUT.

Fullstack mode: Verify each Design Doc separately.

Agent tool invocation (per Design Doc):

subagent_type: dev-workflows-fullstack:code-verifier
description: "Verify Design Doc consistency"
prompt: |
  Verify consistency between Design Doc and code implementation.

  doc_type: design-doc
  document_path: $STEP_7_OUTPUT (or $STEP_7a_OUTPUT / $STEP_7b_OUTPUT)
  verbose: false

Note: Omit code_paths — the verifier independently discovers code scope from the document.

Store output as: $STEP_8_OUTPUT

Step 9: Review

Required Input: $STEP_8_OUTPUT (verification JSON from Step 8)

Agent tool invocation (per Design Doc):

subagent_type: dev-workflows-fullstack:document-reviewer
description: "Review Design Doc"
prompt: |
  Review the following Design Doc considering code verification findings.

  doc_type: DesignDoc
  target: $STEP_7_OUTPUT (or $STEP_7a_OUTPUT / $STEP_7b_OUTPUT)
  mode: composite
  code_verification: $STEP_8_OUTPUT

  ## Parent PRD
  $APPROVED_PRD_PATH

  ## Additional Review Focus
  - Technical accuracy of documented interfaces
  - Consistency with parent PRD scope
  - Completeness of unit boundary definitions

Store output as: $STEP_9_OUTPUT

Step 10: Revision (conditional)

Trigger Conditions (same as Step 5):

  • Review status is "Needs Revision" or "Rejected"
  • Critical discrepancies exist in $STEP_8_OUTPUT
  • consistencyScore < 70

Agent tool invocation (per Design Doc):

subagent_type: dev-workflows-fullstack:technical-designer (or dev-workflows-fullstack:technical-designer-frontend for frontend Design Docs)
description: "Revise Design Doc"
prompt: |
  Update Design Doc based on review feedback and code verification results.

  Operation Mode: update
  Existing Design Doc: $STEP_7_OUTPUT (or $STEP_7a_OUTPUT / $STEP_7b_OUTPUT)

  ## Review Feedback
  $STEP_9_OUTPUT

  ## Code Verification Results
  $STEP_8_OUTPUT

  Address discrepancies by severity. Critical and major items require correction.
  Minor items: correct if straightforward, otherwise leave as-is with rationale.

Loop Control: Maximum 2 revision cycles. After 2 cycles, flag for human review regardless of status.

Unit Completion

  • Review status is "Approved" or "Approved with Conditions"
  • Human review passed (if enabled in Step 0)

Next: Proceed to next unit. After all units → Final Report.

Final Report

Output summary including:

  • Generated documents table (Type, Name, Consistency Score, Review Status)
  • Action items (critical discrepancies, undocumented features, flagged items)
  • Next steps checklist

Error Handling

Error Action
Discovery finds nothing Ask user for project structure hints
Generation fails Log failure, continue with other units, report in summary
consistencyScore < 50 Flag for mandatory human review — require explicit human approval
Review rejects after 2 revisions Stop loop, flag for human intervention
作为编排器,自动执行设计文档合规性与安全验证。通过调用代码和安全审查子代理生成报告,根据结果智能推荐修复路径:代码违规则修复实现,设计过时则更新文档,并支持重新验证以确保质量。
需要检查代码与设计文档的一致性 执行上线前的安全与合规审计 发现代码与设计不符需自动修复
dev-workflows-fullstack/skills/recipe-review/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-review -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-review",
    "description": "Design Doc compliance and security validation with optional auto-fixes",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Post-implementation quality assurance

Orchestrator Definition

Core Identity: "I am an orchestrator."

First Action: Register Steps 1-11 using TaskCreate before any execution.

Execution Method

  • Compliance validation → performed by code-reviewer
  • Security validation → performed by security-reviewer
  • Code-side fix path: Fix implementation → task-executor; Quality checks → quality-fixer; Re-validation → code-reviewer / security-reviewer
  • Design-side update path: DD revision → technical-designer (update mode); DD review → document-reviewer; cross-DD consistency → design-sync (when multiple DDs exist); Re-validation → code-reviewer

Orchestrator invokes sub-agents and passes structured JSON between them. The design-side path applies when the discrepancy reflects code that was correct but the Design Doc became stale, rather than code that violated the Design Doc.

Design Doc (uses most recent if omitted): $ARGUMENTS

Execution Flow

Step 1: Prerequisite Check

# Identify Design Doc
ls docs/design/*.md | grep -v template | tail -1

# Check implementation files
git diff --name-only main...HEAD

Step 2: Execute code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows-fullstack:code-reviewer"
  • description: "Code compliance review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review mode: full. Validate Design Doc compliance and return structured JSON report."

Store output as: $STEP_2_OUTPUT

Step 3: Execute security-reviewer

Invoke security-reviewer using Agent tool:

  • subagent_type: "dev-workflows-fullstack:security-reviewer"
  • description: "Security review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review security compliance."

Store output as: $STEP_3_OUTPUT

Step 4: Verdict and Response

If security-reviewer returned blocked: Stop immediately. Report the blocked finding and escalate to user. Do not proceed to fix steps.

Code compliance criteria (considering project stage):

  • Prototype: Pass at 70%+
  • Production: 90%+ recommended

Security criteria:

  • approved or approved_with_notes → Pass
  • needs_revision → Fail

Report both results independently using subagent output fields only:

Before presenting to the user, the orchestrator computes a recommended route per finding using the rule below (this rule is internal — do not include it in the user-facing prompt):

Finding pattern Recommended route
dd_violation where the code intent matches the original requirement but the Design Doc captured a different design d (Design-side update)
dd_violation where the code drifted from a still-correct Design Doc c (Code-side fix)
reliability / security / maintainability findings c (Code-side fix)

Then present to the user (label each finding with its recommended route, grouped by route):

Code Compliance: [complianceRate from code-reviewer]
  Verdict: [verdict from code-reviewer]
  Identifier Match Rate: [identifierMatchRate from code-reviewer]
  Acceptance Criteria:
  - [fulfilled] [item] (confidence: [high/medium/low])
  - [partially_fulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  - [unfulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  Identifier Mismatches:
  - [identifier]: DD=[designDocValue] Code=[codeValue] at [location] [recommended: c | d]
  Quality Findings:
  - [category] [location]: [description] — [rationale] [recommended: c]

Security Review: [status from security-reviewer]
  Findings by category:
  - [confirmed_risk] [location]: [description] — [rationale] [recommended: c]
  - [defense_gap] [location]: [description] — [rationale] [recommended: c]
  - [hardening] [location]: [description] — [rationale] [recommended: c]
  - [policy] [location]: [description] — [rationale] [recommended: c]
  Notes: [notes from security-reviewer, if present]

Resolve discrepancies — confirm or override the recommended route per finding:
  c) Code-side fix       — code violates Design Doc; modify code to match
  d) Design-side update  — code is correct; Design Doc is stale, revise it
  s) Skip                — accept current state without changes

Use AskUserQuestion. The default offer is "accept all recommended routes" — a single confirmation for the typical case where the orchestrator's recommendations are correct. When the user wants to override, collect per-finding c/d/s decisions instead. If the user selects s for everything: skip Steps 5-10, proceed to Step 11.

Step 5: Execute Skill

Execute Skill: documentation-criteria (for task file template)

Step 5d: Design-Side Update

Run this step only when the user routed at least one finding to d. When all routes are c or s, skip directly to Step 6.

  1. Invoke technical-designer in update mode using Agent tool:

    • subagent_type: "dev-workflows-fullstack:technical-designer"
    • description: "Design Doc update from review findings"
    • prompt: "Update Design Doc at [path] in update mode. The implementation has diverged in the following ways that the team has decided to ratify in the design rather than in the code: [list of d-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
  2. Invoke document-reviewer to verify the updated Design Doc:

    • subagent_type: "dev-workflows-fullstack:document-reviewer"
    • description: "Document review of updated Design Doc"
    • prompt: "Review updated Design Doc at [path] for consistency and completeness."
  3. When multiple Design Docs exist (ls docs/design/*.md | grep -v template | wc -l > 1), invoke design-sync:

    • subagent_type: "dev-workflows-fullstack:design-sync"
    • description: "Cross-DD consistency check"
    • prompt: "source_design: [updated DD path]. Detect conflicts across all Design Docs after the update."
    • When sync_status: conflicts_found: present conflicts to the user; resolution requires re-invoking technical-designer for affected DDs.
  4. After Step 5d completes:

    • If the user selected d for all findings (no c routes) → skip Steps 6-8, proceed to Step 9 for re-validation
    • If the user selected both d and c → re-evaluate the c-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remaining c findings

Step 6: Create Task File

Create task file at docs/plans/tasks/review-fixes-YYYYMMDD.md Include both code compliance issues and security requiredFixes.

Step 7: Execute Fixes

Invoke task-executor using Agent tool:

  • subagent_type: "dev-workflows-fullstack:task-executor"
  • description: "Execute review fixes"
  • prompt: "Task file: docs/plans/tasks/review-fixes-YYYYMMDD.md. Apply staged fixes (stops at 5 files)."

Step 8: Quality Check

Invoke quality-fixer using Agent tool:

  • subagent_type: "dev-workflows-fullstack:quality-fixer"
  • description: "Quality gate check"
  • prompt: "Confirm quality gate passage for fixed files."

Step 9: Re-validate code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows-fullstack:code-reviewer"
  • description: "Re-validate compliance"
  • prompt: "Re-validate Design Doc compliance after fixes. Prior compliance issues: $STEP_2_OUTPUT. Verify each prior issue is resolved (whether resolved code-side or design-side)."

Step 10: Re-validate security-reviewer

Invoke security-reviewer using Agent tool (only if security fixes were applied):

  • subagent_type: "dev-workflows-fullstack:security-reviewer"
  • description: "Re-validate security"
  • prompt: "Re-validate security after fixes. Prior findings: $STEP_3_OUTPUT. Design Doc: [path]. Implementation files: [file list]."

Step 11: Final Cleanup and Report

Delete the review-fix task file this recipe created (if any). Its work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete docs/plans/tasks/review-fixes-YYYYMMDD.md if it exists

If the file cannot be deleted (filesystem error), report the failure but do not block the final report.

Then present the final report:

Code Compliance:
  Initial: [X]%
  Final: [Y]% (if fixes executed)

Security Review:
  Initial: [status]
  Final: [status] (if fixes executed)
  Notes: [notes from approved_with_notes, if any]

Remaining issues:
- [items requiring manual intervention]

Cleanup: review-fixes task file removed

Auto-fixable Items (code-side path)

  • Simple unimplemented acceptance criteria
  • Error handling additions
  • Contract definition fixes
  • Function splitting (length/complexity improvements)
  • Security confirmed_risk and defense_gap fixes (input validation, auth checks, output encoding)

Non-fixable Items

  • Fundamental business logic changes
  • Architecture-level modifications
  • Committed secrets (blocked → human intervention)

Design-Side Update Triggers

Discrepancies suitable for the design-side path (code is correct, DD became stale):

  • Identifier renames where the new identifier reflects the team's current naming
  • Behavioral changes that match the original requirement intent better than what the DD captured
  • Component splits or merges where the new structure is sound and the DD documented the prior structure
  • New ACs that the implementation already satisfies but the DD never enumerated

Scope: Design Doc compliance validation, security review, code-side auto-fixes, and design-side update routing.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the review scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.
执行任务前调用rule-advisor进行元认知分析,选择规则并识别风险。基于分析结果拆解任务、创建清单并按指导顺序执行,确保遵循最佳实践与质量规范。
需要执行复杂开发任务时 生成Agent提示词或工件前 涉及多步骤工作流执行
dev-workflows-fullstack/skills/recipe-task/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-task -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-task",
    "description": "Execute tasks following appropriate rules with rule-advisor metacognition",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Task Execution with Metacognitive Analysis

Task: $ARGUMENTS

Mandatory Execution Process

Step 1: Rule Selection via rule-advisor (REQUIRED)

Invoke rule-advisor using Agent tool:

  • subagent_type: "dev-workflows-fullstack:rule-advisor"
  • description: "Rule selection"
  • prompt: "Task: $ARGUMENTS. Select appropriate rules and perform metacognitive analysis."

Step 2: Utilize rule-advisor Output

After receiving rule-advisor's JSON response, proceed with:

  1. Understand Task Essence (from taskAnalysis.essence)

    • Focus on fundamental purpose, not surface-level work
    • Distinguish between "quick fix" vs "proper solution"
  2. Follow Selected Rules (from selectedRules)

    • Review each selected rule section
    • Apply concrete procedures and guidelines
  3. Recognize Past Failures (from metaCognitiveGuidance.pastFailures)

    • Apply countermeasures for known failure patterns
    • Use suggested alternative approaches
  4. Execute First Action (from metaCognitiveGuidance.firstStep)

    • Start with recommended action
    • Use suggested tools first

Step 3: Create Task List with TaskCreate

Register work steps using TaskCreate. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON".

Break down the task based on rule-advisor's guidance:

  • Reflect taskAnalysis.essence in task descriptions
  • Apply metaCognitiveGuidance.firstStep to first task
  • Restructure tasks considering warningPatterns
  • Set priorities based on dependency order and warningPatterns severity

Step 4: Execute Implementation

Proceed with task execution following:

  • Start with metaCognitiveGuidance.firstStep action from rule-advisor
  • Update task structure with TaskUpdate to reflect rule-advisor insights
  • Selected rules from rule-advisor
  • Task structure (managed via TaskCreate/TaskUpdate)
  • Quality standards defined in the selectedRules output from rule-advisor
  • Monitor warningPatterns flags throughout execution and adjust approach when triggered
用于更新现有设计文档(Design Doc/PRD/ADR)的技能。通过识别目标文档、明确变更内容、调用对应代理执行更新,并经过多层审查与一致性校验,最终在获得用户批准后完成更新流程。
需要修改现有的设计文档、产品需求文档或架构决策记录 收到对特定文档的审查反馈并要求进行修订
dev-workflows-fullstack/skills/recipe-update-doc/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-update-doc -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-update-doc",
    "description": "Update existing design documents (Design Doc \/ PRD \/ ADR) with review",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to updating existing design documents.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

First Action: Register Steps 1-6 using TaskCreate before any execution.

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Execute update flow:
    • Identify target → Clarify changes → Update document → Review → Consistency check
    • Stop at every [Stop: ...] marker → Wait for user approval before proceeding
  3. Scope: Complete when updated document receives approval

CRITICAL: Execute document-reviewer and all stopping points — each serves as a quality gate for document accuracy.

Workflow Overview

Target document → [Stop: Confirm changes]
                        ↓
              technical-designer / technical-designer-frontend / prd-creator (update mode)
                        ↓ (Design Doc only)
              code-verifier → document-reviewer → [Stop: Review approval]
                        ↓ (Design Doc only)
              design-sync → [Stop: Final approval]

Scope Boundaries

Included in this skill:

  • Existing document identification and selection
  • Change content clarification with user
  • Document update with appropriate agent (update mode)
  • Document review with document-reviewer
  • Consistency verification with design-sync (Design Doc only)

Out of scope (redirect to appropriate skills):

  • New requirement analysis
  • Work planning or implementation

Responsibility Boundary: This skill completes with updated document approval.

Target document: $ARGUMENTS

Execution Flow

Step 1: Target Document Identification

# Check existing documents
ls docs/design/*.md docs/prd/*.md docs/adr/*.md 2>/dev/null | grep -v template

Decision flow:

Situation Action
$ARGUMENTS specifies a path Use specified document
$ARGUMENTS describes a topic Search documents matching the topic
Multiple candidates found Present options with AskUserQuestion
No documents found Report and end (document creation is out of scope)

Step 2: Document Type and Layer Determination

Determine type from document path, then determine the layer to select the correct update agent:

Path Pattern Type Update Agent Notes
docs/design/*.md Design Doc technical-designer or technical-designer-frontend See layer detection below
docs/prd/*.md PRD prd-creator -
docs/adr/*.md ADR technical-designer or technical-designer-frontend See layer detection below

Layer detection (for Design Doc and ADR): Read the document and determine its layer from content signals:

  • Frontend (→ technical-designer-frontend): Document title/scope mentions React, components, UI, frontend; or file contains component hierarchy, state management, UI interactions
  • Backend (→ technical-designer): All other cases (API, data layer, business logic, infrastructure)

ADR Update Guidance:

  • Minor changes (clarification, typo fix, small scope adjustment): Update the existing ADR file
  • Major changes (decision reversal, significant scope change): Create a new ADR that supersedes the original

Step 3: Change Content Clarification [Stop]

Use AskUserQuestion to clarify what changes are needed:

  • What sections need updating
  • Reason for the change (bug fix findings, spec change, review feedback, etc.)
  • Expected outcome after the update

Confirm understanding of changes with user before proceeding.

Step 4: Document Update

Invoke the update agent determined in Step 2:

subagent_type: [Update Agent from Step 2]
description: "Update [Type from Step 2]"
prompt: |
  Operation Mode: update
  Existing Document: [path from Step 1]

  ## Changes Required
  [Changes clarified in Step 3]

  Update the document to reflect the specified changes.
  Add change history entry.

Step 5: Document Review [Stop]

For Design Doc updates only: Before document-reviewer, invoke code-verifier:

subagent_type: code-verifier
description: "Verify updated Design Doc"
prompt: |
  doc_type: design-doc
  document_path: [path from Step 1]
  Verify the updated Design Doc against current codebase.

  Verification focus: Pay special attention to literal identifier referential
  integrity in the updated sections (paths, endpoints, type names, config keys).

Store output as: $CODE_VERIFICATION_OUTPUT

Invoke document-reviewer:

subagent_type: document-reviewer
description: "Review updated document"
prompt: |
  Review the following updated document.

  doc_type: [Design Doc / PRD / ADR]
  target: [path from Step 1]
  mode: standard
  code_verification: $CODE_VERIFICATION_OUTPUT (Design Doc only, omit for PRD/ADR)

  Focus on:
  - Consistency of updated sections with rest of document
  - No contradictions introduced by changes
  - Completeness of change history

Store output as: $STEP_5_OUTPUT

On review result:

  • Approved → Proceed to Step 6
  • Needs revision → Return to Step 4 with the following prompt (max 2 iterations):
    subagent_type: [Update Agent from Step 2]
    description: "Revise [Type from Step 2]"
    prompt: |
      Operation Mode: update
      Existing Document: [path from Step 1]
    
      ## Review Feedback to Address
      $STEP_5_OUTPUT
    
      Address each issue raised in the review feedback.
    
  • After 2 rejections → Flag for human review, present accumulated feedback to user and end

Present review result to user for approval.

Step 6: Consistency Verification (Design Doc only) [Stop]

Skip condition: Document type is PRD or ADR → Proceed to completion.

For Design Doc, invoke design-sync:

subagent_type: design-sync
description: "Verify consistency"
prompt: |
  Verify consistency of the updated Design Doc with other design documents.

  Updated document: [path from Step 1]

On consistency result:

  • No conflicts → Present result to user for final approval
  • Conflicts detected → Present conflicts to user with AskUserQuestion:
    • A: Return to Step 4 to resolve conflicts in this document
    • B: End and address conflicts separately

Error Handling

Error Action
Target document not found Report and end (document creation is out of scope)
Sub-agent update fails Log failure, present error to user, retry once
Review rejects after 2 revisions Stop loop, flag for human intervention
design-sync detects conflicts Present to user for resolution decision

Completion Criteria

  • Identified target document
  • Clarified change content with user
  • Updated document with appropriate agent (update mode)
  • Executed code-verifier before document-reviewer (Design Doc only)
  • Executed document-reviewer and addressed feedback
  • Executed design-sync for consistency verification (Design Doc only)
  • Obtained user approval for updated document

Output Example

Document update completed.

  • Updated document: docs/design/[document-name].md
  • Approval status: User approved
指导多智能体协作与工作流程编排。通过需求分析器确定规模,协调各类专业子代理执行任务,监控范围变更并自动重启流程,实现自主化、结构化的复杂任务处理。
需要协调多个智能体完成任务时 管理复杂工作流阶段时 决定自主执行模式时
dev-workflows-fullstack/skills/subagents-orchestration-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill subagents-orchestration-guide -g -y
SKILL.md
Frontmatter
{
    "name": "subagents-orchestration-guide",
    "description": "Guides subagent coordination through implementation workflows. Use when orchestrating multiple agents, managing workflow phases, or determining autonomous execution mode."
}

Subagents Orchestration Guide

Role: The Orchestrator

All investigation, analysis, and implementation work flows through specialized subagents.

First Action Rule

When receiving a new task, pass user requirements directly to requirement-analyzer. Determine the workflow based on its scale assessment result.

Requirement Change Detection During Flow

During flow execution, monitor user responses for scope-expanding signals:

  • Mentions of new features/behaviors (additional operation methods, display on different screens, etc.)
  • Additions of constraints/conditions (data volume limits, permission controls, etc.)
  • Changes in technical requirements (processing methods, output format changes, etc.)

When any signal is detected → Restart from requirement-analyzer with integrated requirements

Available Subagents

Implementation support:

  1. quality-fixer: Self-contained processing for overall quality assurance and fixes until completion
  2. task-decomposer: Appropriate task decomposition of work plans
  3. task-executor: Individual task execution and structured response
  4. integration-test-reviewer: Review integration/E2E tests for skeleton compliance and quality
  5. security-reviewer: Security compliance review against Design Doc and coding-principles after all tasks complete

Document creation: 6. requirement-analyzer: Requirement analysis and work scale determination 7. codebase-analyzer: Analyze existing codebase to produce focused guidance for technical design (data, contracts, dependencies, quality assurance mechanisms) 8. ui-analyzer: Read the project's external-resources file, fetch external UI sources (design origin, design system, guidelines) via MCP/URL/file, and analyze existing UI code. Frontend/fullstack features; runs in parallel with codebase-analyzer. Uses disallowedTools to inherit MCP access 9. prd-creator: Product Requirements Document creation 10. ui-spec-designer: UI Specification creation from PRD and optional prototype code (frontend/fullstack features) 11. technical-designer: ADR/Design Doc creation 12. work-planner: Work plan creation from Design Doc and test skeletons 13. document-reviewer: Single document quality and rule compliance check 14. code-verifier: Verify document-code consistency. Pre-implementation: Design Doc claims against existing codebase. Post-implementation: implementation against Design Doc 15. design-sync: Design Doc consistency verification across multiple documents 16. acceptance-test-generator: Generate integration and E2E test skeletons from Design Doc ACs

Orchestration Principles

Delegation Boundary: What vs How

The orchestrator passes what to accomplish and where to work. Each specialist determines how to execute autonomously.

Pass to specialists (what/where/constraints):

  • Target directory, package, or file paths
  • Task file path or scope description
  • Acceptance criteria and hard constraints from the user or design artifacts

Let specialists determine (how):

  • Specific commands to run (specialists discover these from project configuration and repo conventions)
  • Execution order and tool flags
  • Which files to inspect or modify within the given scope
Bad (orchestrator prescribes how) Good (orchestrator passes what)
quality-fixer "Run these checks: 1. lint 2. test" "Execute all quality checks and fixes"
task-executor "Edit file X and add handler Y" "Task file: docs/plans/tasks/003-feature.md"

Decision precedence when outputs conflict:

  1. User instructions (explicit requests or constraints)
  2. Task files and design artifacts (Design Doc, PRD, work plan)
  3. Objective repo state (git status, file system, project configuration)
  4. Specialist judgment

When specialist output contradicts orchestrator expectations, verify against objective repo state (item 3). If repo state confirms the specialist, follow the specialist. Override specialist output only when it conflicts with items 1 or 2.

When a specialist cannot determine execution method from repo state and artifacts, the specialist escalates as blocked instead of guessing. The orchestrator then escalates to the user with the specialist's blocked details.

Task Assignment with Responsibility Separation

Assign work based on each subagent's responsibilities:

What to delegate to task-executor:

  • Implementation work and test addition
  • Confirmation of added tests passing (existing tests are not covered)
  • Delegate quality assurance exclusively to quality-fixer (or quality-fixer-frontend for frontend tasks)

What to delegate to quality-fixer:

  • Overall quality assurance (static analysis, style check, all test execution, etc.)
  • Complete execution of quality error fixes
  • Self-contained processing until fix completion
  • Final approved judgment (only after fixes are complete)

Constraints Between Subagents

Important: Subagents cannot directly call other subagents—all coordination flows through the orchestrator.

Explicit Stop Points

Autonomous execution MUST stop and wait for user input at these points. Use AskUserQuestion to present confirmations and questions.

Phase Stop Point User Action Required
Requirements After requirement-analyzer completes Confirm requirements / Answer questions
PRD After document-reviewer completes PRD review Approve PRD
UI Spec After document-reviewer completes UI Spec review (frontend/fullstack) Approve UI Spec
ADR After document-reviewer completes ADR review (if ADR created) Approve ADR
Design After design-sync completes consistency verification Approve Design Doc
Work Plan After work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) or work-planner (Small) completes Batch approval for implementation phase

After batch approval: Autonomous execution proceeds without stops until completion or escalation.

Scale Determination and Document Requirements

Scale File Count PRD ADR Design Doc Work Plan
Small 1-2 Update※1 Not needed Not needed Simplified
Medium 3-5 Update※1 Conditional※2 Required Required
Large 6+ Required※3 Conditional※2 Required Required

※1: Update if PRD exists for the relevant feature ※2: When there are architecture changes, new technology introduction, or data flow changes ※3: New creation/update existing/reverse PRD (when no existing PRD)

How to Call Subagents

Execution Method

Each subagent invocation is a fresh Agent tool call, isolating each phase's context; a SendMessage resume reuses the prior agent's context and breaks that isolation. Each call uses:

  • subagent_type: Agent name (e.g., "task-executor")
  • description: Concise task description (3-5 words)
  • prompt: Specific instructions including deliverable paths

Orchestrator's Permitted Tools

The orchestrator coordinates work using only the following tools:

Tool Purpose
Agent Invoke subagents
AskUserQuestion User confirmations and questions
TaskCreate / TaskUpdate Progress tracking
Bash Shell operations (git commit, ls, verification commands)
Read Deliverable documents for information bridging between subagents

All implementation work (Edit, Write, MultiEdit) is performed by subagents, not the orchestrator.

Prompt Construction Rule

Every subagent prompt must include:

  1. Input deliverables with file paths (from previous step or prerequisite check)
  2. Expected action (what the agent should do)

Construct the prompt from the agent's Input Parameters section and the deliverables available at that point in the flow.

Two additional rules:

  • Subagents see only the Agent prompt and files they read. Include required paths, prior JSON, parameters, and scope constraints explicitly.
  • Replace every [placeholder] in examples below with concrete values before invoking the Agent tool.

Call Example (requirement-analyzer)

  • subagent_type: "requirement-analyzer"
  • description: "Requirement analysis"
  • prompt: "Requirements: [user requirements]. Context: [any relevant context]. Perform requirement analysis and scale determination."

Call Example (codebase-analyzer)

  • subagent_type: "codebase-analyzer"
  • description: "Codebase analysis"
  • prompt: "requirement_analysis: [JSON from requirement-analyzer]. prd_path: [path if exists]. requirements: [original user requirements]. Analyze the existing codebase and produce design guidance."

Call Example (ui-analyzer)

  • subagent_type: "ui-analyzer"
  • description: "UI fact gathering"
  • prompt: "requirement_analysis: [JSON from requirement-analyzer]. requirements: [original user requirements]. ui_spec_path: [path if exists]. target_components: [list if focused]. Read docs/project-context/external-resources.md, fetch external UI sources via the declared access methods (MCP / URL / file), and analyze the existing UI codebase. Output the consolidated UI fact JSON."

When invoked alongside codebase-analyzer for frontend or fullstack-frontend work, run both agents in parallel and pass both JSON outputs to consumers (ui-spec-designer for the design phase; technical-designer-frontend for the Design Doc phase).

Call Example (task-executor)

  • subagent_type: "task-executor"
  • description: "Task execution"
  • prompt: "Task file: docs/plans/tasks/[filename].md Please complete the implementation"

Structured Response Specification

Subagents respond in JSON format. Key fields for orchestrator decisions:

  • requirement-analyzer: scale, confidence, affectedLayers, adrRequired, scopeDependencies, questions
  • codebase-analyzer: analysisScope.categoriesDetected, dataModel.detected, qualityAssurance (mechanisms[], domainConstraints[]), focusAreas[], existingElements count, limitations
  • ui-analyzer: analysisScope.uiConventions, externalResources (designOrigin/designSystem/guidelines/visualVerification with fetch_status), componentStructure[], propsPatterns[], cssLayout[], stateDisplay[], displayConditions[], i18n, accessibility[], generatedArtifacts[], focusAreas[] (raw fact_id; consumers apply ui: prefix when merging with codebase analysis facts), candidateWriteSet[] (with confidence labels), limitations
  • code-verifier: status (consistent/mostly_consistent/needs_review/inconsistent), consistencyScore, discrepancies[], reverseCoverage (including dataOperationsInCode, testBoundariesSectionPresent). Pre-implementation: verifies Design Doc claims against existing codebase. Post-implementation: verifies implementation consistency against Design Doc (pass code_paths scoped to changed files)
  • task-executor: status (escalation_needed/completed), escalation_type (design_compliance_violation/similar_function_found/investigation_target_not_found/out_of_scope_file/dependency_version_uncertain/binding_decision_violation/test_environment_not_ready), testsAdded, requiresTestReview
  • quality-fixer: Input: task_file (path to current task file — always pass this in orchestrated flows). Status: approved/stub_detected/blocked. stub_detected → route back to task-executor with incompleteImplementations[] details for completion, then re-run quality-fixer. blocked → discriminate by reason field: "Cannot determine due to unclear specification" → read blockingIssues[] for specification details; "Execution prerequisites not met" → read missingPrerequisites[] with resolutionSteps — present these to the user as actionable next steps
  • document-reviewer: verdict.decision (approved/approved_with_conditions/needs_revision/rejected)
  • design-sync: sync_status (synced/conflicts_found)
  • integration-test-reviewer: status (approved/needs_revision/blocked), requiredFixes
  • security-reviewer: status (approved/approved_with_notes/needs_revision/blocked), findings, notes, requiredFixes
  • acceptance-test-generator: status, generatedFiles.{integration,fixtureE2e,serviceE2e} (path|null per lane), budgetUsage per lane, e2eAbsenceReason per E2E lane (null when emitted; reason enum is owned by acceptance-test-generator and integration-e2e-testing skill)

Handling Requirement Changes

Handling Requirement Changes in requirement-analyzer

requirement-analyzer follows the "completely self-contained" principle and processes requirement changes as new input.

How to Integrate Requirements

Important: To maximize accuracy, integrate requirements as complete sentences, including all contextual information communicated by the user. Result format: raw concatenation of all requirements, followed by a labeled summary (Initial requirement: … / Additional requirement: …).

Update Mode for Document Generation Agents

Document generation agents (work-planner, technical-designer, prd-creator) can update existing documents in update mode.

  • Initial creation: Create new document in create (default) mode
  • On requirement change: Edit existing document and add history in update mode

Criteria for timing when to call each agent:

  • work-planner: Request updates only before execution
  • technical-designer: Request updates according to design changes → Execute document-reviewer for consistency check
  • prd-creator: Request updates according to requirement changes → Execute document-reviewer for consistency check
  • document-reviewer: Always execute before user approval after PRD/ADR/Design Doc creation/update, and after Work Plan creation/update at Medium/Large scale (Small uses a simplified plan with no semantic review — no Design Doc to trace against)

Basic Flow: Planning and Implementation

Always start with requirement-analyzer, then select the minimum planning flow required by scale and affected layers.

Planning flow (per scale)

Scale Planning flow (ends at task-decomposer for Medium/Large; ends at work-planner for Small)
Large requirement-analyzer → PRD → PRD review → external resource hearing → optional ADR → codebase-analyzer (+ ui-analyzer in parallel for frontend/fullstack) → optional UI Spec → Design Doc → code-verifier → document-reviewer → design-sync → acceptance-test-generator → work-planner → work plan review (document-reviewer, doc_type WorkPlan) → task-decomposer
Medium requirement-analyzer → external resource hearing → codebase-analyzer (+ ui-analyzer in parallel for frontend/fullstack) → optional UI Spec → optional ADR → Design Doc → code-verifier → document-reviewer → design-sync → acceptance-test-generator → work-planner → work plan review (document-reviewer, doc_type WorkPlan) → task-decomposer
Small requirement-analyzer → work-planner

External resource hearing runs in the orchestrator (it requires AskUserQuestion). ui-analyzer joins codebase-analyzer in parallel only when the work has a frontend surface; for backend-only work the planning flow uses codebase-analyzer alone.

After the planning flow completes and the user grants batch approval, implementation proceeds. Verifying the plan is implementable end-to-end (verification lanes, fixtures, E2E environment) is an optional preflight the user runs at their discretion via the recipe-prepare-implementation recipe; this guide does not invoke any orchestrator above the agent layer.

Then execute the task execution cycle: task-executor → quality-fixer → commit for each task. See "Autonomous Execution Mode" below for full per-task details. At Small scale this cycle still applies — implementation runs through task-executor, not orchestrator-direct edits.

Each agent name in the chain is invoked via the Agent tool (per "Orchestrator's Permitted Tools" above).

Rules:

  • Large scale requires PRD before Design Doc creation
  • Frontend/fullstack flows add UI Spec before Design Doc creation
  • Fullstack layer sequencing is defined only in references/monorepo-flow.md
  • design-sync is required whenever multiple Design Docs exist
  • task-decomposer begins only after work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) and batch approval
  • Work plan review self-heals: on verdict.decision needs_revision, route back to work-planner (update) and re-review until approved/approved_with_conditions; rejected escalates to the user. The work plan is a derivation of the Design Doc, so plan-fidelity findings need no user adjudication

Autonomous Execution Mode

Pre-Execution Environment Check

Principle: Verify subagents can complete their responsibilities

Required environments:

  • Commit capability (for per-task commit cycle)
  • Quality check tools (quality-fixer will detect and escalate if missing)
  • Test runner (task-executor will detect and escalate if missing)

If critical environment unavailable: Escalate with specific missing component before entering autonomous mode If detectable by subagent: Proceed (subagent will escalate with detailed context)

Authority Delegation

After environment check passes:

  • Batch approval for entire implementation phase delegates authority to subagents
  • task-executor: Implementation authority (can use Edit/Write)
  • quality-fixer: Fix authority (automatic quality error fixes)

Definition of Autonomous Execution Mode

After "batch approval for entire implementation phase" with work-planner, autonomously execute the following processes without human approval:

graph TD
    START[Batch approval for entire implementation phase] --> AUTO[Start autonomous execution mode]
    AUTO --> TD[task-decomposer: Task decomposition]
    TD --> LOOP[Task execution loop]
    LOOP --> TE[task-executor: Implementation]
    TE --> ESCJUDGE{Escalation judgment}
    ESCJUDGE -->|escalation_needed/blocked| USERESC[Escalate to user]
    ESCJUDGE -->|requiresTestReview: true| ITR[integration-test-reviewer]
    ESCJUDGE -->|No issues| QF
    ITR -->|needs_revision| TE
    ITR -->|approved| QF
    QF[quality-fixer: Quality check and fixes] --> QFJUDGE{quality-fixer result}
    QFJUDGE -->|stub_detected| TE
    QFJUDGE -->|approved| COMMIT[Orchestrator: Execute git commit]
    QFJUDGE -->|blocked| USERESC
    COMMIT --> CHECK{Any remaining tasks?}
    CHECK -->|Yes| LOOP
    CHECK -->|No| VERIFY[Post-implementation verification]
    VERIFY --> CV[code-verifier: DD consistency check]
    VERIFY --> SEC[security-reviewer: Security review]
    CV --> VRESULT{Verification results}
    SEC --> VRESULT
    VRESULT -->|All passed| REPORT[Completion report]
    VRESULT -->|Any failed| VFIX[task-executor: Verification fixes]
    VFIX --> QF2[quality-fixer: Quality check]
    QF2 --> REVERIFY[Re-run failed verifiers only]
    REVERIFY --> VRESULT
    VRESULT -->|blocked| USERESC

    LOOP --> INTERRUPT{User input?}
    INTERRUPT -->|None| TE
    INTERRUPT -->|Yes| REQCHECK{Requirement change check}
    REQCHECK -->|No change| TE
    REQCHECK -->|Change| STOP[Stop autonomous execution]
    STOP --> RA[Re-analyze with requirement-analyzer]

Post-Implementation Verification Pass/Fail Criteria

Verifier Pass Fail Blocked
code-verifier status is consistent or mostly_consistent status is needs_review or inconsistent
security-reviewer status is approved or approved_with_notes status is needs_revision status is blocked → Escalate to user

Re-run rule: After fix cycle, re-run only verifiers that returned fail. Verifiers that passed on the previous run are not re-run.

Conditions for Stopping Autonomous Execution

Stop autonomous execution and escalate to user in the following cases:

  1. Escalation from subagent

    • When receiving response with status: "escalation_needed"
    • When receiving response with status: "blocked"
  2. When requirement change detected

    • Any match in requirement change detection checklist
    • Stop autonomous execution and re-analyze with integrated requirements in requirement-analyzer
  3. When work-planner update restriction is violated

    • Requirement changes after task-decomposer starts require overall redesign
    • Restart entire flow from requirement-analyzer
  4. When user explicitly stops

    • Direct stop instruction or interruption

Task Management: 4-Step Cycle

Per-task cycle:

  1. Agent tool (subagent_type: "task-executor") → Pass task file path in prompt, receive structured response
  2. Check task-executor response:
    • status: escalation_needed or blocked → Escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 1 with requiredFixes
      • approved → Proceed to step 3
    • Otherwise → Proceed to step 3
  3. quality-fixer → Quality check and fixes. Always pass the current task file path as task_file
    • stub_detected → Return to step 1 with incompleteImplementations[] details
    • blocked → Escalate to user
    • approved → Proceed to step 4
  4. git commit → Execute with Bash (on approved)

Progress Tracking

Register overall phases using TaskCreate. Update each phase with TaskUpdate as it completes.

Main Orchestrator Roles

  1. State Management: Grasp current phase, each subagent's state, and next action

  2. Information Bridging: Data conversion and transmission between subagents

    • Convert each subagent's output to next subagent's input format
    • Always pass deliverables from previous process to next agent
    • Extract necessary information from structured responses
    • Compose commit messages from changeSummary
    • Explicitly integrate initial and additional requirements when requirements change

    Handoff Contracts

    HC-01: requirement-analyzer → codebase-analyzer

    • Pass: requirement_analysis, prd_path (if exists), original user requirements

    HC-02: codebase-analyzer → technical-designer

    • Pass: full codebase-analyzer JSON as additional context
    • Required downstream uses:
      • focusAreas → canonical disposition-target list for the Fact Disposition Table
      • dataModel, dataTransformationPipelines, qualityAssurance → Existing Codebase Analysis / Verification Strategy / Quality Assurance sections

    HC-03: technical-designer → code-verifier

    • Pass: Design Doc path (doc_type: design-doc)
    • Do not pass code_paths; code-verifier discovers scope from the document

    HC-04: code-verifier + codebase-analyzer → document-reviewer

    • Pass: code_verification JSON and the same codebase_analysis JSON previously given to the designer
    • Purpose: reviewer validates both discrepancy integration and Fact Disposition coverage against focusAreas

    HC-05: code-verifier → next-layer technical-designer (fullstack only)

    • Defined only for multi-layer fullstack flow in references/monorepo-flow.md
    • Pass: prior-layer Design Doc path plus prior_layer_verification
    • Use only discrepancies[] as known issues to address or escalate. Do not infer verified claims that are not explicitly present in the verifier output.

    technical-designer → work-planner

    Pass to work-planner: Design Doc path. Work-planner reads the DD template from documentation-criteria skill, scans all DD sections, and extracts technical requirements in these categories:

    • Verification Strategy: Extracted to work plan header (Correctness Proof Method + Early Verification Point)
    • Implementation targets: Components, functions, or data structures to create or modify
    • Connection/switching/registration: Integration points, dependency wiring, switching methods
    • Contract changes and propagation: Interface changes, data contracts, field propagation across boundaries
    • Verification requirements: Verification methods, test boundaries, integration verification points
    • Prerequisite work: Migration steps, security measures, environment setup

    Work-planner produces a Design-to-Plan Traceability table mapping each extracted item to covering task(s). Items without a covering task must be marked as gap with justification. Unjustified gaps are errors. Justified gaps require user confirmation before plan approval.

    HC-06: acceptance-test-generator → work-planner

    Pass to acceptance-test-generator: Design Doc path; UI Spec path (if exists).

    Orchestrator verification: Every non-null generatedFiles.<lane> path exists on disk. For each null lane, e2eAbsenceReason.<lane> is present (intentional absence, not an error).

    Pass to work-planner: integration / fixture-e2e / service-integration-e2e file paths (or null per lane), per-lane absence reasons, plus timing guidance — integration tests are created alongside each phase implementation, fixture-e2e tests are created alongside the UI feature phase, service-integration-e2e tests are executed only in the final phase.

    On error: Escalate to user when status != completed and integration file generation failed unexpectedly. A null E2E lane with a valid absence reason is not an error.

  3. ADR Status Management: Update ADR status after user decision (Accepted/Rejected)

Important Constraints

Recap (defined above): quality-fixer approval before commit; inter-agent communication is JSON; document-reviewer + user approval before proceeding; check next step against work planning flow after approval; resolve conflicts via Decision precedence.

References

  • references/monorepo-flow.md: Fullstack (monorepo) orchestration flow
执行元认知任务分析与技能选择。通过解析任务本质、估算规模及识别类型,结合标签匹配从技能索引中筛选并排序推荐技能,辅助确定工作复杂度与所需工具。
需要评估任务复杂度和工作量时 决定使用哪些专业技能来完成特定任务时 分析代码修改或功能开发的根本目的时
dev-workflows-fullstack/skills/task-analyzer/SKILL.md
npx skills add shinpr/claude-code-workflows --skill task-analyzer -g -y
SKILL.md
Frontmatter
{
    "name": "task-analyzer",
    "description": "Performs metacognitive task analysis and skill selection. Use when determining task complexity, selecting appropriate skills, or estimating work scale."
}

Task Analyzer

Provides metacognitive task analysis and skill selection guidance.

Skills Index

See skills-index.yaml for available skills metadata.

Task Analysis Process

1. Understand Task Essence

Identify the fundamental purpose beyond surface-level work:

Surface Work Fundamental Purpose
"Fix this bug" Problem solving, root cause analysis
"Implement this feature" Feature addition, value delivery
"Refactor this code" Quality improvement, maintainability
"Update this file" Change management, consistency

Action: Map the user request to one row in the Surface Work → Fundamental Purpose table above. If no row matches, state the fundamental purpose explicitly before proceeding.

2. Estimate Task Scale

Scale File Count Indicators
Small 1-2 Single function/component change
Medium 3-5 Multiple related components
Large 6+ Cross-cutting concerns, architecture impact

Scale affects skill priority:

  • Scale >= Large → include documentation-criteria and implementation-approach in selectedSkills with priority high
  • Scale = Small → limit selectedSkills to task-type essential skills only (max 3)

3. Identify Task Type

Type Characteristics Key Skills
Implementation New code, features coding-principles, testing-principles
Fix Bug resolution ai-development-guide, testing-principles
Refactoring Structure improvement coding-principles, ai-development-guide
Design Architecture decisions documentation-criteria, implementation-approach
Quality Testing, review testing-principles, integration-e2e-testing

4. Tag-Based Skill Matching

Extract relevant tags from task description and match against skills-index.yaml:

Task: "Implement user authentication with tests"
Extracted tags: [implementation, testing, security]
Matched skills:
  - coding-principles (implementation, security)
  - testing-principles (testing)
  - ai-development-guide (implementation)

5. Implicit Relationships

Consider hidden dependencies:

Task Involves Also Include
Error handling debugging, testing
New features design, implementation, documentation
Performance profiling, optimization, testing
Frontend typescript-rules, test-implement
API/Integration integration-e2e-testing

Output Format

Return structured analysis with skill metadata from skills-index.yaml:

taskAnalysis:
  essence: <string>  # Fundamental purpose identified
  type: <implementation|fix|refactoring|design|quality>
  scale: <small|medium|large>
  estimatedFiles: <number>
  tags: [<string>, ...]  # Extracted from task description

selectedSkills:
  - skill: <skill-name>  # From skills-index.yaml
    priority: <high|medium|low>
    reason: <string>  # Why this skill was selected
    # Pass through metadata from skills-index.yaml
    tags: [...]
    typical-use: <string>
    size: <small|medium|large>
    sections: [...]  # All sections from yaml, unfiltered

Note: Section selection (choosing which sections are relevant) is done after reading the actual SKILL.md files.

Skill Selection Priority

  1. Essential - Directly related to task type
  2. Quality - Testing and quality assurance
  3. Process - Workflow and documentation
  4. Supplementary - Reference and best practices

Metacognitive Question Design

Generate 3-5 questions according to task nature:

Task Type Question Focus
Implementation Design validity, edge cases, performance
Fix Root cause (5 Whys), impact scope, regression testing
Refactoring Current problems, target state, phased plan
Design Requirement clarity, future extensibility, trade-offs

Warning Patterns

Detect and flag these patterns:

Pattern Warning Mitigation
Large change detected Pair with implementation-approach Split into phases per strategy
Implementation task detected Pair with testing-principles Apply TDD from start
Error fix requested Pair with ai-development-guide Apply 5 Whys before fixing
Multi-file task without plan Pair with documentation-criteria Create work plan first
指导如何实施单元测试、集成测试及E2E测试。涵盖React组件测试(RTL+Vitest+MSW)和Playwright E2E测试,遵循AAA结构、测试独立性及用户视角命名规范。
实现单元测试 实现集成测试 实现E2E测试 编写React组件测试 编写Playwright测试
dev-workflows-fullstack/skills/test-implement/SKILL.md
npx skills add shinpr/claude-code-workflows --skill test-implement -g -y
SKILL.md
Frontmatter
{
    "name": "test-implement",
    "description": "Test implementation patterns and conventions. Use when implementing unit tests, integration tests, or E2E tests, including RTL+Vitest+MSW component testing and Playwright E2E testing."
}

Test Implementation Patterns

Reference Selection

Test Type Reference When to Use
Unit / Integration references/frontend.md Implementing React component tests with RTL + Vitest + MSW
E2E references/e2e.md Implementing browser-level E2E tests with Playwright

Common Principles

AAA Structure

All tests follow Arrange-Act-Assert:

  • Arrange: Set up preconditions and inputs
  • Act: Execute the behavior under test
  • Assert: Verify the expected outcome

Test Independence

  • Each test runs independently without depending on other tests
  • No shared mutable state between tests
  • Deterministic execution — no random or time dependencies without mocking

Naming

  • Test names describe expected behavior from user perspective
  • One test verifies one behavior
提供语言无关的测试原则,涵盖TDD红绿重构循环、AAA模式及测试质量要求。适用于编写测试、设计测试策略或审查测试质量时参考,强调独立、可重现及高效测试。
编写单元测试或集成测试 设计整体测试策略 审查现有测试代码的质量
dev-workflows-fullstack/skills/testing-principles/SKILL.md
npx skills add shinpr/claude-code-workflows --skill testing-principles -g -y
SKILL.md
Frontmatter
{
    "name": "testing-principles",
    "description": "Language-agnostic testing principles including TDD, test quality, coverage standards, and test design patterns. Use when writing tests, designing test strategies, or reviewing test quality."
}

Language-Agnostic Testing Principles

Test-Driven Development (TDD)

The RED-GREEN-REFACTOR Cycle

Always follow this cycle:

  1. RED: Write a failing test first

    • Write the test before implementation
    • Ensure the test fails for the right reason
    • Verify test can actually fail
  2. GREEN: Write minimal code to pass

    • Implement just enough to make the test pass
    • Focus on making it work
  3. REFACTOR: Improve code structure

    • Clean up implementation
    • Eliminate duplication
    • Improve naming and clarity
    • Keep all tests passing
  4. VERIFY: Ensure all tests still pass

    • Run full test suite
    • Check for regressions
    • Validate refactoring didn't break anything

Quality Requirements

Coverage

  • Treat coverage as a diagnostic signal for finding untested areas, not a target — a target gets gamed into trivial tests (Goodhart's Law)
  • Concentrate tests on critical paths, business logic, and behavior whose regression would matter
  • Prioritize meaningful assertions over the coverage number; any CI threshold is the project's config, not a quality goal in itself

Test Characteristics

All tests must be:

  • Independent: No dependencies between tests (see Test Independence Verification for detailed criteria)
  • Reproducible: Same input always produces same output
  • Fast: Unit tests < 100ms each, integration tests < 1s each, full suite < 10 minutes
  • Self-checking: Clear pass/fail without manual verification
  • Timely: Written close to the code they test

Test Types

Unit Tests

Purpose: Test individual components in isolation

Characteristics:

  • Test single function, method, or class
  • Fast execution (milliseconds)
  • No external dependencies
  • Mock external services
  • Majority of your test suite

Integration Tests

Purpose: Test interactions between components

Characteristics:

  • Test multiple components together
  • May include database, file system, or APIs
  • Slower than unit tests
  • Verify contracts between modules
  • Smaller portion of test suite

End-to-End (E2E) Tests

Purpose: Test complete workflows from user perspective

Characteristics:

  • Test entire application stack
  • Simulate real user interactions
  • Slowest test type
  • Fewest in number
  • Highest confidence level

Test Design Principles

AAA Pattern (Arrange-Act-Assert)

Structure every test in three clear phases:

// Arrange: Setup test data and conditions
user = createTestUser()
validator = createValidator()

// Act: Execute the code under test
result = validator.validate(user)

// Assert: Verify expected outcome
assert(result.isValid == true)

Adaptation: Apply this structure using your language's idioms (methods, functions, procedures)

One Assertion Per Concept

  • Test one behavior per test case
  • Multiple assertions OK if testing single concept
  • Split unrelated assertions into separate tests

Example: prefer returns error when email is invalid over validates user.

Descriptive Test Names

Test names should clearly describe:

  • What is being tested
  • Under what conditions
  • What the expected outcome is

Recommended format: "should [expected behavior] when [condition]"

Examples:

test("should return error when email is invalid")
test("should calculate discount when user is premium")
test("should throw exception when file not found")

Adaptation: Follow your project's naming convention (camelCase, snake_case, describe/it blocks)

Test Independence

Setup and Teardown

  • Use setup hooks to prepare test environment
  • Use teardown hooks to clean up resources
  • Keep setup minimal and focused
  • Ensure teardown runs even if test fails

Mocking and Test Doubles

When to Use Mocks

  • Mock external dependencies: APIs, databases, file systems
  • Mock slow operations: Network calls, heavy computations
  • Mock unpredictable behavior: Random values, current time
  • Mock unavailable services: Third-party services

Mocking Principles

  • Mock at boundaries, not internally
  • Keep mocks simple and focused
  • Verify mock expectations when relevant
  • Wrap external libraries/frameworks behind adapters and mock the adapter

Data Layer Testing

Mock Limitations for Data Layer

Mocks validate call patterns but cannot verify data layer correctness. The following pass through undetected with mock-only testing:

  • Schema mismatches (table names, column names, data types)
  • Query correctness (joins, filters, aggregations, grouping)
  • Database constraints (NOT NULL, UNIQUE, foreign keys)
  • Migration drift (schema changes that make code out of sync)

When Mocks Are Appropriate for Data Access

  • Testing business logic that receives data from the data layer (mock the repository, test the service)
  • Testing error handling paths (simulating connection failures, timeouts)
  • Unit tests where data access is a dependency, not the subject under test

When Mocks Are Insufficient for Data Access

  • Testing repository or data access implementations themselves
  • Verifying query correctness (joins, filters, aggregations, grouping)
  • Testing data integrity constraints
  • Testing migration compatibility

Real Database Testing (Environment-Dependent)

Options for verifying data layer correctness against a real database engine:

  • Containerized databases for CI environments
  • In-memory databases for fast feedback (note: dialect differences may mask issues)
  • Dedicated test databases with seed data

The appropriate approach depends on project environment and CI/CD capabilities.

AI-Generated Code and Schema Awareness

  • AI-generated data access code has heightened schema hallucination risk
  • Generated queries may use correct syntax but reference nonexistent schema elements
  • Mock-based tests pass regardless of schema accuracy
  • Mitigation: Design Docs should include explicit schema references so that documented schemas can be cross-checked against data access code during review

Test Quality Practices

Keep Tests Active

  • Fix or delete failing tests: Resolve failures immediately
  • Remove commented-out tests: Fix them or delete entirely
  • Keep tests running: Broken tests lose value quickly
  • Maintain test suite: Refactor tests as needed

Test Helpers and Utilities

  • Create reusable test data builders
  • Extract common setup into helper functions
  • Build test utilities for complex scenarios
  • Share helpers across test files appropriately

What to Test

Focus on Behavior

Test observable behavior, not implementation:

Good: Test that function returns expected output ✓ Good: Test that correct API endpoint is called ✗ Bad: Test that internal variable was set ✗ Bad: Test order of private method calls

Test Public APIs

  • Test through public interfaces
  • Avoid testing private methods directly
  • Test return values, outputs, exceptions
  • Test side effects (database, files, logs)

Test Edge Cases

Always test:

  • Boundary conditions: Min/max values, empty collections
  • Error cases: Invalid input, null values, missing data
  • Edge cases: Special characters, extreme values
  • Happy path: Normal, expected usage

Test Quality Criteria

These criteria ensure reliable, maintainable tests.

Literal Expected Values

  • Use hardcoded literal values in assertions
  • Calculate expected values independently from the implementation
  • If the implementation has a bug, the test catches it through independent verification
  • If expected value equals mock return value unchanged, the test verifies nothing (no transformation occurred)

Result-Based Verification

  • Verify final results and observable outcomes
  • Assert on return values, output data, or system state changes
  • For mock verification, check that correct arguments were passed

Meaningful Assertions

  • Every test must include at least one assertion
  • Assertions must validate observable behavior
  • A test without assertions always passes and provides no value

Appropriate Mock Scope

  • Mock direct external I/O dependencies: databases, HTTP clients, file systems
  • Use real implementations for internal utilities and business logic
  • Over-mocking reduces test value by verifying wiring instead of behavior

Boundary Value Testing

Test at boundaries of valid input ranges:

  • Minimum valid value
  • Maximum valid value
  • Just below minimum (invalid)
  • Just above maximum (invalid)
  • Empty input (where applicable)

Test Independence Verification

Each test must:

  • Create its own test data
  • Not depend on execution order
  • Clean up its own state
  • Pass when run in isolation

Verification Requirements

Before Commit

  • ✓ All tests pass — fix failing tests immediately
  • ✓ No tests skipped or commented — delete or fix
  • ✓ No debug code left in tests
  • ✓ Test coverage meets standards
  • ✓ No flaky tests — make deterministic
  • ✓ Tests run within performance thresholds

Test Organization

File Structure

  • Mirror production structure: Tests follow code organization
  • Clear naming conventions: Follow project's test file patterns
    • Examples: UserService.test.*, user_service_test.*, test_user_service.*, UserServiceTests.*
  • Logical grouping: Group related tests together
  • Separate test types: Unit, integration, e2e in separate directories

Performance Considerations

Test Speed

  • Unit tests: < 100ms each
  • Integration tests: < 1s each
  • Full suite: Should run frequently (< 10 minutes)

Optimization Strategies

  • Run tests in parallel when possible
  • Use in-memory databases for tests
  • Mock expensive operations
  • Split slow test suites
  • Profile and optimize slow tests

Continuous Integration

CI/CD Requirements

  • Run full test suite on every commit
  • Block merges if tests fail
  • Run tests in isolated environments
  • Test on target platforms/versions

Test Reports

  • Generate coverage reports
  • Track test execution time
  • Identify flaky tests
  • Monitor test trends

Test Design Guardrails

Every Test Must

  • Include at least one meaningful assertion
  • Create its own test data and clean up its own state
  • Pass when run in any order and in isolation
  • Test observable behavior through public interfaces
  • Keep test logic simple (no branching, no loops)
  • Mock only external I/O boundaries, use real implementations for internal logic

Flaky Test Resolution

  • Use deterministic time mocking instead of real clocks
  • Use fixed seed values instead of random data
  • Ensure proper resource cleanup in teardown
  • Resolve race conditions with synchronization primitives

Regression Testing

Prevent Regressions

  • Add test for every bug fix
  • Maintain comprehensive test suite
  • Run full suite regularly
  • Keep all tests unless the tested functionality is removed

Legacy Code

  • Add characterization tests before refactoring
  • Test existing behavior first
  • Gradually improve coverage
  • Refactor with confidence

Testing Best Practices by Language Paradigm

Type System Utilization

For languages with static type systems:

  • Leverage compile-time verification for correctness
  • Focus tests on business logic and runtime behavior
  • Use language's type system to prevent invalid states

For languages with dynamic typing:

  • Add comprehensive runtime validation tests
  • Explicitly test data contract validation
  • Consider property-based testing for broader coverage

Programming Paradigm Considerations

Functional approach:

  • Test pure functions thoroughly (deterministic, no side effects)
  • Test side effects at system boundaries
  • Leverage property-based testing for invariants

Object-oriented approach:

  • Test behavior through public interfaces
  • Mock dependencies via abstraction layers
  • Test polymorphic behavior carefully

Common principle: Adapt testing strategy to leverage language strengths while ensuring comprehensive coverage

Documentation and Communication

Tests as Documentation

  • Tests document expected behavior
  • Use clear, descriptive test names
  • Include examples of usage
  • Show edge cases and error handling

Test Failure Messages

  • Provide clear, actionable error messages
  • Include actual vs expected values
  • Add context about what was being tested
  • Make debugging easier
提供React与TypeScript前端开发规范,涵盖类型安全、组件设计、状态管理及错误处理。指导代码重构、注释编写及类型推断,确保代码健壮性与可维护性。
实现React组件 编写TypeScript代码 前端功能开发 处理API响应类型
dev-workflows-fullstack/skills/typescript-rules/SKILL.md
npx skills add shinpr/claude-code-workflows --skill typescript-rules -g -y
SKILL.md
Frontmatter
{
    "name": "typescript-rules",
    "description": "React\/TypeScript frontend development rules including type safety, component design, state management, and error handling. Use when implementing React components, TypeScript code, or frontend features."
}

TypeScript Development Rules (Frontend)

Basic Principles

  • Aggressive Refactoring - Prevent technical debt and maintain health
  • Delete code when no current caller exists - YAGNI principle (Kent Beck)

Comment Writing Rules

Code first: names and types carry meaning; a comment must add what code cannot, and one comment per decision is enough. Frontend specifics:

  • Comment intent, not markup: explain why a component memoizes, guards, or re-renders — not what the JSX renders
  • Timeless content only: Record decisions and rationale; leave chronological history to version control

Type Safety

Absolute Rule: Replace every any with unknown, generics, or union types. any disables type checking and causes runtime errors.

any Type Alternatives (Priority Order)

  1. unknown Type + Type Guards: Use for validating external input (API responses, localStorage, URL parameters)
  2. Generics: When type flexibility is needed
  3. Union Types・Intersection Types: Combinations of multiple types
  4. Type Assertions (Last Resort): Only when type is certain

Type Guard Implementation Pattern

function isUser(value: unknown): value is User {
  return typeof value === 'object' && value !== null && 'id' in value && 'name' in value
}

Modern Type Features

  • satisfies Operator: const config = { apiUrl: '/api' } satisfies Config - Preserves inference
  • const Assertion: const ROUTES = { HOME: '/' } as const satisfies Routes - Immutable and type-safe
  • Branded Types: type UserId = string & { __brand: 'UserId' } - Distinguish meaning
  • Template Literal Types: type EventName = \on${Capitalize}`` - Express string patterns with types

Type Safety in Frontend Implementation

  • React Props/State: TypeScript manages types, unknown unnecessary
  • External API Responses: Always receive as unknown, validate with type guards
  • localStorage/sessionStorage: Treat as unknown, validate
  • URL Parameters: Treat as unknown, validate
  • Form Input (Controlled Components): Type-safe with React synthetic events

Type Safety in Data Flow

  • Frontend → Backend: Props/State (Type Guaranteed) → API Request (Serialization)
  • Backend → Frontend: API Response (unknown) → Type Guard → State (Type Guaranteed)

Type Complexity Management

  • Props Design:
    • Props count: 3-7 props ideal (consider component splitting if exceeds 10)
    • Optional Props: 50% or less (consider default values or Context if excessive)
    • Nesting: Up to 2 levels (flatten deeper structures)
  • Type Assertions: Review design if used 3+ times
  • External API Types: Relax constraints and define according to reality (convert appropriately internally)

Coding Conventions

Component Design Criteria

  • Function components only: Official React recommendation, optimizable by modern tooling (Exception: Error Boundary requires class component)
  • Custom Hooks: Standard pattern for logic reuse and dependency injection
  • Component Hierarchy: Use the project's adopted component architecture. When the project uses Atomic Design: Atoms → Molecules → Organisms → Templates → Pages. When the project uses Feature-based, Container-Presenter, or another structure: follow that structure consistently and document the chosen layering in the project README or design doc
  • Co-location: Place tests, styles, and related files alongside components

Server/Client Boundary (RSC frameworks only — e.g., Next.js App Router)

  • Default to server components for data fetching and rendering; isolate interactivity behind a "use client" boundary at the smallest scope that needs it
  • Keep browser-only APIs (window, localStorage, event handlers) inside client components; calling them in a server component breaks the render
  • N/A for client-only SPAs (e.g., Vite) — skip when the project has no server-component runtime

State Management Patterns

  • Local State: useState for component-specific state
  • Context API: For sharing state across component tree (theme, auth, etc.)
  • Custom Hooks: Encapsulate state logic and side effects
  • Server State: React Query or SWR for API data caching

Data Flow Principles

  • Single Source of Truth: Each piece of state has one authoritative source
  • Unidirectional Flow: Data flows top-down via props
  • Immutable Updates: Use immutable patterns for state updates
// Immutable state update — always create new arrays/objects
setUsers(prev => [...prev, newUser])

Function Design

  • 0-2 parameters maximum: Use object for 3+ parameters
    function createUser({ name, email, role }: CreateUserParams) {}
    

Props Design (Props-driven Approach)

  • Props are the interface: Define all necessary information as props
  • Pass all data dependencies as props; use Context only for cross-cutting concerns (theme, auth, locale)
  • Type-safe: Always define Props type explicitly

Environment Variables

  • Use the build tool's env accessor: read client-side env through the bundler's exposed accessor — Vite via import.meta.env, Next.js/CRA via prefixed process.env. Raw, unprefixed access is undefined in the browser bundle
  • Only prefixed vars reach the client: build tools expose only vars carrying their public prefix; an unprefixed var is undefined in the browser. The prefix differs per tool — match the project's bundler (Vite VITE_, Next.js public NEXT_PUBLIC_, CRA REACT_APP_)
  • Centrally manage env through a typed config object with a default for every variable
// Client-exposed env must carry the bundler's public prefix, or it is undefined in the browser.
// Vite:    import.meta.env.VITE_API_URL
// Next.js: process.env.NEXT_PUBLIC_API_URL
const config = {
  apiUrl: import.meta.env.VITE_API_URL || 'http://localhost:3000', // adjust accessor + prefix to the project's bundler
  appName: import.meta.env.VITE_APP_NAME || 'My App'
}

Security (Client-side Constraints)

  • CRITICAL: All frontend code is public and visible in browser
  • All secrets stay server-side: Store API keys, tokens, and secrets on the backend only
  • Exclude .env files via .gitignore
  • Limit error messages to non-sensitive context
// Backend manages secrets, frontend accesses via proxy
const response = await fetch('/api/data') // Backend handles API key authentication

Dependency Injection

  • Custom Hooks for dependency injection: Ensure testability and modularity

Asynchronous Processing

  • Promise Handling: Always use async/await
  • Error Handling: Always handle with try-catch or Error Boundary
  • Type Definition: Explicitly define return value types (e.g., Promise<Result>)
  • Effect race/cleanup: guard useEffect data fetches against out-of-order responses and post-unmount state updates — abort or ignore stale results (AbortController or a mounted flag), or use a server-state library (React Query/SWR) that cancels and dedupes. try-catch alone does not cover this

Format Rules

  • Semicolon omission (follow Biome settings)
  • Types in PascalCase, variables/functions in camelCase
  • Imports use absolute paths (src/)

Clean Code Principles

  • Delete unused code immediately
  • Delete debug console.log()
  • Delete commented-out code (retrieve from version control when needed)
  • Comments explain "why" (not "what")

Error Handling

Absolute Rule: Every caught error must be logged with context and either re-thrown to Error Boundary, returned as a Result error variant, or displayed as user-facing error state.

Fail-Fast Principle: Fail quickly on errors to prevent continued processing in invalid states

catch (error) {
  logger.error('Processing failed', error)
  throw error // Handle with Error Boundary or higher layer
}

Result Type Pattern: Express errors with types for explicit handling

type Result<T, E> = { ok: true; value: T } | { ok: false; error: E }

// Example: Express error possibility with types
function parseUser(data: unknown): Result<User, ValidationError> {
  if (!isValid(data)) return { ok: false, error: new ValidationError() }
  return { ok: true, value: data as User }
}

Custom Error Classes

export class AppError extends Error {
  constructor(message: string, public readonly code: string, public readonly statusCode = 500) {
    super(message)
    this.name = this.constructor.name
  }
}
// Purpose-specific: ValidationError(400), ApiError(502), NotFoundError(404)

Layer-Specific Error Handling (React)

  • Error Boundary: Catch React component errors, display fallback UI
  • Custom Hook: Detect business rule violations, propagate AppError as-is
  • API Layer: Convert fetch errors to domain errors

Structured Logging and Sensitive Information Protection Redact sensitive fields (password, token, apiKey, secret, creditCard) before logging

Asynchronous Error Handling in React

  • Error Boundary setup mandatory: Catch rendering errors
  • Use try-catch with all async/await in event handlers
  • Always log and re-throw errors or display error state

Refactoring Techniques

Basic Policy

  • Small Steps: Maintain always-working state through gradual improvements
  • Safe Changes: Minimize the scope of changes at once
  • Behavior Guarantee: Ensure existing behavior remains unchanged while proceeding

Implementation Procedure: Understand Current State → Gradual Changes → Behavior Verification → Final Validation

Priority: Duplicate Code Removal > Large Function Division > Complex Conditional Branch Simplification > Type Safety Improvement

Performance Optimization

  • Automatic memoization: when React Compiler is enabled, rely on it; reach for manual React.memo/useMemo/useCallback only as a profiler- or identity-justified escape hatch (a measured bottleneck, or stable reference identity for third-party APIs / effect dependencies)
  • State Optimization: Minimize re-renders with proper state structure
  • Lazy Loading: Use React.lazy and Suspense for code splitting
  • Bundle Size: Monitor via the build script against the project's budget

Non-functional Requirements

  • Browser Compatibility: Chrome/Firefox/Safari/Edge (latest 2 versions)
  • Rendering Time: Within 5 seconds for major pages
提供技术决策标准、反模式检测及调试技巧,指导代码质量审查。适用于识别SRP/DRY违规、错误处理设计缺陷,确保错误可见性,防止掩盖问题,提升系统可靠性与可维护性。
进行技术架构或代码设计决策时 检测代码异味或违反设计原则时 执行代码质量保证与审查时 设计错误处理与降级策略时
dev-workflows/skills/ai-development-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill ai-development-guide -g -y
SKILL.md
Frontmatter
{
    "name": "ai-development-guide",
    "description": "Technical decision criteria, anti-pattern detection, debugging techniques, and quality check workflow. Use when making technical decisions, detecting code smells, or performing quality assurance."
}

AI Developer Guide - Technical Decision Criteria and Anti-pattern Collection

Technical Anti-patterns (Red Flag Patterns)

Immediately stop and reconsider design when detecting the following patterns:

Code Quality Anti-patterns

  1. Writing similar code 3 or more times - Violates Rule of Three
  2. Multiple responsibilities mixed in a single file - Violates Single Responsibility Principle (SRP)
  3. Defining same content in multiple files - Violates DRY principle
  4. Making changes without checking dependencies - Potential for unexpected impacts
  5. Disabling code with comments - Should use version control
  6. Error suppression - Hiding problems creates technical debt
  7. Bypassing safety mechanisms (type systems, validation, contracts) - Circumventing language's correctness guarantees

Design Anti-patterns

  • "Make it work for now" thinking - Accumulation of technical debt
  • Patchwork implementation - Unplanned additions to existing code
  • Optimistic implementation of uncertain technology - Designing unknown elements assuming "it'll probably work"
  • Symptomatic fixes - Surface-level fixes that don't solve root causes
  • Unplanned large-scale changes - Lack of incremental approach

Fail-Fast Fallback Design Principles

Core Principle

Make all errors visible and traceable with full context. Prioritize primary code reliability over fallback implementations. Excessive fallback mechanisms mask errors and make debugging difficult.

Implementation Guidelines

Default Approach

  • Propagate all errors explicitly unless a Design Doc specifies a fallback
  • Make failures explicit: Errors should be visible and traceable
  • Preserve error context: Include original error information when re-throwing

When Fallbacks Are Acceptable

  • Only with explicit Design Doc approval: Document why fallback is necessary
  • Business-critical continuity: When partial functionality is better than none
  • Graceful degradation paths: Clearly defined degraded service levels

Layer Responsibilities

  • Infrastructure Layer:

    • Always throw errors upward
    • No business logic decisions
    • Provide detailed error context
  • Application Layer:

    • Make business-driven error handling decisions
    • Implement fallbacks only when specified in requirements
    • Log all fallback activations for monitoring

Error Masking Detection

Review Triggers (require design review):

  • Writing 3rd error handler in the same feature
  • Multiple error handling blocks in single function/method
  • Nested error handling structures
  • Error handlers that return default values without logging

Before Implementing Any Fallback:

  1. Verify Design Doc explicitly defines this fallback
  2. Document the business justification
  3. Ensure error is logged with full context
  4. Add monitoring/alerting for fallback activation

Implementation Pattern

AVOID: Silent fallback that hides errors
    <handle error>:
        return DEFAULT_VALUE  // Error hidden, debugging impossible

PREFERRED: Explicit failure with context
    <handle error>:
        log_error('Operation failed', context, error)
        <propagate error>  // Re-throw exception, return Error, return error tuple

Adaptation: Use language-appropriate error handling (exceptions, Result types, error tuples, etc.)

Rule of Three - Criteria for Code Duplication

How to handle duplicate code based on Martin Fowler's "Refactoring":

Duplication Count Action Reason
1st time Inline implementation Cannot predict future changes
2nd time Consider future consolidation Pattern beginning to emerge
3rd time Implement commonalization Pattern established

Criteria for Commonalization

Cases for Commonalization

  • Business logic duplication
  • Complex processing algorithms
  • Areas likely requiring bulk changes
  • Validation rules

Cases to Avoid Commonalization

  • Accidental matches (coincidentally same code)
  • Possibility of evolving in different directions
  • Significant readability decrease from commonalization
  • Simple helpers in test code

Common Failure Patterns and Avoidance Methods

Pattern 1: Error Fix Chain

Symptom: Fixing one error causes new errors Cause: Surface-level fixes without understanding root cause Avoidance: Identify root cause with 5 Whys before fixing

Pattern 2: Circumventing Correctness Guarantees

Symptom: Bypassing safety mechanisms (type systems, validation, contracts) Cause: Impulse to avoid correctness errors Avoidance: Use language-appropriate safety mechanisms (static checking, runtime validation, contracts, assertions)

Pattern 3: Implementation Without Sufficient Testing

Symptom: Many bugs after implementation Cause: Ignoring Red-Green-Refactor process Avoidance: Always start with failing tests

Pattern 4: Ignoring Technical Uncertainty

Symptom: Frequent unexpected errors when introducing new technology Cause: Assuming "it should work according to official documentation" without prior investigation Avoidance:

  • Record certainty evaluation at the beginning of task files
    Certainty: low (Reason: no working examples found for this integration)
    Exploratory implementation: true
    Fallback: use established alternative approach
    
  • For low certainty cases, create minimal verification code first

Pattern 5: Insufficient Existing Code Investigation

Symptom: Duplicate implementations, architecture inconsistency, integration failures, adopting outdated patterns Cause: Insufficient understanding of existing code before implementation; referencing only nearby files without verifying representativeness Avoidance Methods:

  • Before implementation, always search for similar functionality (using domain, responsibility, configuration patterns as keywords)
  • Similar functionality found → Use that implementation (do not create new implementation)
  • Similar functionality is technical debt → Create ADR improvement proposal before implementation
  • No similar functionality exists → Implement new functionality following existing design philosophy
  • Record all decisions and rationale in "Existing Codebase Analysis" section of Design Doc
  • Reference representativeness check: When adopting a pattern or dependency from nearby code, verify it is representative across the repository before adopting — nearby files alone are an insufficient basis

Debugging Techniques

1. Error Analysis Procedure

  1. Read error message (first line) accurately
  2. Focus on first and last of stack trace
  3. Identify first line where your code appears

2. 5 Whys - Root Cause Analysis

Trace the failure through repeated "why" questions until the root cause is actionable.

3. Minimal Reproduction Code

To isolate problems, attempt reproduction with minimal code:

  • Remove unrelated parts
  • Replace external dependencies with mocks
  • Create minimal configuration that reproduces problem

4. Debug Log Output

Include operation context, relevant input data, current state, and timestamp.

Quality Assurance Mechanism Awareness

Before executing quality checks, identify what quality mechanisms exist for the change area:

  • Primary detection: inspect the change area's file types, project manifest, and configuration to identify applicable quality tools
    • Check CI pipeline definitions for checks that cover the affected paths
    • Check for domain-specific linter or validator configurations (e.g., schema validators, API spec validators, configuration file linters)
    • Check for domain-specific constraints in project configuration (naming rules, length limits, format requirements)
  • Supplementary hint: IF task file specifies Quality Assurance Mechanisms → use them as additional hints for which domain-specific checks to look for
  • Include discovered domain-specific checks alongside standard quality phases below

Quality Check Workflow

Universal quality assurance phases applicable to all languages:

Phase 1: Static Analysis

  1. Code Style Checking: Verify adherence to style guidelines
  2. Code Formatting: Ensure consistent formatting
  3. Unused Code Detection: Identify dead code and unused imports/variables
  4. Static Type Checking: Verify type correctness (for statically typed languages)
  5. Static Analysis: Detect potential bugs, security issues, code smells

Phase 2: Build Verification

  1. Compilation/Build: Verify code builds successfully (for compiled languages)
  2. Dependency Resolution: Ensure all dependencies are available and compatible
  3. Resource Validation: Check configuration files, assets are valid

Phase 3: Testing

  1. Unit Tests: Run all unit tests
  2. Integration Tests: Run integration tests
  3. Test Coverage: Measure and verify coverage meets standards
  4. E2E Tests: Run end-to-end tests

Phase 4: Final Quality Gate

All checks must pass before proceeding:

  • Zero static analysis errors
  • Build succeeds
  • All tests pass
  • Coverage meets project-configured threshold

Quality Check Pattern (Language-Agnostic)

Workflow:
1. Format check → 2. Lint/Style → 3. Static analysis →
4. Build/Compile → 5. Unit tests → 6. Coverage check →
7. Integration tests → 8. Final gate

Auto-fix capabilities (when available):
- Format auto-fix
- Lint auto-fix
- Dependency/import organization
- Simple code smell corrections

Situations Requiring Technical Decisions

Timing of Abstraction

  • Extract patterns after writing concrete implementation 3 times
  • Be conscious of YAGNI, implement only currently needed features
  • Prioritize current simplicity over future extensibility

Performance vs Readability

  • Prioritize readability unless profiling identifies a measurable bottleneck (e.g., response time exceeding SLA, memory exceeding allocation)
  • Measure before optimizing
  • Document reason with comments when optimizing

Granularity of Contracts and Interfaces

  • Overly detailed contracts reduce maintainability
  • Design interfaces where each method maps to a single domain operation and parameter types use domain vocabulary
  • Use abstraction mechanisms to reduce duplication

Scope Expansion

  • Apply implementation/edit instructions to the user's or task's specified scope. Escalate before expanding it.
  • Treat explicit quantities and targets ("one", "this file", "only X") as boundaries
  • Copy/move/mirror requests preserve content verbatim; edit content only when requested
  • Port/translation requests preserve intent and behavior; adapt only what the destination context requires
  • Before changing related files, symmetric locations, adjacent behavior, or adding helpful extras, escalate with the proposed expansion

Implementation Completeness Assurance

Impact Analysis: Mandatory 3-Stage Process

Complete these stages sequentially before any implementation:

1. Discovery - Identify all affected code:

  • Implementation references (imports, calls, instantiations)
  • Interface dependencies (contracts, types, data structures)
  • Test coverage
  • Configuration (build configs, env settings, feature flags)
  • Documentation (comments, docs, diagrams)

2. Understanding - Analyze each discovered location:

  • Role and purpose in the system
  • Dependency direction (consumer or provider)
  • Data flow (origin → transformations → destination)
  • Coupling strength

3. Identification - Produce structured report:

## Impact Analysis
### Direct Impact
- [Unit]: [Reason and modification needed]

### Indirect Impact
- [System]: [Integration path → reason]

### Data Flow
[Source] → [Transformation] → [Consumer]

### Risk Assessment
- High: [Complex dependencies, fragile areas]
- Medium: [Moderate coupling, test gaps]
- Low: [Isolated, well-tested areas]

### Implementation Order
1. [Start with lowest risk or deepest dependency]
2. [...]

Critical: Do not implement until all 3 stages are documented

Unused Code Deletion

When unused code is detected:

  • Will it be used in this work? Yes → Implement now | No → Delete now (Git preserves)
  • Applies to: Code, tests, docs, configs, assets

Existing Code Modification

In use? No → Delete
       Yes → Working? No → Delete + Reimplement
                     Yes → Fix/Extend

Principle: Prefer clean implementation over patching broken code

提供语言无关的代码原则,强调可维护性、简洁性和可读性。适用于功能实现、重构及代码审查,指导函数设计、参数管理及错误处理,确保代码质量与长期健康。
实现新功能时参考编码规范 对现有代码进行重构优化 执行代码质量审查
dev-workflows/skills/coding-principles/SKILL.md
npx skills add shinpr/claude-code-workflows --skill coding-principles -g -y
SKILL.md
Frontmatter
{
    "name": "coding-principles",
    "description": "Language-agnostic coding principles for maintainability, readability, and quality. Use when implementing features, refactoring code, or reviewing code quality."
}

Language-Agnostic Coding Principles

Core Philosophy

  1. Maintainability over Speed: Prioritize long-term code health over initial development velocity
  2. Simplicity First: Choose the simplest solution that meets requirements (YAGNI principle)
  3. Minimum Surface for Required Coverage: When introducing maintenance-surface-bearing elements (persistent state, public-contract or cross-boundary fields/props, behavioral modes/flags/variants, reusable abstractions, or component splits), select the smallest design surface that covers the current user-visible requirements and accepted technical constraints (audit, data integrity, compatibility, security, performance, accessibility). Adoption is justified by naming a current requirement or constraint that smaller alternatives fail to cover; value-based arguments serve as tiebreakers. Distinct from YAGNI (time-axis judgment of present vs. future need), this principle governs surface-area minimization at a fixed coverage point.
  4. Explicit over Implicit: Make intentions clear through code structure and naming
  5. Delete over Comment: Remove unused code instead of commenting it out

Code Quality

Continuous Improvement

  • Refactor related code within each change set — address style, naming, or structure issues in the files being modified
  • Improve code structure incrementally
  • Keep the codebase lean and focused
  • Delete unused code immediately

Readability

  • Use meaningful, descriptive names drawn from the problem domain
  • Use full words in names; abbreviations are acceptable only when widely recognized in the domain
  • Use descriptive names; single-letter names are acceptable only for loop counters or well-known conventions (i, j, x, y)
  • Extract magic numbers and strings into named constants
  • Keep code self-documenting where possible

Function Design

Parameter Management

  • Recommended: 0-2 parameters per function
  • For 3+ parameters: Use objects, structs, or dictionaries to group related parameters
  • Example (conceptual):
    // Instead of: createUser(name, email, age, city, country)
    // Use: createUser(userData)
    

Single Responsibility

  • Each function should do one thing well
  • Keep functions small and focused (typically < 50 lines)
  • Extract complex logic into separate, well-named functions
  • Functions should have a single level of abstraction

Function Organization

  • Pure functions when possible (no side effects)
  • Separate data transformation from side effects
  • Use early returns to reduce nesting
  • Keep nesting to a maximum of 3 levels; use early returns or extracted functions to flatten deeper nesting

Error Handling

Error Management Principles

  • Always handle errors: Log with context or propagate explicitly
  • Log appropriately: Include context for debugging
  • Protect sensitive data: Mask or exclude passwords, tokens, PII from logs
  • Fail fast: Detect and report errors as early as possible

Error Propagation

  • Use language-appropriate error handling mechanisms
  • Propagate errors to appropriate handling levels
  • Provide meaningful error messages
  • Include error context when re-throwing

Dependency Management

Loose Coupling via Parameterized Dependencies

  • Inject external dependencies as parameters (constructor injection for classes, function parameters for procedural/functional code)
  • Depend on abstractions, not concrete implementations
  • Minimize inter-module dependencies
  • Facilitate testing through mockable dependencies

Reference Representativeness

Verifying References Before Adoption

When adopting patterns, APIs, or dependencies from existing code:

  • IF referencing only 2-3 nearby files → THEN confirm the pattern is representative by checking usage across the repository before adopting
  • IF multiple approaches coexist in the repository → THEN identify the majority pattern and make a deliberate choice — selecting whichever is nearest is insufficient
  • IF adopting an external dependency (library, plugin, SDK) → THEN verify repository-wide usage distribution for the same dependency; if the appropriate version cannot be determined from repository state alone, escalate
  • IF following an existing pattern → THEN state the reason for following it when an alternative exists (e.g., consistency with surrounding code, avoiding breaking changes, pending coordinated update)

Principle

Nearby code is a starting point for investigation, not a sufficient basis for adoption. Verify that what you reference is representative of the repository's conventions and current best practices before using it as a model.

Performance Considerations

Optimization Approach

  • Measure first: Profile before optimizing
  • Focus on algorithms: Algorithmic complexity > micro-optimizations
  • Use appropriate data structures: Choose based on access patterns
  • Resource management: Handle memory, connections, and files properly

When to Optimize

  • After identifying actual bottlenecks through profiling
  • When performance issues are measurable
  • Optimize only after measurable bottlenecks are identified, not during initial development

Code Organization

Structural Principles

  • Group related functionality: Keep related code together
  • Separate concerns: Domain logic, data access, presentation
  • Consistent naming: Follow project conventions
  • Module cohesion: High cohesion within modules, low coupling between

File Organization

  • One primary responsibility per file
  • Logical grouping of related functions/classes
  • Clear folder structure reflecting architecture
  • Avoid "god files" (files > 500 lines)

Commenting Principles

Default: code first

Names, types, and structure are the primary medium. A comment earns its place only by carrying information the code itself cannot express. When in doubt, improve the name instead of adding a comment.

The test for every comment

A comment is justified only if it answers one of these:

  • Why: reasoning, trade-off, or constraint behind a non-obvious decision
  • Limitation / edge case: a boundary a reader cannot infer from the code
  • Public API contract: behavior, inputs, outputs of an exported interface

One comment per decision. If a comment restates what the names and control flow already show, delete it and rename instead.

Comment Scope

  • Comment the why, limits, and public contracts (per the test above); let names and structure carry everything else, including the "how"
  • Record historical context in version control commit messages, not in comments
  • Delete commented-out code (retrieve from git history when needed)

Comment Quality

  • Write comments that remain accurate regardless of future code changes; avoid references to dates, versions, or temporary state
  • Update comments when changing code
  • Use proper grammar and formatting
  • Write for future maintainers

Refactoring Approach

Safe Refactoring

  • Small steps: Make one change at a time
  • Maintain working state: Keep tests passing
  • Verify behavior: Run tests after each change
  • Incremental improvement: Don't aim for perfection immediately

Refactoring Triggers

  • Code duplication (DRY principle)
  • Functions > 50 lines
  • Complex conditional logic
  • Unclear naming or structure

Testing Considerations

Testability

  • Write testable code from the start
  • Avoid hidden dependencies
  • Keep side effects explicit
  • Design for parameterized dependencies

Test-Driven Development

  • Write tests before implementation when appropriate
  • Keep tests simple and focused
  • Test behavior, not implementation
  • Maintain test quality equal to production code

Security Principles

Secure Defaults

  • Store credentials and secrets through environment variables or dedicated secret managers
  • Use parameterized queries (prepared statements) for all database access
  • Use established cryptographic libraries provided by the language or framework
  • Generate security-critical values (tokens, IDs, nonces) with cryptographically secure random generators
  • Encrypt sensitive data at rest and in transit using standard protocols

Input and Output Boundaries

  • Validate all external input at system entry points for expected format, type, and length
  • Encode output appropriately for its rendering context (HTML, SQL, shell, URL)
  • Return only information necessary for the caller in error responses; log detailed diagnostics server-side

Access Control

  • Apply authentication to all entry points that handle user data or trigger state changes
  • Verify authorization for each resource access, not only at the entry point
  • Grant only the permissions required for the operation (files, database connections, API scopes)

Knowledge Cutoff Supplement (2026-03)

  • OWASP Top 10:2025 shifted from symptoms to root causes; added "Software Supply Chain Failures" (A03) and "Mishandling of Exceptional Conditions" (A10)
  • Recent research indicates AI-generated code shows elevated rates of access control gaps — treat authentication and authorization as high-priority review targets
  • OpenSSF published "Security-Focused Guide for AI Code Assistant Instructions" — recommends language-specific, actionable constraints over generic advice
  • For detailed detection patterns, see references/security-checks.md

Documentation

Code Documentation

  • Document public APIs and interfaces
  • Include usage examples for complex functionality
  • Maintain README files for modules
  • Update documentation in the same commit that changes the corresponding behavior

Architecture Documentation

  • Document high-level design decisions
  • Explain integration points
  • Clarify data flows and boundaries
  • Record trade-offs and alternatives considered

Version Control Practices

Commit Practices

  • Make atomic, focused commits
  • Write clear, descriptive commit messages
  • Commit working code (passes tests)
  • Commit only production-ready code; store secrets in environment variables or secret managers

Code Review Readiness

  • Self-review before requesting review
  • Keep changes focused and reviewable
  • Provide context in pull request descriptions
  • Respond to feedback constructively

Language-Specific Adaptations

While these principles are language-agnostic, adapt them to your specific programming language:

  • Static typing: Use strong types when available
  • Dynamic typing: Add runtime validation
  • OOP languages: Apply SOLID principles
  • Functional languages: Prefer pure functions and immutability
  • Concurrency: Follow language-specific patterns for thread safety
提供PRD、ADR、设计文档等模板及创建标准。根据功能类型和文件数量决定所需文档,明确ADR触发条件(如架构变更),规范文档内容与顺序,指导技术文档的创建与审查。
创建或审查技术文档 确定项目所需的文档类型 评估是否需要进行架构决策记录
dev-workflows/skills/documentation-criteria/SKILL.md
npx skills add shinpr/claude-code-workflows --skill documentation-criteria -g -y
SKILL.md
Frontmatter
{
    "name": "documentation-criteria",
    "description": "Documentation creation criteria including PRD, ADR, Design Doc, and Work Plan requirements with templates. Use when creating or reviewing technical documents, or determining which documents are required."
}

Documentation Creation Criteria

Templates

Creation Decision Matrix

Condition Required Documents Creation Order
New Feature Addition (backend) PRD → [ADR] → Design Doc → Work Plan After PRD approval
New Feature Addition (frontend/fullstack) PRD → UI Spec → [ADR] → Design Doc → Work Plan UI Spec before Design Doc
ADR Conditions Met (see below) ADR → Design Doc → Work Plan Start immediately
6+ Files [ADR if conditions apply] → Design Doc → Work Plan (Design Doc + Work Plan required) Start immediately
3-5 Files Design Doc → Work Plan (Required) Start immediately
1-2 Files None Direct implementation

ADR Creation Conditions (Required if Any Apply)

1. Contract System Changes

  • Adding nested contracts with 3+ levels: Contract A { Contract B { Contract C { field: T } } }
    • Rationale: Deep nesting has high complexity and wide impact scope
  • Changing/deleting contracts used in 3+ locations
    • Rationale: Multiple location impacts require careful consideration
  • Contract responsibility changes (e.g., DTO→Entity, Request→Domain)
    • Rationale: Conceptual model changes affect design philosophy

2. Data Flow Changes

  • Storage location changes (DB→File, Memory→Cache)
  • Processing order changes with 3+ steps
    • Example: "Input→Validation→Save" to "Input→Save→Async Validation"
  • Data passing method changes (parameter passing→shared state, direct reference→event-based communication)

3. Architecture Changes

  • Layer addition, responsibility changes, component relocation

4. External Dependency Changes

  • Library/framework/external API introduction or replacement

5. Complex Implementation Logic (Regardless of Scale)

  • Managing 3+ states
  • Coordinating 5+ asynchronous processes

Detailed Document Definitions

PRD (Product Requirements Document)

Purpose: Define business requirements and user value

Includes:

  • Business requirements and user value
  • Success metrics and KPIs (each metric specifies a numeric target and measurement method)
  • User stories and use cases
  • MoSCoW prioritization (Must/Should/Could/Won't)
  • Acceptance criteria with sequential IDs (AC-001, AC-002, ...) for downstream traceability
  • MVP and Future phase separation
  • User journey diagram (required)
  • Scope boundary diagram (required)

Scope: Business requirements, user value, success metrics, user stories, and prioritization only. Implementation details belong in Design Doc, technical selection rationale in ADR, phases and task breakdown in Work Plan.

ADR (Architecture Decision Record)

Purpose: Record technical decision rationale and background

Includes:

  • Decision (what was selected)
  • Rationale (why that selection was made)
  • Option comparison (minimum 3 options) and trade-offs
  • Architecture impact
  • Principled implementation guidelines (e.g., "Use dependency injection")

Scope: Decision, rationale, option comparison, architecture impact, and principled guidelines only. Implementation procedures and code examples belong in Design Doc, schedule and resource assignments in Work Plan.

UI Specification

Purpose: Define UI structure, screen transitions, component decomposition, and interaction design for frontend features

Includes:

  • Screen list and transition conditions
  • Component decomposition with state x display matrix (default/loading/empty/error/partial)
  • Interaction definitions linked to PRD acceptance criteria (EARS format)
  • Prototype management (code-based prototypes as attachments, not source of truth)
  • AC traceability from PRD to screens/components
  • Existing component reuse map and design tokens
  • Visual acceptance criteria (golden states, layout constraints)
  • Accessibility requirements (keyboard, screen reader, contrast)

Scope: Screen structure, transitions, component decomposition, interaction design, and visual acceptance criteria only. Technical implementation and API contracts belong in Design Doc, test implementation in test skeleton generation output, schedule in Work Plan.

Required Structural Elements:

  • At least one component with state x display matrix and interaction table
  • AC traceability table mapping PRD ACs to screens/states
  • Screen list with transition conditions
  • Existing component reuse map (reuse/extend/new decisions)

Prototype Code Handling:

  • Prototype code provided by user is placed in docs/ui-spec/assets/{feature-name}/
  • Prototype is an attachment to UI Spec, never the source of truth
  • UI Spec + Design Doc are the canonical specifications

Design Document

Purpose: Define technical implementation methods in detail

Includes:

  • Existing codebase analysis (required)
    • Implementation path mapping (both existing and new)
    • Integration point clarification (connection points with existing code even for new implementations)
  • Technical implementation approach (vertical/horizontal/hybrid)
  • Technical dependencies and implementation constraints (required implementation order)
  • Interface and contract definitions
  • Data flow and component design
  • Acceptance criteria (each criterion specifies a verifiable condition with pass/fail threshold)
  • Change impact map (clearly specify direct impact/indirect impact/no ripple effect)
  • Complete enumeration of integration points
  • Data contract clarification
  • Agreement checklist (agreements with stakeholders)
  • Code inspection evidence (inspected files/functions during investigation)
  • Field propagation map (when fields cross component boundaries)
  • Data representation decision (when introducing new structures)
  • Applicable standards (explicit/implicit classification)
  • Prerequisite ADRs (including common ADRs)
  • Verification Strategy (required)
    • Correctness proof method (what "correct" means for this change, how it's verified, when)
    • Early verification point (first target to prove the approach works, success criteria, failure response)

Required Structural Elements:

Change Impact Map:
  Change Target: [Component/Feature]
  Direct Impact: [Files/Functions]
  Indirect Impact: [Data format/Processing time]
  No Ripple Effect: [Unaffected features]

Interface Change Matrix:
  Existing: [Function/method/operation name]
  New: [Function/method/operation name]
  Conversion Required: [Yes/No]
  Compatibility Method: [Approach]

Scope: Technical implementation methods, interfaces, data flow, acceptance criteria, and verification strategy only. Technology selection rationale belongs in ADR, schedule and assignments in Work Plan.

Work Plan

Purpose: Implementation task management and progress tracking

Includes:

  • Task breakdown and dependencies (maximum 2 levels)
  • Schedule and duration estimates
  • Include test skeleton file paths produced for this work plan (integration and E2E)
  • Verification Strategy summary (extracted from Design Doc)
  • Final Quality Assurance Phase (required)
  • Progress records (checkbox format)

Scope: Task breakdown, dependencies, schedule, verification strategy summary, and progress tracking only. Technical rationale belongs in ADR, design details in Design Doc.

Phase Division Criteria (adapt to implementation approach from Design Doc):

When Vertical Slice selected:

  • Each phase = one value unit (feature, component, or migration target)
  • Each phase includes its own implementation + verification per Verification Strategy

When Horizontal Slice selected:

  1. Phase 1: Foundation Implementation - Contract definitions, interfaces/signatures, test preparation
  2. Phase 2: Core Feature Implementation - Business logic, unit tests
  3. Phase 3: Integration Implementation - External connections, presentation layer

When Hybrid selected:

  • Combine vertical and horizontal as defined in Design Doc implementation approach

All approaches: Final phase is always Quality Assurance (acceptance criteria achievement, all tests passing, quality checks). Each phase's verification method follows Verification Strategy from Design Doc.

Three Elements of Task Completion Definition:

  1. Implementation Complete: Code is functional
  2. Quality Complete: Tests, static checks, linting pass
  3. Integration Complete: Verified connection with other components

Creation Process

  1. Problem Analysis: Change scale assessment, ADR condition check
    • Identify explicit and implicit project standards before investigation
  2. ADR Option Consideration (ADR only): Compare 3+ options, specify trade-offs
  3. Creation: Use templates, include measurable conditions
  4. Approval: "Accepted" after review enables implementation

Storage Locations

Document Path Naming Convention Template
PRD docs/prd/ [feature-name]-prd.md prd-template.md
ADR docs/adr/ ADR-[4-digits]-[title].md adr-template.md
UI Spec docs/ui-spec/ [feature-name]-ui-spec.md ui-spec-template.md
UI Spec Assets docs/ui-spec/assets/{feature-name}/ Prototype code files -
Design Doc docs/design/ [feature-name]-design.md design-template.md
Work Plan docs/plans/ YYYYMMDD-{type}-{description}.md plan-template.md
Task File docs/plans/tasks/ {plan-name}-task-{number}.md task-template.md

*Note: Work plans are excluded by .gitignore

ADR Status

ProposedAcceptedDeprecated/Superseded/Rejected

AI Automation Rules

  • 6+ files: Suggest ADR creation
  • Contract/data flow change detected: ADR mandatory
  • Check existing ADRs before implementation

Diagram Requirements

Required diagrams for each document (using mermaid notation):

Document Required Diagrams Purpose
PRD User journey diagram, Scope boundary diagram Clarify user experience and scope
ADR Option comparison diagram (when needed) Visualize trade-offs
UI Spec Screen transition diagram, Component tree diagram Clarify screen flow and component structure
Design Doc Architecture diagram, Data flow diagram Understand technical structure
Work Plan Phase structure diagram, Task dependency diagram Clarify implementation order

Common ADR Relationships

  1. At creation: Identify common technical areas (logging, error handling, async processing, etc.), reference existing common ADRs
  2. When missing: Consider creating necessary common ADRs
  3. Design Doc: Specify common ADRs in "Prerequisite ADRs" section
  4. Compliance check: Verify design aligns with common ADR decisions
捕获并持久化代码库外部资源(如设计稿、API、密钥等)的访问方法,确保下游工作可确定性获取。适用于依赖外部资源或提及相关术语的场景。
工作依赖外部资源 用户提及设计源、设计系统、API模式、IaC源码或密钥存储
dev-workflows/skills/external-resource-context/SKILL.md
npx skills add shinpr/claude-code-workflows --skill external-resource-context -g -y
SKILL.md
Frontmatter
{
    "name": "external-resource-context",
    "description": "Captures and persists access methods for resources outside the repository (design source, design system, API schema, IaC source, secret store) so downstream work can reach them deterministically. Use when work depends on external resources, or when the user mentions design source, design system, API schema, IaC source, secret store, or canonical source."
}

External Resource Context

Purpose

AI agents understand the codebase but not the external resources surrounding it. This skill captures, in a deterministic location, the access methods to resources outside the repository so downstream work (design, planning, implementation, review) can reach them without re-asking the user.

Resources covered: design origin (where the canonical visual specification lives), design system (component library and tokens), guidelines (usage docs, accessibility rules), visual verification environment (how to confirm rendering), database schema source, migration history, secret store location, API schema source (OpenAPI / proto / GraphQL SDL), mock environment, IaC source, environment configuration.

Scope Boundaries

In scope: hearing protocol, storage location, single-source-of-truth ownership rule, reference protocol for downstream consumers.

Out of scope: enforcing that captured resources are correct or current — verification belongs to the agent that consumes the resource. Generating the resources themselves (e.g., creating a DESIGN.md from scratch).

Storage Locations (Two-Tier)

Tier Location Holds Update Frequency
Project docs/project-context/external-resources.md Environment-stable facts: which resources exist for this project and how to access them (URL, MCP name, file path, command) Rare — only when the project's environment changes
Feature ## External Resources Used section inside the relevant UI Spec or Design Doc The subset of project-tier resources actually used by this feature, plus feature-specific identifiers (e.g., a specific node id within the design tool, a specific endpoint path) Per feature

Single Source of Truth Rule

The project tier owns environment facts. Feature-tier sections list only feature-specific identifiers (node id within the design source, specific endpoint path within the API, specific IaC module name) and reference project-tier entries by label; URLs, MCP names, and access commands remain in the project-tier file. When the environment changes, only the project-tier file is updated.

Example feature-tier entry uses the table format defined in references/template.md: a row with the project-tier label in the first column and the feature-specific identifier in the second column.

Hearing Protocol

When to Hear

Condition Action
docs/project-context/external-resources.md does not exist Run full hearing for the relevant domain(s)
File exists Ask the user via AskUserQuestion: "Update external-resources.md? (no / yes-full / yes-diff-only)". On yes-full run full hearing. On yes-diff-only ask the user which axes changed, hear only those. On no skip hearing

Domain Routing

Load the domain reference matching the current task:

Task type References to load
Frontend (UI work) references/frontend.md
Backend (server / data work) references/backend.md
API contract work references/api.md
Infrastructure / deployment references/infra.md
Fullstack All of the above; per-axis "Not applicable" answers are expected

Each domain reference defines the axes and the question template.

Two-Phase Hearing

  1. Structured hearing — for each axis defined in the domain reference, present the user with AskUserQuestion using the choices listed there (always include "Not applicable" as an option). For each non-N/A axis, follow up with an access-method question (URL / MCP name / file path / command).

  2. Self-declaration — after the structured axes, present a single AskUserQuestion: "Are there any other external resources for this work that the structured questions did not cover? If yes, describe them in your next message." If the user describes additional resources, append them to the storage file under an "Additional resources" subsection.

The two phases are sequential. Self-declaration runs even if the user answered "Not applicable" to every structured axis.

Storage Protocol

After hearing completes:

  1. Build the project-tier content from the answers. Use references/template.md as the structure.
  2. Write to docs/project-context/external-resources.md. Create the directory if absent.
  3. When the calling workflow has a target UI Spec or Design Doc, also append or update the document's ## External Resources Used section with the feature-tier subset (label references + feature-specific identifiers only).
  4. Report the file paths back to the calling workflow.

Reference Protocol (For Downstream Consumers)

Agents that load this skill consult resources in this order:

  1. Read docs/project-context/external-resources.md first (if present) to learn what is available and how to access it.
  2. Read the target UI Spec or Design Doc's ## External Resources Used section for feature-specific identifiers.
  3. Use the access method declared in the project tier (e.g., the named MCP, the URL, the file path) to fetch the actual resource content.

Agents that only need to consult the saved file as input data (not actively hear) can read it directly without loading this skill — frontmatter declaration is reserved for agents that may need to trigger hearing or interpret the protocol semantics.

Output Format

The project-tier file follows the structure in references/template.md. The project-tier file's heading levels and section names are fixed so downstream agents can locate sections deterministically.

For feature-tier sections inside UI Spec or Design Doc, the heading text "External Resources Used" is fixed; the heading level matches the parent document's natural structure (h2 in UI Spec where it is a sibling of other top-level sections, h3 in Design Doc where it sits under Background and Context).

Quality Checklist

  • Each axis answered has both a presence indicator and an access method, or is marked "Not applicable"
  • Self-declaration phase ran even when all structured axes were "Not applicable"
  • Project-tier file does not contain feature-specific identifiers
  • Feature-tier sections reference project-tier entries by label, not by duplicating URLs / MCP names
  • When the project file already existed, the update decision (no / yes-full / yes-diff-only) was confirmed before any write

References

用于规划实施策略、选择开发方法或定义验证标准的元认知框架。涵盖现状分析、策略探索、风险评估及约束验证,提供遗留处理与新建模式参考,辅助制定稳健的实施计划。
规划实施策略 选择开发方法 定义验证标准
dev-workflows/skills/implementation-approach/SKILL.md
npx skills add shinpr/claude-code-workflows --skill implementation-approach -g -y
SKILL.md
Frontmatter
{
    "name": "implementation-approach",
    "description": "Implementation strategy selection framework. Use when planning implementation strategy, selecting development approach, or defining verification criteria."
}

Implementation Strategy Selection Framework (Meta-cognitive Approach)

Meta-cognitive Strategy Selection Process

Phase 1: Comprehensive Current State Analysis

Core Question: "What does the existing implementation look like?"

Analysis Framework

Architecture Analysis: Responsibility separation, data flow, dependencies, technical debt
Implementation Quality Assessment: Code quality, test coverage, performance, security
Historical Context Understanding: Current form rationale, past decision validity, constraint changes, requirement evolution

Meta-cognitive Question List

  • What is the true responsibility of this implementation?
  • Which parts are business essence and which derive from technical constraints?
  • What dependencies or implicit preconditions are unclear from the code?
  • What benefits and constraints does the current design bring?

Phase 2: Strategy Exploration and Creation

Core Question: "When determining before → after, what implementation patterns or strategies should be referenced?"

Strategy Discovery Process

Research and Exploration: Tech stack examples (WebSearch), similar projects, OSS references, literature/blogs
Creative Thinking: Strategy combinations, constraint-based design, phase division, extension point design

Reference Strategy Patterns (Creative Combinations Encouraged)

Legacy Handling Strategies:

  • Strangler Pattern: Gradual migration through phased replacement
  • Facade Pattern: Complexity hiding through unified interface
  • Adapter Pattern: Bridge with existing systems

New Development Strategies:

  • Feature-driven Development: Vertical implementation prioritizing user value
  • Foundation-driven Development: Foundation-first construction prioritizing stability
  • Risk-driven Development: Prioritize addressing maximum risk elements

Integration/Migration Strategies:

  • Proxy Pattern: Transparent feature extension
  • Decorator Pattern: Phased enhancement of existing features
  • Bridge Pattern: Flexibility through abstraction

Important: The optimal solution is discovered through creative thinking according to each project's context.

Phase 3: Risk Assessment and Control

Core Question: "What risks arise when applying this to existing implementation, and what's the best way to control them?"

Risk Analysis Matrix

Technical Risks: System impact, data consistency, performance degradation, integration complexity
Operational Risks: Service availability, deployment downtime, process changes, rollback procedures
Project Risks: Schedule delays, learning costs, quality achievement, team coordination

Risk Control Strategies

Preventive Measures: Phased migration, parallel operation verification, integration/regression tests, monitoring setup
Incident Response: Rollback procedures, log/metrics preparation, communication system, service continuation procedures

Phase 4: Constraint Compatibility Verification

Core Question: "What are this project's constraints?"

Constraint Checklist

Technical Constraints: Library compatibility, resource capacity, mandatory requirements, numerical targets
Temporal Constraints: Deadlines/priorities, dependencies, milestones, learning periods
Resource Constraints: Team/skills, work hours/systems, budget, external contracts
Business Constraints: Market launch timing, customer impact, regulatory compliance

Phase 5: Implementation Approach Decision

Select optimal solution from basic implementation approaches (creative combinations encouraged):

Vertical Slice (Feature-driven)

Characteristics: Vertical implementation across all layers by feature unit Application Conditions: Features share fewer than 2 data models, each feature is independently deliverable, changes touch 3+ architecture layers Verification Method: End-user value delivery at each feature completion

Horizontal Slice (Foundation-driven)

Characteristics: Phased construction by architecture layer Application Conditions: 3+ features depend on a common foundation layer, foundation changes require stability verification before consumers can proceed Verification Method: Integrated operation verification when all foundation layers complete

Hybrid (Creative Combination)

Characteristics: Flexible combination according to project characteristics Application Conditions: Unclear requirements, need to change approach per phase, transition from prototyping to full implementation Verification Method: Verify at appropriate L1/L2/L3 levels according to each phase's goals

Phase 6: Decision Rationale Documentation

Design Doc Documentation: Record in the Design Doc's implementation approach section:

  1. Selected strategy name and characteristics
  2. Alternatives considered and reason for rejection
  3. Risk mitigation plan (from Phase 3)
  4. Constraint compliance summary (from Phase 4)
  5. Verification level (L1/L2/L3) and integration point definition

Verification Level Definitions

Priority for completion verification of each task:

  • L1: Functional Operation Verification - Operates as end-user feature (e.g., search executable)
  • L2: Test Operation Verification - New tests added and passing
  • L3: Build Success Verification - Code builds/runs without errors

Priority: L1 > L2 > L3 in order of verifiability importance

Integration Point Definitions

Define integration points according to selected strategy:

  • Strangler-based: When switching between old and new systems for each feature
  • Feature-driven: When users can actually use the feature
  • Foundation-driven: When all architecture layers are ready and E2E tests pass
  • Hybrid: When individual goals defined for each phase are achieved

Quality Checks

  1. Verify at least one strategy combination beyond listed patterns was considered
  2. Confirm Phase 1 analysis framework is complete before selecting strategy
  3. Confirm Phase 3 risk analysis matrix is populated before implementation starts
  4. Confirm Phase 4 constraint checklist is reviewed before strategy decision
  5. Confirm Phase 6 documentation template is filled with selection rationale

Guidelines for Meta-cognitive Execution

  1. Leverage Known Patterns: Use as starting point, explore creative combinations
  2. Active WebSearch Use: Research implementation examples from similar tech stacks
  3. Apply 5 Whys: Pursue root causes to grasp essence
  4. Multi-perspective Evaluation: Comprehensively evaluate from each Phase 1-4 perspective
提供集成与E2E测试的设计原则、ROI计算模型及审查标准。涵盖测试类型定义、基于行为的优先级排序,指导测试用例设计、骨架规范制定及质量评审,确保高价值场景的测试覆盖。
设计集成测试或E2E测试 评估测试用例ROI 审查测试代码质量 选择测试执行通道
dev-workflows/skills/integration-e2e-testing/SKILL.md
npx skills add shinpr/claude-code-workflows --skill integration-e2e-testing -g -y
SKILL.md
Frontmatter
{
    "name": "integration-e2e-testing",
    "description": "Integration and E2E test design principles, ROI calculation, test skeleton specification, and review criteria. Use when designing integration tests, E2E tests, or reviewing test quality."
}

Integration and E2E Testing Principles

References

E2E test design: See references/e2e-design.md for UI Spec-driven E2E test candidate selection and browser test architecture. The reference uses Playwright as the default browser harness; substitute the project's standard when different.

Test Type Definition and Limits

Test Type Purpose Scope External Deps Limit per Feature Implementation Timing
Integration Verify component interactions in-process Partial system integration (in-process modules; for UI components, the framework's in-process renderer e.g., RTL+MSW for React/TS) Mocked or in-process MAX 3 Created alongside implementation
fixture-e2e Verify UI behavior in a browser with deterministic fixtures Full UI flow with mocked backend / fixture-driven state Mocked / fixture only — no live services MAX 3 Created alongside the UI feature
service-integration-e2e Verify critical user journeys against a running local stack Full system across services Live local services or stubs MAX 1-2 Executed only in the final phase

Lane selection (E2E only):

  • Default lane for user-facing UI journeys is fixture-e2e — it runs a real browser against deterministic fixtures, catches the bugs that unit/integration tests miss (button no-op, state never updates, navigation breaks), and runs in CI without infrastructure setup
  • Add service-integration-e2e only when the journey's correctness depends on real cross-service behavior (data persistence, transactional consistency, external service contracts) that cannot be faked safely

The two E2E lanes are budgeted independently — having a fixture-e2e for a journey does not consume the service-integration-e2e budget and vice versa.

Behavior-First Principle

Include (High ROI)

  • Business logic correctness (calculations, state transitions, data transformations)
  • Data integrity and persistence behavior
  • User-visible functionality completeness
  • Error handling behavior (what user sees/experiences)

Redirect to Other Test Types

  • External service connections → Verify via contract/interface tests
  • Performance metrics → Verify via dedicated load testing
  • Implementation details → Verify observable behavior instead
  • UI layout specifics → Verify information availability instead

Principle: Test = User-observable behavior verifiable in isolated CI environment

ROI Calculation

ROI is used to rank candidates within the same test type (integration candidates against each other, E2E candidates against each other). Cross-type comparison is unnecessary because integration and E2E budgets are selected independently.

ROI Score = Business Value × User Frequency + Legal Requirement × 10 + Defect Detection
              (range: 0–120)

Higher ROI Score = higher priority within its test type. No normalization or capping is applied — the raw score is used directly for ranking. Deduplication is a separate step that removes candidates entirely; it does not modify scores.

ROI Thresholds by Lane

The two E2E lanes have very different ownership costs and use independent thresholds.

Lane ROI threshold Rationale
fixture-e2e ROI ≥ 20 (beyond reserved slot) Cost is comparable to integration tests once the harness exists; the floor avoids filling MAX 3 with low-signal tests when fewer would suffice
service-integration-e2e ROI > 50 (beyond reserved slot) Creation, execution, and maintenance cost is 3-10× higher than integration; reserve for journeys whose value cannot be proven any other way

Reserved slot rules (see Multi-Step User Journey Definition below) apply per lane and override the threshold (the reserved candidate is emitted regardless of its ROI score). Below-floor candidates beyond the reserved slot are not emitted, leaving budget intentionally unfilled rather than padding with low-value tests.

ROI Calculation Examples

Scenario BV Freq Legal Defect ROI Score Test Type Selection Outcome
Core checkout UI flow 10 9 true 9 109 fixture-e2e Selected (reserved slot: user-facing multi-step journey, browser-level verification with fixtures)
Core checkout against live payment service 10 9 true 9 109 service-integration-e2e Selected (real-service correctness above ROI threshold)
Dismiss button updates UI state 6 7 false 8 50 fixture-e2e Selected (rank 2 of 3 fixture-e2e budget)
Payment error message display 5 4 false 7 27 fixture-e2e Selected (rank 3 of 3 fixture-e2e budget)
Optional filter toggle 3 4 false 2 14 fixture-e2e Not selected (rank 4, budget full)
Payment retry against real provider 8 3 false 7 31 service-integration-e2e Below ROI threshold (31 < 50), not selected
DB persistence check 8 8 false 8 72 Integration Selected (rank 1 of 3)
Pure data transformation 5 3 false 4 19 Integration Selected (rank 2 of 3)

Multi-Step User Journey Definition

A feature qualifies as containing a multi-step user journey when ALL of the following are true:

  1. 2+ distinct interaction boundaries are traversed in sequence to complete a user goal. What counts as a boundary depends on the system type:
    • Web: distinct routes/pages
    • Mobile native: distinct screens/views
    • CLI: distinct command invocations or interactive prompts
    • API: distinct API calls forming a transaction (e.g., create → confirm → finalize)
  2. State carries across steps — data produced or actions taken in one step affect what the next step accepts or displays
  3. The journey has a completion point — a final state the user or caller reaches (e.g., confirmation page, saved record, API success response, completed workflow)

User-Facing vs Service-Internal Journeys

Multi-step journeys are classified for reserved-slot eligibility:

Classification Condition Reserved Slot Eligibility Example
User-facing A human user directly triggers and observes the steps (via UI, CLI, or direct API interaction) Eligible — defaults to fixture-e2e reserved slot. Add a service-integration-e2e reserved slot only when the journey's correctness depends on real cross-service behavior Web checkout flow, CLI setup wizard, mobile onboarding
Service-internal Steps are triggered by backend services without direct user interaction Not eligible for reserved slot — use integration tests. Service-integration-e2e through normal ROI > 50 path is still valid when full-system verification is warranted Async job pipeline, service-to-service saga, scheduled batch processing

This classification applies only to the reserved-slot rule and the E2E Gap Check. Other selection follows lane-specific ROI rules above.

Use this definition when evaluating E2E test candidates and E2E gap detection.

Test Skeleton Specification

Required Comment Patterns

Each test MUST include the following annotations:

AC: [Original acceptance criteria text]
Behavior: [Trigger] → [Process] → [Observable Result]
@category: core-functionality | integration | edge-case | fixture-e2e | service-integration-e2e
@lane: integration | fixture-e2e | service-integration-e2e
@dependency: none | [component names] | full-system
@complexity: low | medium | high
ROI: [score]

@lane selection rule:

  • integration — Component interaction in-process, no browser (e.g., RTL+MSW for React/TS, in-process module/handler integration in any language)
  • fixture-e2e — Browser-level UI verification with mocked backend / fixture-driven state
  • service-integration-e2e — Browser-level or end-to-end verification against running local services or stubs

Use the project's comment syntax to wrap these annotations (e.g., // for C-family, # for Python/Ruby/Shell).

Verification Items (Optional)

When verification points need explicit enumeration:

Verification items:
- [Item 1]
- [Item 2]

EARS Format Mapping

EARS Keyword Test Type Generation Approach
When Event-driven Trigger event → verify outcome
While State condition Setup state → verify behavior
If-then Branch coverage Both condition paths verified
(none) Basic functionality Direct invocation → verify result

Test File Naming Convention

  • Integration tests: *.int.test.* or *.integration.test.*
  • fixture-e2e tests: *.fixture.e2e.test.* (or organize under tests/e2e/fixture/)
  • service-integration-e2e tests: *.service.e2e.test.* (or organize under tests/e2e/service/)

The test runner or framework in the project determines the appropriate file extension. Repos that already use a single *.e2e.test.* convention may keep it as long as each file declares @lane: in its header — the lane annotation is the source of truth for routing and budget accounting.

Review Criteria

Skeleton and Implementation Consistency

Check Failure Condition
Behavior Verification No assertion for "observable result" in the implemented test
Verification Item Coverage Listed items not all covered by assertions
Mock Boundary Internal components mocked in integration test

Implementation Quality

Check Failure Condition
AAA Structure Arrange/Act/Assert separation unclear
Independence State sharing between tests, order dependency
Reproducibility Date/random dependency, varying results
Readability Test name doesn't match verification content

Quality Standards

Required

  • Each test verifies one behavior
  • Clear AAA (Arrange-Act-Assert) structure
  • No test interdependencies
  • Deterministic execution
该技能旨在优化LLM间交互,通过明确输入输出、成功标准及决策点,消除歧义。提供重写模式将模糊指令转化为具体可执行步骤,确保下游Agent能准确理解并稳定执行任务,无需猜测。
编写或修订面向LLM的提示词 创建Agent间的交接文档 生成规划工件或报告 审查现有指令的清晰度
dev-workflows/skills/llm-friendly-context/SKILL.md
npx skills add shinpr/claude-code-workflows --skill llm-friendly-context -g -y
SKILL.md
Frontmatter
{
    "name": "llm-friendly-context",
    "description": "Clarifies inputs, outputs, success criteria, decisions, and unresolved conditions so downstream agents can execute without guessing. Use when writing or revising LLM-facing prompts, handoffs, planning artifacts, reviews, reports, or generated instructions."
}

LLM-Friendly Context

The goal is stable downstream execution: the next agent should know what to read, what to do, what counts as success, and when to stop or escalate.

Core Rules

  1. Use positive, executable instructions

    • State what the next agent should do.
    • Convert quality policies into positive criteria.
    • Example: "Preserve existing public API behavior across the documented compatibility cases."
  2. Make vague instructions concrete

    • Replace subjective terms with observable conditions, paths, commands, schemas, examples, or decision rules.
    • Terms that often need clarification when they leave a decision to the next agent: appropriate, proper, related, existing behavior, optional, as needed, if needed, per convention, unresolved alternatives, TBD, placeholder.
  3. Specify output shape

    • Define required sections, fields, table columns, JSON keys, or checklist items.
    • For handoffs, include paths to produced artifacts and the exact status fields the caller must inspect.
  4. Provide necessary context

    • Include the purpose, source artifacts, hard constraints, accepted decisions, and unresolved conditions.
    • Prefer concrete file paths and section hints over broad module names.
  5. Decompose complex work into verifiable steps

    • Split work with 3+ objectives or sequential dependencies into ordered steps.
    • Each step needs a checkpoint: what evidence proves it is complete.
  6. Permit uncertainty explicitly

    • If the source material is missing, contradictory, or not verifiable, state the uncertainty and the required escalation.
    • Record unknown business, product, security, or compatibility decisions as blocking unresolved items with the input needed to resolve them.
  7. Keep constraints proportionate

    • Add only constraints that reduce ambiguity or preserve a real requirement.
    • Keep simple downstream tasks lightweight when the target action, context, and success criteria are already clear.

Rewrite Patterns

Use these rewrites before treating a prompt, handoff, or artifact as complete.

Ambiguous form Rewrite as
optional used as an unresolved choice Required, omitted, or required only under a named condition
Multiple alternatives that the next agent must choose between The selected option, or a deterministic decision rule
as needed / if needed The triggering condition and required action
per convention The file, function, test, or documented convention to follow
related files Specific paths, globs, or search hints
existing behavior The observable behavior, source file, test, API response, or UI state to preserve
placeholder Exact temporary value/behavior, allowed dependencies, and verification expectation
TBD used as a placeholder for required information A blocking unresolved item with owner, required input, or escalation condition
appropriate / proper A measurable criterion or checklist

Handoff Checklist

Before sending a prompt or artifact to another agent, verify:

  • The target action is explicit.
  • Required input paths and source artifacts are named.
  • Accepted decisions and constraints are stated once, without alternate wording.
  • Output format or expected status fields are specified.
  • Success criteria are observable.
  • Ambiguous expressions have been rewritten or marked as unresolved.
  • The next agent can complete its scope with explicit choices, decision rules, or blocking unresolved items.

Generated Artifact Checklist

Before writing or finalizing a generated document:

  • Each requirement, claim, task, test skeleton, or review finding has enough source context to trace why it exists.
  • Every executable instruction names the target, action, and expected result.
  • Verification steps say what to run or observe and what result proves success.
  • If an artifact is derived from another artifact, copied decisions stay consistent in wording and meaning.
  • If downstream work is blocked by missing information, the artifact records the missing input and escalation condition.
基于设计文档为现有代码库添加集成/E2E测试。通过编排器注册步骤,发现并分类文档,生成测试骨架,创建任务文件,并委托子代理执行实现、审查和质量修复。
需要为现有后端、前端或全栈代码添加集成或端到端测试 提供包含设计文档的路径参数
dev-workflows/skills/recipe-add-integration-tests/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-add-integration-tests -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-add-integration-tests",
    "description": "Add integration\/E2E tests to existing codebase using Design Docs",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Test addition workflow for existing implementations (backend, frontend, or fullstack)

Orchestrator Definition

Core Identity: "I am an orchestrator."

First Action: Register Steps 0-8 using TaskCreate before any execution.

Why Delegate: Orchestrator's context is shared across all steps. Direct implementation consumes context needed for review and quality check phases. Task files create context boundaries. Subagents work in isolated context.

Execution Method:

  • Skeleton generation → delegate to acceptance-test-generator
  • Task file creation → orchestrator creates directly (minimal context usage)
  • Test implementation → delegate to task-executor
  • Test review → delegate to integration-test-reviewer
  • Quality checks → delegate to quality-fixer

Document paths: $ARGUMENTS

Prerequisites

  • At least one Design Doc must exist (created manually or via reverse-engineer)
  • Existing implementation to test

Execution Flow

Step 0: Execute Skill

Execute Skill: documentation-criteria (for task file template in Step 3)

Step 1: Discover and Validate Documents

# Verify at least one document path was provided
test -n "$ARGUMENTS" || { echo "ERROR: No document paths provided"; exit 1; }

# Verify provided paths exist
ls $ARGUMENTS

# Discover additional documents
ls docs/design/*.md 2>/dev/null | grep -v template
ls docs/ui-spec/*.md 2>/dev/null

Classify discovered documents by filename:

  • Filename contains backendDesign Doc (backend)
  • Filename contains frontendDesign Doc (frontend)
  • Located in docs/ui-spec/UI Spec (optional)
  • None of the above → treat as single-layer Design Doc

Step 2: Skeleton Generation

Invoke acceptance-test-generator using Agent tool:

  • subagent_type: "dev-workflows:acceptance-test-generator"
  • description: "Generate test skeletons"
  • prompt: List only the documents that exist from Step 1:
    Generate test skeletons from the following documents:
    - Design Doc (backend): [path]    ← include only if exists
    - Design Doc (frontend): [path]   ← include only if exists
    - UI Spec: [path]                 ← include only if exists
    

Expected output: generatedFiles containing integration and e2e paths

Step 3: Create Task Files [GATE]

Create one task file per layer, using the monorepo-flow.md naming convention for deterministic agent routing:

  • Backend skeletons exist → docs/plans/tasks/integration-tests-backend-task-YYYYMMDD.md
  • Frontend skeletons exist → docs/plans/tasks/integration-tests-frontend-task-YYYYMMDD.md
  • Single-layer (no backend/frontend distinction) → docs/plans/tasks/integration-tests-backend-task-YYYYMMDD.md

Template (per task file):

---
name: Implement [layer] integration tests for [feature name]
type: test-implementation
---

## Objective

Implement test cases defined in skeleton files.

## Target Files

- Skeleton: [layer-specific paths from Step 2 generatedFiles]
- Design Doc: [layer-specific Design Doc from Step 1]

## Tasks

- [ ] Implement each test case in skeleton
- [ ] Verify all tests pass
- [ ] Ensure coverage meets requirements

## Acceptance Criteria

- All skeleton test cases implemented
- All tests passing
- quality-fixer reports approved

Output: "Task file(s) created at [path(s)]. Ready for Step 4."

Step 4: Test Implementation

For each task file from Step 3, invoke task-executor routed by filename pattern (per monorepo-flow.md):

  • *-backend-task-*subagent_type: "dev-workflows:task-executor"
  • *-frontend-task-*subagent_type: "dev-workflows-frontend:task-executor-frontend"
  • description: "Implement integration tests"
  • prompt: "Task file: [task file path from Step 3]. Implement tests following the task file."

Execute one task file at a time through Steps 4→5→6→7 before starting the next.

Expected output: status, testsAdded

Step 5: Test Review

Invoke integration-test-reviewer using Agent tool:

  • subagent_type: "dev-workflows:integration-test-reviewer"
  • description: "Review test quality"
  • prompt: "Review test quality. Test files: [paths from Step 4 testsAdded]. Skeleton files: [layer-specific paths from Step 2 generatedFiles matching current task's layer]"

Expected output: status (approved/needs_revision), requiredFixes

Step 6: Apply Review Fixes

Check Step 5 result:

  • status: approved → Mark complete, proceed to Step 7
  • status: needs_revision → Invoke task-executor with requiredFixes, then return to Step 5

Invoke task-executor routed by task filename pattern:

  • *-backend-task-*subagent_type: "dev-workflows:task-executor"
  • *-frontend-task-*subagent_type: "dev-workflows-frontend:task-executor-frontend"
  • description: "Fix review findings"
  • prompt: "Fix the following issues in test files: [requiredFixes from Step 5]"

Step 7: Quality Check

Invoke quality-fixer routed by task filename pattern:

  • *-backend-task-*subagent_type: "dev-workflows:quality-fixer"
  • *-frontend-task-*subagent_type: "dev-workflows-frontend:quality-fixer-frontend"
  • description: "Final quality assurance"
  • prompt: "Final quality assurance for test files added in this workflow. Run all tests and verify coverage."

Expected output: status (approved/stub_detected/blocked)

Check quality-fixer response:

  • stub_detected → Return to Step 4 with incompleteImplementations[] details, then re-execute Steps 4→5→6→7
  • blocked → Escalate to user
  • approved → Proceed to Step 8

Step 8: Commit

On approved from quality-fixer:

  • Commit test files using Bash with message format: "test: add [layer] integration tests for [feature name]"

Step 9: Final Cleanup

After all task files have been processed and committed, delete the task files this recipe created. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file matching docs/plans/tasks/integration-tests-backend-task-*.md and docs/plans/tasks/integration-tests-frontend-task-*.md created during this run

If task files cannot be deleted (filesystem error), report the failure but do not block completion.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.
自主执行分解任务的编排器。通过解析工作计划与任务文件,严格遵循任务执行、升级检查、质量修复及提交的四步循环,协调子代理完成开发任务并清理已消耗文件。
用户指令执行现有任务文件 需要批量审批并运行既定工作计划
dev-workflows/skills/recipe-build/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-build -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-build",
    "description": "Execute decomposed tasks in autonomous execution mode",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Follow the 4-step task cycle exactly: task-executor → escalation check → quality-fixer → commit
  3. Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
  4. Scope: Complete when all tasks are committed or escalation occurs

CRITICAL: Run quality-fixer before every commit.

Work plan: $ARGUMENTS

Pre-execution Prerequisites

Work Plan Resolution

Before any task processing, locate the work plan. Resolution rule:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md. Layer-aware fullstack tasks ({plan-name}-backend-task-*.md / {plan-name}-frontend-task-*.md) are excluded here so a stale fullstack run does not redirect this recipe to the wrong work plan
  2. From the matched files, also exclude every file matching any of these patterns — they originate from other workflow phases and are not implementation tasks for this run's plan: *-task-prep-*.md (readiness preflight tasks), _overview-*.md (decomposition overview file), *-phase*-completion.md (per-phase completion files), review-fixes-*.md (post-implementation review fixes), integration-tests-*-task-*.md (integration-test add-on scaffolding)
  3. For each remaining file, extract the {plan-name} prefix as the segment that appears before -task-
  4. When at least one task file matches, the work plan is docs/plans/{plan-name}.md for the prefix that has the most recent task-file mtime; ties broken by the lexicographically last {plan-name}
  5. When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template .md in docs/plans/

Consumed Task Set

Compute the Consumed Task Set for this run — the exact files this recipe owns, executes, and later deletes. Use the same restricted pattern as Work Plan Resolution:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md for the {plan-name} resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded
  2. Exclude every file matching: *-task-prep-*.md, _overview-*.md, *-phase*-completion.md, review-fixes-*.md, integration-tests-*-task-*.md (these originate from other workflow phases)

Every subsequent reference to "task files" in this recipe — Task Generation Decision Flow, Task Execution Cycle iteration, and Final Cleanup — uses this set, not the unrestricted docs/plans/tasks/*.md glob.

Task Generation Decision Flow

Analyze the Consumed Task Set and determine the action required:

State Criteria Next Action
Tasks exist Consumed Task Set is non-empty User's execution instruction serves as batch approval → Enter autonomous execution immediately
No tasks + plan exists Consumed Task Set is empty but the resolved work plan exists Confirm with user → run task-decomposer
Neither exists + Design Doc exists No plan, no Consumed Task Set, but docs/design/*.md exists Invoke work-planner to create work plan from Design Doc, then run document-reviewer (dev-workflows:document-reviewer, doc_type: WorkPlan); branch on the reviewer's verdict.decision — on needs_revision, re-invoke work-planner (update) and re-review until approved/approved_with_conditions, then present the reviewed plan for batch approval before task decomposition; on rejected, stop before task decomposition and escalate to the user
Neither exists No plan, no Consumed Task Set, no Design Doc Report missing prerequisites to user and stop

Task Decomposition Phase (Conditional)

When the Consumed Task Set is empty:

1. User Confirmation

No task files in the Consumed Task Set.
Work plan: docs/plans/[plan-name].md

Generate tasks from the work plan? (y/n):

2. Task Decomposition (if approved)

Invoke task-decomposer using Agent tool:

  • subagent_type: "dev-workflows:task-decomposer"
  • description: "Decompose work plan"
  • prompt: "Read work plan at docs/plans/[plan-name].md and decompose into atomic tasks. Output: Individual task files in docs/plans/tasks/. Granularity: 1 task = 1 commit = independently executable"

3. Verify Generation

Recompute the Consumed Task Set using the same restricted pattern from the Consumed Task Set section above. Confirm it is now non-empty. If it is still empty, escalate to the user — task-decomposer either failed silently or produced files that don't match the expected pattern.

Flow: Task generation → Consumed Task Set recompute → Autonomous execution (in this order)

Pre-execution Checklist

  • Confirmed Consumed Task Set is non-empty (computed in the Consumed Task Set section above)
  • Identified task execution order within the Consumed Task Set (dependencies)
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Task Execution Cycle (4-Step Cycle)

MANDATORY EXECUTION CYCLE: task-executor → escalation check → quality-fixer → commit

For EACH task in the Consumed Task Set, YOU MUST:

  1. Register tasks using TaskCreate: Register work steps. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON"
  2. Agent tool (subagent_type: "dev-workflows:task-executor") → Pass task file path in prompt, receive structured response
  3. CHECK task-executor response:
    • status: "escalation_needed" or "blocked" → STOP and escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 2 with requiredFixes
      • approved → Proceed to step 4
    • readyForQualityCheck: true → Proceed to step 4
  4. INVOKE quality-fixer: Execute all quality checks and fixes. Always pass the current task file path as task_file
  5. CHECK quality-fixer response:
    • stub_detected → Return to step 2 with incompleteImplementations[] details
    • blocked → STOP and escalate to user
    • approved → Proceed to step 6
  6. COMMIT on approval: Execute git commit

CRITICAL: Parse every sub-agent response for status fields. Execute the matching branch in the 4-step cycle. Proceed to next task only after quality-fixer returns approved.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Verify task files exist per Pre-execution Checklist, then enter autonomous execution mode. When requirement changes are detected during execution, escalate to the user with the change summary before continuing.

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows:code-verifier") → doc_type: design-doc, Design Doc path, code_paths: implementation file list (git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows:security-reviewer") → Design Doc path, implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute task-executor with consolidated fixes → quality-fixer
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file in the Consumed Task Set
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer for this {plan-name})
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Completion Report Contract

Final report must include:

  • Task decomposition status
  • Implemented task count
  • Quality check result
  • Commit count
  • Cleanup result
  • Escalation or blocking summary, if any
负责从代码库分析到设计文档创建的编排技能。通过委托子代理执行范围引导、代码分析、技术设计、验证及审查,并在关键节点等待用户确认,最终产出获批的ADR或设计文档。
需要生成架构决策记录(ADR) 需要创建详细的技术设计文档 启动基于代码库的分析与设计流程
dev-workflows/skills/recipe-design/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-design -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-design",
    "description": "Execute from codebase analysis to design document creation",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the design phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results. The one exception is the Step 1 scope bootstrap, a recipe-local orchestrator task limited to locating seed files.
  2. Run the design flow below in order:
    • Execute: scope bootstrap → codebase-analyzer → [Stop: Scope confirmation] → technical-designer → code-verifier → document-reviewer → design-sync
    • code-verifier and design-sync apply when the design output is a Design Doc; both are skipped for ADR-only
    • Stop at every [Stop: ...] marker → Wait for user approval before proceeding
  3. Scope: Complete when design documents receive approval

subagents-orchestration-guide usage: Reference the guide only for orchestration principles (Delegation Boundary, Decision precedence, permitted tools), the Scale Determination table, and handoff contracts HC-02 onward. This recipe defines its own start order and subagent prompts. The guide's requirement-analyzer-origin flow, First Action Rule, HC-01, and Call Examples do not apply to this recipe.

CRITICAL: Execute document-reviewer, design-sync (for Design Docs), and all stopping points — each serves as a quality gate. Skipping any step risks undetected inconsistencies.

Workflow Overview

Requirements → scope bootstrap → codebase-analyzer → [Stop: Scope confirmation]
                                                            ↓
                                                    technical-designer
                                                            ↓
                                                    code-verifier → document-reviewer
                                                            ↓
                                                       design-sync → [Stop: Design approval]

Scope Boundaries

Included in this skill:

  • Scope bootstrap: locating seed files so codebase-analyzer receives a populated input
  • Codebase analysis with codebase-analyzer (entry point of the design phase)
  • Scope confirmation with the user, grounded in codebase-analyzer findings
  • ADR creation (if architecture changes, new technology, or data flow changes)
  • Design Doc creation with technical-designer
  • Design Doc verification with code-verifier (before document review)
  • Document review with document-reviewer
  • Design Doc consistency verification with design-sync

Responsibility Boundary: This skill completes with design document (ADR/Design Doc) approval. Work planning and beyond are outside scope.

Execution Flow

Requirements: $ARGUMENTS

Step 1: Scope Bootstrap

codebase-analyzer requires a populated requirement_analysis.affectedFiles. Build that seed with a lightweight, orchestrator-local pass — locating files only, with no deep reading and no design decisions:

  1. Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
  2. Search the repository with Bash (rg, or grep when rg is unavailable) for files matching those keywords.
  3. Collect the matched file paths as the seed affectedFiles.
  4. When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as affectedFiles before invoking codebase-analyzer. If the user confirms no related code exists, report that codebase-grounded design does not apply and confirm with the user how to proceed.
  5. When the search returns more than ~20 files: the keywords are too broad for a focused design scope. Present the most relevant candidates to the user (AskUserQuestion) and confirm the seed affectedFiles before invoking codebase-analyzer.

This step locates seed files only. Reading files in full, tracing dependencies, and analysis remain codebase-analyzer's responsibility.

Step 2: Codebase Analysis

Invoke codebase-analyzer with its existing schema. The orchestrator constructs requirement_analysis from the Step 1 seed.

  • Invoke codebase-analyzer using Agent tool
    • subagent_type: "dev-workflows:codebase-analyzer", description: "Codebase analysis"
    • prompt: include
      • requirements: the user requirements verbatim
      • requirement_analysis: a JSON object with all four fields — affectedFiles (Step 1 seed), purpose (the user requirements), scale (provisional value from the Scale Determination table applied to the seed file count), technicalConsiderations ({ constraints: [], risks: [], dependencies: [] } — the bootstrap performs no analysis, so the object is present with empty lists)
      • Expected action: analyze the seed files and produce design guidance

Step 3: Scope Confirmation

After codebase-analyzer returns, confirm the design scope with the user before any design work. This is a recipe-local confirmation step. Use AskUserQuestion.

Present, sourced from the codebase-analyzer JSON:

  • Target files/modules: analysisScope.filesAnalyzed and the modules they belong to
  • Affected layers: layers touched, derived from analysisScope.categoriesDetected and focusAreas
  • Unknowns/assumptions: limitations plus any assumptions codebase-analyzer recorded
  • Questions before design: open points that need a user answer before design proceeds

Ask the user to choose one:

  • Proceed to design with this scope — continue to Step 4 (Design Doc)
  • Correct the scope and re-run — return to Step 1 with the corrected scope; when the user names the corrected files or modules, use those directly as the Step 1 seed instead of re-deriving them by search
  • Hold additional hearing, then proceed — gather the missing answers, then continue to Step 4
  • Produce an ADR — when the confirmed scope involves architecture changes, new technology, or data flow changes, continue to Step 4 with technical-designer in ADR mode

After the user confirms the scope, count the confirmed target files and set the scale from the subagents-orchestration-guide Scale Determination table. This confirmed scale supersedes the Step 2 provisional value and determines the design document.

[STOP]: Wait for the user's choice before proceeding.

Step 4: Design Document Creation

Pass the full codebase-analyzer JSON to technical-designer (handoff contract HC-02). technical-designer presents at least two design alternatives with trade-offs for each.

  • Invoke technical-designer using Agent tool
    • For Design Doc: subagent_type: "dev-workflows:technical-designer", description: "Design Doc creation", prompt: "Create Design Doc based on the requirements. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. Confirmed scope: [Step 3 confirmed scope]. Apply the code: prefix to codebase-analyzer fact_ids when filling the Fact Disposition Table. Present at least two architecture alternatives with trade-offs."
    • For ADR: subagent_type: "dev-workflows:technical-designer", description: "ADR creation", prompt: "Create ADR for [technical decision]. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. Confirmed scope: [Step 3 confirmed scope]. Present at least two alternatives with trade-offs."
  • (Design Doc only) Invoke code-verifier to verify the Design Doc against existing code. Skip for ADR.
    • subagent_type: "dev-workflows:code-verifier", description: "Design Doc verification", prompt: "doc_type: design-doc document_path: [Design Doc path] Verify Design Doc against existing code."
  • Invoke document-reviewer to verify consistency (pass code-verifier results for Design Doc; omit for ADR)
    • subagent_type: "dev-workflows:document-reviewer", description: "Document review", prompt: "Review [document path] for consistency and completeness. codebase_analysis: [codebase-analyzer JSON from Step 2]. code_verification: [code-verifier output from this step] (Design Doc only)"
  • (Design Doc only) Invoke design-sync to verify consistency across design documents. Skip for ADR-only.
    • subagent_type: "dev-workflows:design-sync", description: "Design consistency check", prompt: "Check consistency across all Design Docs in docs/design/. Report conflicts and overlaps."

[STOP]: Present the design document, plus design-sync results for a Design Doc, and obtain user approval.

Completion Criteria

  • Built the Step 1 scope bootstrap seed (or obtained target files from the user when the search returned none)
  • Executed codebase-analyzer with a populated requirement_analysis
  • Confirmed the design scope with the user and set the scale from the confirmed target files
  • Created appropriate design document (ADR or Design Doc) with technical-designer
  • Executed code-verifier on Design Doc and passed results to document-reviewer (skip for ADR-only)
  • Executed document-reviewer and addressed feedback
  • Executed design-sync for consistency verification (skip for ADR-only)
  • Obtained user approval for design document

Output Example

Design phase completed.

  • Design document: docs/design/[document-name].md or docs/adr/[document-name].md
  • Approval status: User approved
诊断故障根因并生成解决方案的编排技能。通过结构化流程协调调查、验证和求解子代理,识别变更失败或新发现,最终输出报告。
需要排查系统故障或错误原因 要求分析根本原因并提供解决建议 用户询问技术问题背后的机制
dev-workflows/skills/recipe-diagnose/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-diagnose -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-diagnose",
    "description": "Investigate problem, verify findings, and derive solutions",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Diagnosis flow to identify root cause and present solutions

Target problem: $ARGUMENTS

Orchestrator Definition

Core Identity: "I am not a worker. I am an orchestrator."

Execution Method:

  • Investigation → performed by investigator
  • Verification → performed by verifier
  • Solution derivation → performed by solver

Orchestrator invokes sub-agents and passes structured JSON between them.

Task Registration: Register execution steps using TaskCreate and proceed systematically. Update status using TaskUpdate.

Step 0: Problem Structuring (Before investigator invocation)

0.1 Problem Type Determination

Type Criteria
Change Failure Indicates some change occurred before the problem appeared
New Discovery No relation to changes is indicated

If uncertain, ask the user whether any changes were made right before the problem occurred.

0.2 Information Supplementation for Change Failures

If the following are unclear, ask with AskUserQuestion before proceeding:

  • What was changed (cause change)
  • What broke (affected area)
  • Relationship between both (shared components, etc.)

0.3 Problem Essence Understanding

Invoke rule-advisor via Agent tool:

subagent_type: rule-advisor
description: "Problem essence analysis"
prompt: Identify the essence and required rules for this problem: [Problem reported by user]

Confirm from rule-advisor output:

  • taskAnalysis.mainFocus: Primary focus of the problem
  • mandatoryChecks.taskEssence: Root problem beyond surface symptoms
  • selectedRules: Applicable rule sections
  • warningPatterns: Patterns to avoid

0.4 Reflecting in investigator Prompt

Include the following in investigator prompt:

  1. Problem essence (taskEssence)
  2. Key applicable rules summary (from selectedRules)
  3. Investigation focus (investigationFocus): Convert warningPatterns to "points prone to confusion or oversight in this investigation"
  4. For change failures, additionally include:
    • Detailed analysis of the change content
    • Commonalities between cause change and affected area
    • Determination of whether the change is a "correct fix" or "new bug" with comparison baseline selection

Diagnosis Flow Overview

Problem → investigator → verifier → solver ─┐
                 ↑                          │
                 └── coverage insufficient ─┘
                      (max 2 iterations)

coverage sufficient → Report

Context Separation: Pass only structured JSON output to each step. Each step starts fresh with the JSON data only.

Execution Steps

Register the following using TaskCreate and execute:

Step 1: Investigation (investigator)

Agent tool invocation:

subagent_type: investigator
description: "Investigate problem"
prompt: |
  Comprehensively collect information related to the following phenomenon.

  Phenomenon: [Problem reported by user]

  Problem essence: [taskEssence from Step 0.3]
  Investigation focus: [investigationFocus from Step 0.4]

  [For change failures, additionally include:]
  Change details: [What was changed]
  Affected area: [What broke]
  Shared components: [Commonalities between cause and effect]

Expected output: pathMap (execution paths per symptom), failurePoints (faults found at each node), impactAnalysis per failure point, unexplored areas, investigation limitations

Step 2: Investigation Quality Check

Review investigation output:

Quality Check (verify JSON output contains the following):

  • pathMap exists with at least one symptom, and each symptom has at least one path with nodes listed
  • Each failure point has: location, upstreamDependency, symptomExplained, causalChain (reaching a stop condition), checkStatus, evidence with a source citing a specific file or location
  • Each failure point has comparisonAnalysis (normalImplementation found or explicitly null)
  • causeCategory for each failure point is one of: typo / logic_error / missing_constraint / design_gap / external_factor
  • investigationSources covers at least 3 distinct source types (code, history, dependency, config, document, external)
  • Investigation covers investigationFocus items (when provided in Step 0.4)
  • All nodes on mapped paths have been checked (no path was abandoned after finding the first fault)

If quality insufficient: Re-run investigator specifying missing items explicitly:

prompt: |
  Re-investigate with focus on the following gaps:
  - Missing: [list specific missing items from quality check]

  Previous investigation results (for context, do not re-investigate covered areas):
  [Previous investigation JSON]

design_gap Escalation:

When investigator output contains causeCategory: design_gap or recurrenceRisk: high:

  1. Insert user confirmation before verifier execution
  2. Use AskUserQuestion: "A design-level issue was detected. How should we proceed?"
    • A: Attempt fix within current design
    • B: Include design reconsideration
  3. If user selects B, pass includeRedesign: true to solver

Proceed to verifier once quality is satisfied.

Step 3: Verification (verifier)

Agent tool invocation:

subagent_type: verifier
description: "Verify investigation results"
prompt: Verify the following investigation results.

Investigation results: [Investigation JSON output]

Expected output: Coverage check (missing paths, unchecked nodes), Devil's Advocate evaluation per failure point, failure point evaluation with checkStatus, coverage assessment

Coverage Criteria:

  • sufficient: Main paths traced, all critical nodes checked, each failure point individually evaluated
  • partial: Main paths traced, some nodes unchecked or some failure points at blocked/not_reached
  • insufficient: Significant paths untraced, or critical nodes not investigated

Step 4: Solution Derivation (solver)

Agent tool invocation:

subagent_type: solver
description: "Derive solutions"
prompt: Derive solutions based on the following verified failure points.

Confirmed failure points: [verifier's conclusion.confirmedFailurePoints]
Refuted failure points: [verifier's conclusion.refutedFailurePoints]
Failure point relationships: [verifier's conclusion.failurePointRelationships]
Impact analysis: [investigator's impactAnalysis]
Coverage assessment: [sufficient/partial/insufficient]

Expected output: Multiple solutions (at least 3), tradeoff analysis, recommendation and implementation steps, residual risks

Completion condition: coverageAssessment=sufficient

When not reached:

  1. Return to Step 1 with unchecked areas identified by verifier as investigation targets
  2. Maximum 2 additional investigation iterations
  3. After 2 iterations without reaching sufficient, present user with options:
    • Continue additional investigation
    • Execute solution at current coverage level

Step 5: Final Report Creation

Prerequisite: coverageAssessment=sufficient achieved

After diagnosis completion, report to user in the following format:

## Diagnosis Result Summary

### Identified Failure Points
[Confirmed failure points from verification results]
- Per failure point: location, symptom explained, finalStatus

### Verification Process
- Path coverage: [Paths traced and nodes checked]
- Additional investigation iterations: [0/1/2]
- Coverage assessment: [sufficient/partial/insufficient]

### Recommended Solution
[Solution derivation recommendation]

Rationale: [Selection rationale]

### Implementation Steps
1. [Step 1]
2. [Step 2]
...

### Alternatives
[Alternative description]

### Residual Risks
[solver's residualRisks]

### Post-Resolution Verification Items
- [Verification item 1]
- [Verification item 2]

Completion Criteria

  • Executed investigator and obtained pathMap, failurePoints, and impactAnalysis
  • Performed investigation quality check and re-ran if insufficient
  • Executed verifier and obtained coverage assessment
  • Executed solver
  • Achieved coverageAssessment=sufficient (or obtained user approval after 2 additional iterations)
  • Presented final report to user
作为编排者,依据subagents-orchestration-guide规范,全周期管理从需求到部署的实施流程。通过委派子代理、严格遵循步骤与停止点确认,实现需求分析、设计、规划、实施及QA的自动化协同执行。
启动新的软件功能或修复需求的全生命周期实施 继续中断的开发流程并验证当前阶段进度 处理质量错误、测试失败或构建错误以触发修复流程
dev-workflows/skills/recipe-implement/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-implement -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-implement",
    "description": "Orchestrate the complete implementation lifecycle from requirements to deployment",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Full-cycle implementation management (Requirements Analysis → Design → Planning → Implementation → Quality Assurance)

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Follow subagents-orchestration-guide skill flows exactly:
    • Execute one step at a time in the defined flow (Large/Medium/Small scale)
    • When flow specifies "Execute document-reviewer" → Execute it immediately
    • Stop at every [Stop: ...] marker → Use AskUserQuestion for confirmation and wait for approval before proceeding
  3. Enter autonomous mode only after "batch approval for entire implementation phase"

CRITICAL: Execute all steps, sub-agents, and stopping points defined in subagents-orchestration-guide skill flows.

Execution Decision Flow

1. Current Situation Assessment

Instruction Content: $ARGUMENTS

Assess the current situation:

Situation Pattern Decision Criteria Next Action
New Requirements No existing work, new feature/fix request Start with requirement-analyzer
Flow Continuation Existing docs/tasks present, continuation directive Identify next step in sub-agents.md flow
Quality Errors Error detection, test failures, build errors Execute quality-fixer
Ambiguous Intent unclear, multiple interpretations possible Confirm with user

2. Progress Verification for Continuation

When continuing existing flow, verify:

  • Latest artifacts (PRD/ADR/Design Doc/Work Plan/Tasks)
  • Current phase position (Requirements/Design/Planning/Implementation/QA)
  • Identify next step in subagents-orchestration-guide skill corresponding flow

3. Next Action Execution

MANDATORY subagents-orchestration-guide skill reference:

  • Verify scale-based flow (Large/Medium/Small scale)
  • Confirm autonomous execution mode conditions
  • Recognize mandatory stopping points
  • Invoke next sub-agent defined in flow

After requirement-analyzer [Stop]

When user responds to questions:

  • If response matches any scopeDependencies.question → Check impact for scale change
  • If scale changes → Re-execute requirement-analyzer with updated context
  • If confidence: "confirmed" or no scale change → Proceed to next step

4. Register All Flow Steps Using TaskCreate (MANDATORY)

After scale determination, register all steps of the applicable flow using TaskCreate:

  • First task: "Map preloaded skills to applicable concrete rules"
  • Register each step as individual task
  • Set currently executing step to in_progress using TaskUpdate
  • Complete task registration before invoking subagents

Subagents Orchestration Guide Compliance Execution

Pre-execution Checklist (MANDATORY):

  • Confirmed relevant subagents-orchestration-guide skill flow
  • Identified current progress position
  • Clarified next step
  • Recognized stopping points
  • codebase-analyzer included before Design Doc creation (Medium/Large scale)
  • code-verifier included before document-reviewer for Design Doc review (Medium/Large scale)
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Required Flow Compliance:

  • Run quality-fixer before every commit
  • Obtain user approval before Edit/Write/MultiEdit outside autonomous mode

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Mandatory Orchestrator Responsibilities

Task Execution Quality Cycle (4-Step Cycle per Task)

Per-task cycle (complete each task before starting next):

  1. Agent tool (subagent_type: "dev-workflows:task-executor") → Pass task file path in prompt, receive structured response
  2. Check task-executor response:
    • status: escalation_needed or blocked → Escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 1 with requiredFixes
      • approved → Proceed to step 3
    • Otherwise → Proceed to step 3
  3. quality-fixer → Quality check and fixes. Always pass the current task file path as task_file
    • stub_detected → Return to step 1 with incompleteImplementations[] details
    • blocked → Escalate to user
    • approved → Proceed to step 4
  4. git commit → Execute with Bash (on approved)

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows:code-verifier") → doc_type: design-doc, Design Doc path, code_paths: implementation file list (git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows:security-reviewer") → Design Doc path, implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute task-executor with consolidated fixes → quality-fixer
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file matching docs/plans/tasks/{plan-name}-task-*.md (the {plan-name} derived from the work plan path used in this run)
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer)
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Test Information Communication

After acceptance-test-generator execution, when invoking work-planner (subagent_type: "dev-workflows:work-planner"), communicate:

  • Generated integration test file path (from generatedFiles.integration)
  • Generated fixture-e2e test file path or null (from generatedFiles.fixtureE2e)
  • Generated service-integration-e2e test file path or null (from generatedFiles.serviceE2e)
  • Per-lane E2E absence reason (from e2eAbsenceReason.fixtureE2e and e2eAbsenceReason.serviceE2e, when each lane is null)
  • Explicit note: integration tests are created simultaneously with implementation, fixture-e2e tests are created alongside the UI feature phase, service-integration-e2e tests are executed only in the final phase

Execution Method

All work is executed through sub-agents. Sub-agent selection follows subagents-orchestration-guide skill.

该技能用于根据设计文档创建工作执行计划并获取审批。它协调子智能体,可选生成测试骨架,利用工作规划器制定计划,经文档审查员审核后最终获得用户批准。
需要根据设计文档创建工作执行计划 请求创建开发工作计划
dev-workflows/skills/recipe-plan/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-plan -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-plan",
    "description": "Create work plan from design document and obtain plan approval",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the planning phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
  2. Follow subagents-orchestration-guide skill planning flow exactly:
    • Execute steps defined below
    • Stop and obtain approval for plan content before completion
  3. Scope: See Scope Boundaries below

CRITICAL: When the user requests test generation, always execute acceptance-test-generator first — it provides the test skeleton that work-planner depends on.

Scope Boundaries

Included in this skill:

  • Design document selection
  • Test skeleton generation with acceptance-test-generator
  • Work plan creation with work-planner
  • Work plan review with document-reviewer
  • Plan approval obtainment

Responsibility Boundary: This skill completes with work plan approval.

Follow the planning process below:

Execution Process

Step 1: Design Document Selection

! ls -la docs/design/*.md | head -10

  • Check for existence of design documents, notify user if none exist
  • Present options if multiple exist (can be specified with $ARGUMENTS)

Step 2: Test Skeleton Generation Confirmation

  • Confirm with user whether to generate test skeletons (integration + E2E lanes) first
  • If user wants generation: invoke acceptance-test-generator
  • Pass generation results to next process according to subagents-orchestration-guide skill coordination specification

Step 3: Work Plan Creation

Invoke work-planner using Agent tool:

  • subagent_type: "dev-workflows:work-planner"

  • description: "Work plan creation"

  • If test skeletons were generated in Step 2, build the prompt by listing every lane's status:

    • Always include: "Integration test file: [path or 'not generated']"
    • For each E2E lane (fixtureE2e, serviceE2e):
      • When generatedFiles.<lane> is not null: "[lane] test file: [path]"
      • When generatedFiles.<lane> is null: "No [lane] skeleton generated (reason: [e2eAbsenceReason.])"
    • Append placement guidance: "Integration tests are created simultaneously with each phase implementation. fixture-e2e tests are created alongside the UI feature phase. service-integration-e2e tests are executed only in the final phase."
  • If test skeletons were not generated: prompt: "Create work plan from Design Doc at [path]."

  • Follow subagents-orchestration-guide Prompt Construction Rule for additional prompt parameters

Step 4: Work Plan Review

Invoke document-reviewer to review the work plan:

  • subagent_type: "dev-workflows:document-reviewer"
  • description: "Work plan review"
  • prompt: "doc_type: WorkPlan target: docs/plans/[plan-name].md. Review semantic traceability to the Design Doc, early verification placement, real-boundary verification coverage, Failure Mode Checklist, and Review Scope."
  • The work plan is a derivation of the Design Doc, so plan-fidelity findings are resolved without user input. Branch on the reviewer's verdict.decision: on needs_revision, re-invoke work-planner in update mode with the findings and re-review, repeating until approved or approved_with_conditions. On rejected, escalate to the user.

Step 5: Present for Approval

  • Present the reviewed work plan to the user for batch approval. If the user requests changes, re-invoke work-planner with revised parameters and re-run Step 4.
  • Highlight steps with unclear scope or external dependencies and ask the user to confirm

Response at Completion

Recommended: After plan approval, output the standard block below.

Planning phase completed.
- Work plan: docs/plans/[plan-name].md
- Status: Approved

Please provide separate instructions for implementation.

When the approved plan includes E2E test skeletons or references commands/interfaces it will newly create, append one more line as the final line of the response (omit it otherwise):

Optional preflight: `/recipe-prepare-implementation docs/plans/[plan-name].md` verifies these are implementable before build (exits no-op if all resolve).
在工作计划进入构建阶段前,验证其端到端可实施性。检查验证策略、E2E环境及UI组件就绪情况,解决缺失的依赖或配置缺口,确保从第一阶段起即可观测,若已就绪则无操作退出。
提及 implement-ready/verification readiness/lane setup/E2E environment missing 工作计划的就绪状态未经过预检且即将开始构建
dev-workflows/skills/recipe-prepare-implementation/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-prepare-implementation -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-prepare-implementation",
    "description": "Verifies the work plan is implementable end-to-end and resolves verification-lane \/ fixture \/ E2E-environment gaps before the build phase begins. Use when \"implement-ready\/verification readiness\/lane setup\/E2E environment missing\" is mentioned, or before any build phase begins on a work plan whose readiness has not been preflight-checked.",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Optional readiness phase between work-plan approval and recipe-*-build. Confirms the implementation will be observable from Phase 1 onward and resolves any gaps via Phase 0 tasks. Exits no-op when the readiness criteria already pass, so the recipe is safe to invoke unconditionally.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Self-contained scope: When gaps are found, this recipe BOTH generates resolution tasks AND executes them through the standard 4-step cycle. Recipe completes only when readiness criteria pass or remaining gaps are escalated.
  3. No-op exit: When the readiness scan finds no failing criteria, generate no resolution tasks and exit immediately, presenting the Readiness Report to the user. No files are modified in this branch.

Work plan: $ARGUMENTS

When This Recipe Applies

Run before any recipe-*-build invocation when ANY of the following hold:

  • Work plan was created from a Design Doc whose Verification Strategy references commands, files, functions, or endpoints not yet present in the codebase
  • Work plan includes E2E test skeletons (seed data, auth fixture, environment variables, or external mocks may be unaddressed)
  • Work plan touches UI components without a fixture entry or development route to render their visual states
  • The team has not previously confirmed the local lane runs end-to-end for this feature area

When none of the above hold, the readiness scan in Step 2 will find zero failing criteria and the recipe exits no-op (see Context at the top of this skill).

Readiness Criteria

Each criterion is a measurable check producing pass, fail, or not_applicable with cited evidence.

ID Criterion Pass evidence
R1 Verification Strategy references resolve Every command, file path, function, endpoint, and test referenced in the work plan's Verification Strategy section either exists in the codebase (verified via Glob/Grep) or is the deliverable of a task already in this plan
R2 E2E preconditions addressed When E2E skeletons exist: every precondition mentioned in skeleton comments (seed data, auth fixture, env var, external mock) is present in the codebase or covered by a Phase 0 task in this plan
R3 Phase 1 observability The first implementation phase contains at least one task whose Operation Verification Methods can execute at task completion using only artifacts that exist before the task starts (existing code, prior Phase 0 task deliverables, or the task's own outputs)
R4 UI rendering surface When the plan implements UI components: a fixture entry, dev route, Storybook story, or equivalent rendering surface exists for the impacted components, OR a Phase 0 task adds one
R5 Local lane procedure The work plan or a referenced doc records the commands needed to start the system locally for manual verification (start commands, default ports, seed steps)

R4 and R5 are evaluated only when their triggering signals appear in the work plan; otherwise mark not_applicable.

Pre-execution Prerequisites

# Verify the work plan exists
! ls -la docs/plans/*.md | grep -v template | tail -5

State check:

  • Work plan exists → Proceed to Step 1
  • No work plan → Stop and report: "An approved work plan is required. Complete the upstream planning phase first, then re-invoke this recipe."

Execution Flow

Step 1: Load Inputs

Read the work plan path passed in $ARGUMENTS. Extract:

  • Verification Strategy section (Correctness Proof Method + Early Verification Point)
  • Quality Assurance Mechanisms table
  • Design-to-Plan Traceability table
  • Test skeleton references listed in the plan header
  • Phase structure with each phase's tasks
  • Referenced Design Doc(s) and UI Spec (when present)

Step 2: Readiness Scan

For each criterion R1–R5:

  1. Execute the scan defined in Readiness Criteria using Read / Glob / Grep
  2. Record the result: pass / fail / not_applicable
  3. Cite evidence: file:line for pass, the unresolved reference for fail, the missing trigger signal for not_applicable

Build the Readiness Report (see Output Format) regardless of outcome.

Step 3: No-op Check

When every applicable criterion is pass (zero fail):

  • Present the Readiness Report (see Output Format below) to the user
  • Exit with outcome: ready, gaps_resolved: 0
  • No files are modified in this branch

When one or more criteria are fail → proceed to Step 4.

Step 4: Plan Resolution Tasks

For each fail criterion:

  1. Determine the smallest concrete task that closes the gap (examples: "Add fixture entry for ComponentX covering loading/empty/error states", "Add seed script for E2E user fixtures", "Document local startup commands in docs/run/local.md")

  2. Decide the task's layer by matching every target file path against the markers below:

    • backend when every target file path matches one of: **/api/**, **/server/**, **/services/**, **/backend/**, **/handlers/**, **/repositories/**
    • frontend when every target file path matches one of: **/components/**, **/pages/**, **/web/**, **/frontend/**, **/*.tsx, **/*.jsx
    • mixed (target files span both backend and frontend markers) → escalate to user; ask the user to split the gap into per-layer tasks
    • unrecognized (any target file matches neither backend nor frontend markers — e.g., docs/**, scripts/**, root-level configs, fixture data files outside the markers above) → escalate to user; ask the user to either (a) decide which layer's executor / quality-fixer should run the task, or (b) update the markers if the project uses different paths

    Apply the rules in the order above. The first matching rule wins; "unrecognized" is the final fallback rather than a catch-all that defaults to backend.

  3. Create a Phase 0 task file at docs/plans/tasks/{plan-name}-backend-task-prep-{NN}.md (backend) or docs/plans/tasks/{plan-name}-frontend-task-prep-{NN}.md (frontend) using the task template from documentation-criteria skill. The -task-prep- segment lets recipe-prepare-implementation distinguish prep tasks from implementation tasks while keeping the existing {plan-name}-{layer}-task-* matcher used by other recipes

  4. Update the work plan to insert these tasks as Phase 0 (before Phase 1)

Present the proposed resolution task list to the user with AskUserQuestion. Proceed only after explicit approval — this is the single human gate inside this recipe.

Step 5: Execute Resolution Tasks

For each resolution task, run the standard 4-step cycle (see subagents-orchestration-guide "Task Management: 4-Step Cycle"):

  1. Agent tool — route by filename layer segment:
    • *-backend-task-prep-*subagent_type: "dev-workflows:task-executor"
    • *-frontend-task-prep-*subagent_type: "dev-workflows-frontend:task-executor-frontend"
    • Filename without a recognized layer segment → escalate (the file should not exist; Step 4 prevents this)
  2. Check escalation per orchestration-guide
  3. quality-fixer — route by the same filename layer segment:
    • *-backend-task-prep-*"dev-workflows:quality-fixer"
    • *-frontend-task-prep-*"dev-workflows-frontend:quality-fixer-frontend"
  4. Commit when quality-fixer returns approved

Append the Scope Boundary block (below) to every subagent prompt.

Step 6: Re-scan, Present Readiness Report, Cleanup, Exit

  1. Re-scan: Re-run the Step 2 readiness scan after all resolution tasks are committed.

  2. Present Readiness Report: Present the Readiness Report (see Output Format below) to the user. The report is shown in-session and is not written into the work plan — the durable output of this recipe is the committed Phase 0 resolution tasks, not a persisted report.

  3. Final Cleanup: Delete every prep task file this recipe created for the current {plan-name} (docs/plans/tasks/{plan-name}-backend-task-prep-*.md and docs/plans/tasks/{plan-name}-frontend-task-prep-*.md) AND the phase-completion file generated for prep phases (docs/plans/tasks/{plan-name}-phase0-completion.md when present, since prep tasks live in Phase 0). Prep task files for other plans are out of scope — this recipe deletes only what it created for the current run. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs. The work plan itself is preserved for the downstream recipe--build / recipe--implement.

  4. Exit:

    Re-scan result Action
    All applicable criteria pass Exit with outcome: ready, gaps_resolved: N and final Readiness Report
    One or more fail remain Exit with outcome: escalated — present remaining failures to the user with the next-action recommendation. Treat the re-scan as the terminal evaluation; further resolution requires the user to re-invoke this recipe with updated inputs.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Output Format

Final report presented to the user at exit:

## Implementation Readiness Report

Work plan: [path]
Outcome: ready | escalated
Gaps resolved: [N]

### Readiness Criteria

| ID | Result | Evidence |
|----|--------|----------|
| R1 | pass / fail / not_applicable | [file:line OR "missing: <unresolved reference>"] |
| R2 | ... | ... |
| R3 | ... | ... |
| R4 | ... | ... |
| R5 | ... | ... |

### Resolution Tasks Executed (when gaps_resolved > 0)
- [task file path] — [one-line summary] — committed
- ...

### Remaining Gaps (when outcome is escalated)
- [criterion ID]: [unresolved reference] — Next action: [recommendation]

Completion Criteria

  • Work plan loaded and Verification Strategy / E2E references / Phase structure extracted
  • Readiness scan run with per-criterion result and evidence recorded
  • No-op exit when all pass, OR resolution tasks generated, approved, and executed via the 4-step cycle
  • Re-scan run after the last resolution task commits
  • Prep task files (and Phase 0 phase-completion file when generated) deleted from docs/plans/tasks/
  • Final report presented to the user
该技能通过发现、生成、验证和审查工作流,从现有代码库逆向工程生成产品需求文档(PRD)和设计文档。支持分阶段处理、多智能体协作及人工审核,适用于全栈或特定架构的代码文档化。
用户希望从现有代码生成PRD 用户需要为代码库创建设计文档 请求对代码进行逆向工程以获取技术规格
dev-workflows/skills/recipe-reverse-engineer/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-reverse-engineer -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-reverse-engineer",
    "description": "Generate PRD and Design Docs from existing codebase through discovery, generation, verification, and review workflow",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Reverse engineering workflow to create documentation from existing code

Target: $ARGUMENTS

Orchestrator Definition

Core Identity: "I am an orchestrator."

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Process one step at a time: Execute steps sequentially within each unit (2 → 3 → 4 → 5). Each step's output is the required input for the next step. Complete all steps for one unit before starting the next
  3. Pass $STEP_N_OUTPUT as-is to sub-agents — the orchestrator bridges data without processing or filtering it

Task Registration: Register phases first using TaskCreate, then steps within each phase as you enter it. Update status using TaskUpdate.

Step 0: Initial Configuration

0.1 Scope Confirmation

Use AskUserQuestion to confirm:

  1. Target path: Which directory/module to document
  2. Depth: PRD only, or PRD + Design Docs
  3. Reference Architecture: layered / mvc / clean / hexagonal / none
  4. Human review: Yes (recommended) / No (fully autonomous)
  5. Fullstack design: Yes / No
    • Yes: For each functional unit, generate backend + frontend Design Docs
    • Note: Requires both agents (technical-designer, technical-designer-frontend)

0.2 Output Configuration

  • PRD output: docs/prd/ or existing PRD directory
  • Design Doc output: docs/design/ or existing design directory
  • Verify directories exist, create if needed

Workflow Overview

Phase 1: PRD Generation
  Step 1: Scope Discovery (unified, single pass → group into PRD units → human review)
  Step 2-5: Per-unit loop (Generation → Verification → Review → Revision)

Phase 2: Design Doc Generation (if requested)
  Step 6: Design Doc Scope Mapping (reuse Step 1 results, no re-discovery)
  Step 7-10: Per-unit loop (Generation → Verification → Review → Revision)
  ※ fullstack=Yes: each unit produces backend + frontend Design Docs

Phase 1: PRD Generation

Register using TaskCreate:

  • Step 1: PRD Scope Discovery
  • Per-unit processing (Steps 2-5 for each unit)

Step 1: PRD Scope Discovery

Agent tool invocation:

subagent_type: dev-workflows:scope-discoverer
description: "Discover functional scope"
prompt: |
  Discover functional scope targets in the codebase.

  target_path: $USER_TARGET_PATH
  reference_architecture: $USER_RA_CHOICE
  focus_area: $USER_FOCUS_AREA (if specified)

Store output as: $STEP_1_OUTPUT

Quality Gate:

  • At least one unit discovered → proceed
  • No units discovered → ask user for hints
  • $STEP_1_OUTPUT.prdUnits exists
  • All sourceUnits across prdUnits (flattened, deduplicated) match the set of discoveredUnits IDs — no unit missing, no unit duplicated
  • Each discovered unit's unitInventory has at least one non-empty category (routes, testFiles, or publicExports). Units with all three empty indicate incomplete discovery — re-run scope-discoverer with focus on that unit's relatedFiles

Human Review Point (if enabled): Present $STEP_1_OUTPUT.prdUnits with their source unit mapping. The user confirms, adjusts grouping, or excludes units from scope. This is the most important review point — incorrect grouping cascades into all downstream documents.

Step 2-5: Per-Unit Processing

FOR each unit in $STEP_1_OUTPUT.prdUnits (sequential, one unit at a time):

Step 2: PRD Generation

Agent tool invocation:

subagent_type: dev-workflows:prd-creator
description: "Generate PRD"
prompt: |
  Create reverse-engineered PRD for the following feature.

  Operation Mode: reverse-engineer
  External Scope Provided: true

  Feature: $PRD_UNIT_NAME (from $STEP_1_OUTPUT)
  Description: $PRD_UNIT_DESCRIPTION
  Related Files: $PRD_UNIT_COMBINED_RELATED_FILES
  Entry Points: $PRD_UNIT_COMBINED_ENTRY_POINTS

  Use provided scope as investigation starting point.
  If tracing entry points reveals files outside this scope, include them.
  Create final version PRD based on thorough code investigation.

Store output as: $STEP_2_OUTPUT (PRD path)

Step 3: Code Verification

Prerequisite: $STEP_2_OUTPUT (PRD path from Step 2)

Agent tool invocation:

subagent_type: dev-workflows:code-verifier
description: "Verify PRD consistency"
prompt: |
  Verify consistency between PRD and code implementation.

  doc_type: prd
  document_path: $STEP_2_OUTPUT
  verbose: false

Note: Omit code_paths — the verifier independently discovers code scope from the document, ensuring independent verification not constrained by scope-discoverer's output.

Store output as: $STEP_3_OUTPUT

Quality Gate:

  • consistencyScore >= 70 AND verifiableClaimCount >= 20 → proceed to review
  • consistencyScore >= 70 BUT verifiableClaimCount < 20 → re-run verifier (investigation too shallow)
  • consistencyScore < 70 → flag for detailed review

Step 4: Review

Required Input: $STEP_3_OUTPUT (verification JSON from Step 3)

Agent tool invocation:

subagent_type: dev-workflows:document-reviewer
description: "Review PRD"
prompt: |
  Review the following PRD considering code verification findings.

  doc_type: PRD
  target: $STEP_2_OUTPUT
  mode: composite
  code_verification: $STEP_3_OUTPUT

  ## Additional Review Focus
  - Alignment between PRD claims and verification evidence
  - Resolution recommendations for each discrepancy
  - Completeness of undocumented feature coverage

Store output as: $STEP_4_OUTPUT

Step 5: Revision (conditional)

Trigger Conditions (any one of the following):

  • Review status is "Needs Revision" or "Rejected"
  • Critical discrepancies exist in $STEP_3_OUTPUT
  • consistencyScore < 70

Agent tool invocation:

subagent_type: dev-workflows:prd-creator
description: "Revise PRD"
prompt: |
  Update PRD based on review feedback and code verification results.

  Operation Mode: update
  Existing PRD: $STEP_2_OUTPUT

  ## Review Feedback
  $STEP_4_OUTPUT

  ## Code Verification Results
  $STEP_3_OUTPUT

  Address discrepancies by severity. Critical and major items require correction.
  Minor items: correct if straightforward, otherwise leave as-is with rationale.

Loop Control: Maximum 2 revision cycles. After 2 cycles, flag for human review regardless of status.

Unit Completion

  • Review status is "Approved" or "Approved with Conditions"
  • Human review passed (if enabled in Step 0)

Next: Proceed to next unit. After all units → Phase 2.

Phase 2: Design Doc Generation

Execute only if Design Docs were requested in Step 0

Register using TaskCreate:

  • Step 6: Design Doc Scope Mapping
  • Per-unit processing (Steps 7-10 for each unit)

Step 6: Design Doc Scope Mapping

No additional discovery required. Use $STEP_1_OUTPUT.discoveredUnits (implementation-granularity units) for technical profiles. Use $STEP_1_OUTPUT.prdUnits[].sourceUnits to trace which discovered units belong to each PRD unit.

Each PRD unit from Phase 1 maps to Design Doc unit(s):

  • Standard mode (fullstack=No): 1 PRD unit → 1 Design Doc (using technical-designer)
  • Fullstack mode (fullstack=Yes): 1 PRD unit → 2 Design Docs (technical-designer + technical-designer-frontend)

Map $STEP_1_OUTPUT units to Design Doc generation targets, carrying forward:

  • technicalProfile.primaryModules → Primary Files
  • technicalProfile.publicInterfaces → Public Interfaces
  • dependencies → Dependencies
  • relatedFiles → Scope boundary
  • unitInventory → Unit Inventory (routes, test files, public exports)

Store output as: $STEP_6_OUTPUT

Step 7-10: Per-Unit Processing

FOR each unit in $STEP_6_OUTPUT (sequential, one unit at a time):

Step 7: Design Doc Generation

Scope: Document the current architecture exactly as implemented in code.

Standard mode (fullstack=No):

Agent tool invocation:

subagent_type: dev-workflows:technical-designer
description: "Generate Design Doc"
prompt: |
  Create Design Doc for the following feature based on existing code.

  Operation Mode: reverse-engineer

  Feature: $UNIT_NAME (from $STEP_6_OUTPUT)
  Description: $UNIT_DESCRIPTION
  Primary Files: $UNIT_PRIMARY_MODULES
  Public Interfaces: $UNIT_PUBLIC_INTERFACES
  Dependencies: $UNIT_DEPENDENCIES
  Unit Inventory: $UNIT_INVENTORY (routes, test files, public exports from scope discovery)

  Parent PRD: $APPROVED_PRD_PATH

  Document current architecture as-is. Use Unit Inventory as a completeness baseline — all routes and exports should be accounted for in the Design Doc.

Store output as: $STEP_7_OUTPUT

Fullstack mode (fullstack=Yes):

For each unit, invoke 7a then 7b sequentially (7b depends on 7a output):

7a. Backend Design Doc:

subagent_type: dev-workflows:technical-designer
description: "Generate backend Design Doc"
prompt: |
  Create a backend Design Doc for the following feature based on existing code.

  Operation Mode: reverse-engineer

  Feature: $UNIT_NAME (from $STEP_6_OUTPUT)
  Description: $UNIT_DESCRIPTION
  Primary Files: $UNIT_PRIMARY_MODULES
  Public Interfaces: $UNIT_PUBLIC_INTERFACES
  Dependencies: $UNIT_DEPENDENCIES
  Unit Inventory: $UNIT_INVENTORY

  Parent PRD: $APPROVED_PRD_PATH

  Focus on: API contracts, data layer, business logic, service architecture.
  Document current architecture as-is. Use Unit Inventory as completeness baseline.

Store output as: $STEP_7a_OUTPUT

7b. Frontend Design Doc:

subagent_type: dev-workflows-frontend:technical-designer-frontend
description: "Generate frontend Design Doc"
prompt: |
  Create a frontend Design Doc for the following feature based on existing code.

  Operation Mode: reverse-engineer

  Feature: $UNIT_NAME (from $STEP_6_OUTPUT)
  Description: $UNIT_DESCRIPTION
  Primary Files: $UNIT_PRIMARY_MODULES
  Public Interfaces: $UNIT_PUBLIC_INTERFACES
  Dependencies: $UNIT_DEPENDENCIES
  Unit Inventory: $UNIT_INVENTORY

  Parent PRD: $APPROVED_PRD_PATH
  Backend Design Doc: $STEP_7a_OUTPUT

  Reference backend Design Doc for API contracts.
  Focus on: component hierarchy, state management, UI interactions, data fetching.
  Document current architecture as-is. Use Unit Inventory as completeness baseline.

Store output as: $STEP_7b_OUTPUT

Step 8: Code Verification

Standard mode: Verify $STEP_7_OUTPUT.

Fullstack mode: Verify each Design Doc separately.

Agent tool invocation (per Design Doc):

subagent_type: dev-workflows:code-verifier
description: "Verify Design Doc consistency"
prompt: |
  Verify consistency between Design Doc and code implementation.

  doc_type: design-doc
  document_path: $STEP_7_OUTPUT (or $STEP_7a_OUTPUT / $STEP_7b_OUTPUT)
  verbose: false

Note: Omit code_paths — the verifier independently discovers code scope from the document.

Store output as: $STEP_8_OUTPUT

Step 9: Review

Required Input: $STEP_8_OUTPUT (verification JSON from Step 8)

Agent tool invocation (per Design Doc):

subagent_type: dev-workflows:document-reviewer
description: "Review Design Doc"
prompt: |
  Review the following Design Doc considering code verification findings.

  doc_type: DesignDoc
  target: $STEP_7_OUTPUT (or $STEP_7a_OUTPUT / $STEP_7b_OUTPUT)
  mode: composite
  code_verification: $STEP_8_OUTPUT

  ## Parent PRD
  $APPROVED_PRD_PATH

  ## Additional Review Focus
  - Technical accuracy of documented interfaces
  - Consistency with parent PRD scope
  - Completeness of unit boundary definitions

Store output as: $STEP_9_OUTPUT

Step 10: Revision (conditional)

Trigger Conditions (same as Step 5):

  • Review status is "Needs Revision" or "Rejected"
  • Critical discrepancies exist in $STEP_8_OUTPUT
  • consistencyScore < 70

Agent tool invocation (per Design Doc):

subagent_type: dev-workflows:technical-designer (or dev-workflows-frontend:technical-designer-frontend for frontend Design Docs)
description: "Revise Design Doc"
prompt: |
  Update Design Doc based on review feedback and code verification results.

  Operation Mode: update
  Existing Design Doc: $STEP_7_OUTPUT (or $STEP_7a_OUTPUT / $STEP_7b_OUTPUT)

  ## Review Feedback
  $STEP_9_OUTPUT

  ## Code Verification Results
  $STEP_8_OUTPUT

  Address discrepancies by severity. Critical and major items require correction.
  Minor items: correct if straightforward, otherwise leave as-is with rationale.

Loop Control: Maximum 2 revision cycles. After 2 cycles, flag for human review regardless of status.

Unit Completion

  • Review status is "Approved" or "Approved with Conditions"
  • Human review passed (if enabled in Step 0)

Next: Proceed to next unit. After all units → Final Report.

Final Report

Output summary including:

  • Generated documents table (Type, Name, Consistency Score, Review Status)
  • Action items (critical discrepancies, undocumented features, flagged items)
  • Next steps checklist

Error Handling

Error Action
Discovery finds nothing Ask user for project structure hints
Generation fails Log failure, continue with other units, report in summary
consistencyScore < 50 Flag for mandatory human review — require explicit human approval
Review rejects after 2 revisions Stop loop, flag for human intervention
作为编排器验证代码与设计文档的一致性及安全性。通过调用子代理执行审查,根据结果判断是修复代码还是更新设计文档,支持自动修复并重新验证,确保实现质量与合规性。
需要检查代码是否符合设计文档规范时 需要进行安全合规性审计时 发现代码与设计文档不一致需决定修复方向时
dev-workflows/skills/recipe-review/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-review -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-review",
    "description": "Design Doc compliance and security validation with optional auto-fixes",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Post-implementation quality assurance

Orchestrator Definition

Core Identity: "I am an orchestrator."

First Action: Register Steps 1-11 using TaskCreate before any execution.

Execution Method

  • Compliance validation → performed by code-reviewer
  • Security validation → performed by security-reviewer
  • Code-side fix path: Fix implementation → task-executor; Quality checks → quality-fixer; Re-validation → code-reviewer / security-reviewer
  • Design-side update path: DD revision → technical-designer (update mode); DD review → document-reviewer; cross-DD consistency → design-sync (when multiple DDs exist); Re-validation → code-reviewer

Orchestrator invokes sub-agents and passes structured JSON between them. The design-side path applies when the discrepancy reflects code that was correct but the Design Doc became stale, rather than code that violated the Design Doc.

Design Doc (uses most recent if omitted): $ARGUMENTS

Execution Flow

Step 1: Prerequisite Check

# Identify Design Doc
ls docs/design/*.md | grep -v template | tail -1

# Check implementation files
git diff --name-only main...HEAD

Step 2: Execute code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows:code-reviewer"
  • description: "Code compliance review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review mode: full. Validate Design Doc compliance and return structured JSON report."

Store output as: $STEP_2_OUTPUT

Step 3: Execute security-reviewer

Invoke security-reviewer using Agent tool:

  • subagent_type: "dev-workflows:security-reviewer"
  • description: "Security review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review security compliance."

Store output as: $STEP_3_OUTPUT

Step 4: Verdict and Response

If security-reviewer returned blocked: Stop immediately. Report the blocked finding and escalate to user. Do not proceed to fix steps.

Code compliance criteria (considering project stage):

  • Prototype: Pass at 70%+
  • Production: 90%+ recommended

Security criteria:

  • approved or approved_with_notes → Pass
  • needs_revision → Fail

Report both results independently using subagent output fields only:

Before presenting to the user, the orchestrator computes a recommended route per finding using the rule below (this rule is internal — do not include it in the user-facing prompt):

Finding pattern Recommended route
dd_violation where the code intent matches the original requirement but the Design Doc captured a different design d (Design-side update)
dd_violation where the code drifted from a still-correct Design Doc c (Code-side fix)
reliability / security / maintainability findings c (Code-side fix)

Then present to the user (label each finding with its recommended route, grouped by route):

Code Compliance: [complianceRate from code-reviewer]
  Verdict: [verdict from code-reviewer]
  Identifier Match Rate: [identifierMatchRate from code-reviewer]
  Acceptance Criteria:
  - [fulfilled] [item] (confidence: [high/medium/low])
  - [partially_fulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  - [unfulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  Identifier Mismatches:
  - [identifier]: DD=[designDocValue] Code=[codeValue] at [location] [recommended: c | d]
  Quality Findings:
  - [category] [location]: [description] — [rationale] [recommended: c]

Security Review: [status from security-reviewer]
  Findings by category:
  - [confirmed_risk] [location]: [description] — [rationale] [recommended: c]
  - [defense_gap] [location]: [description] — [rationale] [recommended: c]
  - [hardening] [location]: [description] — [rationale] [recommended: c]
  - [policy] [location]: [description] — [rationale] [recommended: c]
  Notes: [notes from security-reviewer, if present]

Resolve discrepancies — confirm or override the recommended route per finding:
  c) Code-side fix       — code violates Design Doc; modify code to match
  d) Design-side update  — code is correct; Design Doc is stale, revise it
  s) Skip                — accept current state without changes

Use AskUserQuestion. The default offer is "accept all recommended routes" — a single confirmation for the typical case where the orchestrator's recommendations are correct. When the user wants to override, collect per-finding c/d/s decisions instead. If the user selects s for everything: skip Steps 5-10, proceed to Step 11.

Step 5: Execute Skill

Execute Skill: documentation-criteria (for task file template)

Step 5d: Design-Side Update

Run this step only when the user routed at least one finding to d. When all routes are c or s, skip directly to Step 6.

  1. Invoke technical-designer in update mode using Agent tool:

    • subagent_type: "dev-workflows:technical-designer"
    • description: "Design Doc update from review findings"
    • prompt: "Update Design Doc at [path] in update mode. The implementation has diverged in the following ways that the team has decided to ratify in the design rather than in the code: [list of d-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
  2. Invoke document-reviewer to verify the updated Design Doc:

    • subagent_type: "dev-workflows:document-reviewer"
    • description: "Document review of updated Design Doc"
    • prompt: "Review updated Design Doc at [path] for consistency and completeness."
  3. When multiple Design Docs exist (ls docs/design/*.md | grep -v template | wc -l > 1), invoke design-sync:

    • subagent_type: "dev-workflows:design-sync"
    • description: "Cross-DD consistency check"
    • prompt: "source_design: [updated DD path]. Detect conflicts across all Design Docs after the update."
    • When sync_status: conflicts_found: present conflicts to the user; resolution requires re-invoking technical-designer for affected DDs.
  4. After Step 5d completes:

    • If the user selected d for all findings (no c routes) → skip Steps 6-8, proceed to Step 9 for re-validation
    • If the user selected both d and c → re-evaluate the c-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remaining c findings

Step 6: Create Task File

Create task file at docs/plans/tasks/review-fixes-YYYYMMDD.md Include both code compliance issues and security requiredFixes.

Step 7: Execute Fixes

Invoke task-executor using Agent tool:

  • subagent_type: "dev-workflows:task-executor"
  • description: "Execute review fixes"
  • prompt: "Task file: docs/plans/tasks/review-fixes-YYYYMMDD.md. Apply staged fixes (stops at 5 files)."

Step 8: Quality Check

Invoke quality-fixer using Agent tool:

  • subagent_type: "dev-workflows:quality-fixer"
  • description: "Quality gate check"
  • prompt: "Confirm quality gate passage for fixed files."

Step 9: Re-validate code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows:code-reviewer"
  • description: "Re-validate compliance"
  • prompt: "Re-validate Design Doc compliance after fixes. Prior compliance issues: $STEP_2_OUTPUT. Verify each prior issue is resolved (whether resolved code-side or design-side)."

Step 10: Re-validate security-reviewer

Invoke security-reviewer using Agent tool (only if security fixes were applied):

  • subagent_type: "dev-workflows:security-reviewer"
  • description: "Re-validate security"
  • prompt: "Re-validate security after fixes. Prior findings: $STEP_3_OUTPUT. Design Doc: [path]. Implementation files: [file list]."

Step 11: Final Cleanup and Report

Delete the review-fix task file this recipe created (if any). Its work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete docs/plans/tasks/review-fixes-YYYYMMDD.md if it exists

If the file cannot be deleted (filesystem error), report the failure but do not block the final report.

Then present the final report:

Code Compliance:
  Initial: [X]%
  Final: [Y]% (if fixes executed)

Security Review:
  Initial: [status]
  Final: [status] (if fixes executed)
  Notes: [notes from approved_with_notes, if any]

Remaining issues:
- [items requiring manual intervention]

Cleanup: review-fixes task file removed

Auto-fixable Items (code-side path)

  • Simple unimplemented acceptance criteria
  • Error handling additions
  • Contract definition fixes
  • Function splitting (length/complexity improvements)
  • Security confirmed_risk and defense_gap fixes (input validation, auth checks, output encoding)

Non-fixable Items

  • Fundamental business logic changes
  • Architecture-level modifications
  • Committed secrets (blocked → human intervention)

Design-Side Update Triggers

Discrepancies suitable for the design-side path (code is correct, DD became stale):

  • Identifier renames where the new identifier reflects the team's current naming
  • Behavioral changes that match the original requirement intent better than what the DD captured
  • Component splits or merges where the new structure is sound and the DD documented the prior structure
  • New ACs that the implementation already satisfies but the DD never enumerated

Scope: Design Doc compliance validation, security review, code-side auto-fixes, and design-side update routing.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the review scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.
通过调用rule-advisor进行元认知分析,选择规则并识别潜在失败模式。随后创建任务列表,结合规则指导执行任务,确保遵循最佳实践并监控警告模式以优化结果。
需要执行复杂任务并遵循特定规则时 希望利用元认知分析避免常见错误时
dev-workflows/skills/recipe-task/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-task -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-task",
    "description": "Execute tasks following appropriate rules with rule-advisor metacognition",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Task Execution with Metacognitive Analysis

Task: $ARGUMENTS

Mandatory Execution Process

Step 1: Rule Selection via rule-advisor (REQUIRED)

Invoke rule-advisor using Agent tool:

  • subagent_type: "dev-workflows:rule-advisor"
  • description: "Rule selection"
  • prompt: "Task: $ARGUMENTS. Select appropriate rules and perform metacognitive analysis."

Step 2: Utilize rule-advisor Output

After receiving rule-advisor's JSON response, proceed with:

  1. Understand Task Essence (from taskAnalysis.essence)

    • Focus on fundamental purpose, not surface-level work
    • Distinguish between "quick fix" vs "proper solution"
  2. Follow Selected Rules (from selectedRules)

    • Review each selected rule section
    • Apply concrete procedures and guidelines
  3. Recognize Past Failures (from metaCognitiveGuidance.pastFailures)

    • Apply countermeasures for known failure patterns
    • Use suggested alternative approaches
  4. Execute First Action (from metaCognitiveGuidance.firstStep)

    • Start with recommended action
    • Use suggested tools first

Step 3: Create Task List with TaskCreate

Register work steps using TaskCreate. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON".

Break down the task based on rule-advisor's guidance:

  • Reflect taskAnalysis.essence in task descriptions
  • Apply metaCognitiveGuidance.firstStep to first task
  • Restructure tasks considering warningPatterns
  • Set priorities based on dependency order and warningPatterns severity

Step 4: Execute Implementation

Proceed with task execution following:

  • Start with metaCognitiveGuidance.firstStep action from rule-advisor
  • Update task structure with TaskUpdate to reflect rule-advisor insights
  • Selected rules from rule-advisor
  • Task structure (managed via TaskCreate/TaskUpdate)
  • Quality standards defined in the selectedRules output from rule-advisor
  • Monitor warningPatterns flags throughout execution and adjust approach when triggered
用于更新现有设计文档(Design Doc/PRD/ADR)的编排技能。通过识别目标、澄清变更、调用子代理执行更新,并经过严格的质量门禁审查与一致性校验,确保文档最终获得批准。
需要修改或更新现有的设计文档、产品需求文档或架构决策记录 对已生成的技术设计或PRD进行迭代和完善
dev-workflows/skills/recipe-update-doc/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-update-doc -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-update-doc",
    "description": "Update existing design documents (Design Doc \/ PRD \/ ADR) with review",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to updating existing design documents.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

First Action: Register Steps 1-6 using TaskCreate before any execution.

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Execute update flow:
    • Identify target → Clarify changes → Update document → Review → Consistency check
    • Stop at every [Stop: ...] marker → Wait for user approval before proceeding
  3. Scope: Complete when updated document receives approval

CRITICAL: Execute document-reviewer and all stopping points — each serves as a quality gate for document accuracy.

Workflow Overview

Target document → [Stop: Confirm changes]
                        ↓
              technical-designer / technical-designer-frontend / prd-creator (update mode)
                        ↓ (Design Doc only)
              code-verifier → document-reviewer → [Stop: Review approval]
                        ↓ (Design Doc only)
              design-sync → [Stop: Final approval]

Scope Boundaries

Included in this skill:

  • Existing document identification and selection
  • Change content clarification with user
  • Document update with appropriate agent (update mode)
  • Document review with document-reviewer
  • Consistency verification with design-sync (Design Doc only)

Out of scope (redirect to appropriate skills):

  • New requirement analysis
  • Work planning or implementation

Responsibility Boundary: This skill completes with updated document approval.

Target document: $ARGUMENTS

Execution Flow

Step 1: Target Document Identification

# Check existing documents
ls docs/design/*.md docs/prd/*.md docs/adr/*.md 2>/dev/null | grep -v template

Decision flow:

Situation Action
$ARGUMENTS specifies a path Use specified document
$ARGUMENTS describes a topic Search documents matching the topic
Multiple candidates found Present options with AskUserQuestion
No documents found Report and end (document creation is out of scope)

Step 2: Document Type and Layer Determination

Determine type from document path, then determine the layer to select the correct update agent:

Path Pattern Type Update Agent Notes
docs/design/*.md Design Doc technical-designer or technical-designer-frontend See layer detection below
docs/prd/*.md PRD prd-creator -
docs/adr/*.md ADR technical-designer or technical-designer-frontend See layer detection below

Layer detection (for Design Doc and ADR): Read the document and determine its layer from content signals:

  • Frontend (→ technical-designer-frontend): Document title/scope mentions React, components, UI, frontend; or file contains component hierarchy, state management, UI interactions
  • Backend (→ technical-designer): All other cases (API, data layer, business logic, infrastructure)

ADR Update Guidance:

  • Minor changes (clarification, typo fix, small scope adjustment): Update the existing ADR file
  • Major changes (decision reversal, significant scope change): Create a new ADR that supersedes the original

Step 3: Change Content Clarification [Stop]

Use AskUserQuestion to clarify what changes are needed:

  • What sections need updating
  • Reason for the change (bug fix findings, spec change, review feedback, etc.)
  • Expected outcome after the update

Confirm understanding of changes with user before proceeding.

Step 4: Document Update

Invoke the update agent determined in Step 2:

subagent_type: [Update Agent from Step 2]
description: "Update [Type from Step 2]"
prompt: |
  Operation Mode: update
  Existing Document: [path from Step 1]

  ## Changes Required
  [Changes clarified in Step 3]

  Update the document to reflect the specified changes.
  Add change history entry.

Step 5: Document Review [Stop]

For Design Doc updates only: Before document-reviewer, invoke code-verifier:

subagent_type: code-verifier
description: "Verify updated Design Doc"
prompt: |
  doc_type: design-doc
  document_path: [path from Step 1]
  Verify the updated Design Doc against current codebase.

  Verification focus: Pay special attention to literal identifier referential
  integrity in the updated sections (paths, endpoints, type names, config keys).

Store output as: $CODE_VERIFICATION_OUTPUT

Invoke document-reviewer:

subagent_type: document-reviewer
description: "Review updated document"
prompt: |
  Review the following updated document.

  doc_type: [Design Doc / PRD / ADR]
  target: [path from Step 1]
  mode: standard
  code_verification: $CODE_VERIFICATION_OUTPUT (Design Doc only, omit for PRD/ADR)

  Focus on:
  - Consistency of updated sections with rest of document
  - No contradictions introduced by changes
  - Completeness of change history

Store output as: $STEP_5_OUTPUT

On review result:

  • Approved → Proceed to Step 6
  • Needs revision → Return to Step 4 with the following prompt (max 2 iterations):
    subagent_type: [Update Agent from Step 2]
    description: "Revise [Type from Step 2]"
    prompt: |
      Operation Mode: update
      Existing Document: [path from Step 1]
    
      ## Review Feedback to Address
      $STEP_5_OUTPUT
    
      Address each issue raised in the review feedback.
    
  • After 2 rejections → Flag for human review, present accumulated feedback to user and end

Present review result to user for approval.

Step 6: Consistency Verification (Design Doc only) [Stop]

Skip condition: Document type is PRD or ADR → Proceed to completion.

For Design Doc, invoke design-sync:

subagent_type: design-sync
description: "Verify consistency"
prompt: |
  Verify consistency of the updated Design Doc with other design documents.

  Updated document: [path from Step 1]

On consistency result:

  • No conflicts → Present result to user for final approval
  • Conflicts detected → Present conflicts to user with AskUserQuestion:
    • A: Return to Step 4 to resolve conflicts in this document
    • B: End and address conflicts separately

Error Handling

Error Action
Target document not found Report and end (document creation is out of scope)
Sub-agent update fails Log failure, present error to user, retry once
Review rejects after 2 revisions Stop loop, flag for human intervention
design-sync detects conflicts Present to user for resolution decision

Completion Criteria

  • Identified target document
  • Clarified change content with user
  • Updated document with appropriate agent (update mode)
  • Executed code-verifier before document-reviewer (Design Doc only)
  • Executed document-reviewer and addressed feedback
  • Executed design-sync for consistency verification (Design Doc only)
  • Obtained user approval for updated document

Output Example

Document update completed.

  • Updated document: docs/design/[document-name].md
  • Approval status: User approved
指导多智能体协作与工作流程编排。通过需求分析器评估规模,协调专用子代理执行任务分解、设计、编码及审查。支持监控范围变更并重启流程,确保自主执行与质量合规。
需要协调多个子代理完成任务 管理复杂的工作流阶段 确定自主执行模式
dev-workflows/skills/subagents-orchestration-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill subagents-orchestration-guide -g -y
SKILL.md
Frontmatter
{
    "name": "subagents-orchestration-guide",
    "description": "Guides subagent coordination through implementation workflows. Use when orchestrating multiple agents, managing workflow phases, or determining autonomous execution mode."
}

Subagents Orchestration Guide

Role: The Orchestrator

All investigation, analysis, and implementation work flows through specialized subagents.

First Action Rule

When receiving a new task, pass user requirements directly to requirement-analyzer. Determine the workflow based on its scale assessment result.

Requirement Change Detection During Flow

During flow execution, monitor user responses for scope-expanding signals:

  • Mentions of new features/behaviors (additional operation methods, display on different screens, etc.)
  • Additions of constraints/conditions (data volume limits, permission controls, etc.)
  • Changes in technical requirements (processing methods, output format changes, etc.)

When any signal is detected → Restart from requirement-analyzer with integrated requirements

Available Subagents

Implementation support:

  1. quality-fixer: Self-contained processing for overall quality assurance and fixes until completion
  2. task-decomposer: Appropriate task decomposition of work plans
  3. task-executor: Individual task execution and structured response
  4. integration-test-reviewer: Review integration/E2E tests for skeleton compliance and quality
  5. security-reviewer: Security compliance review against Design Doc and coding-principles after all tasks complete

Document creation: 6. requirement-analyzer: Requirement analysis and work scale determination 7. codebase-analyzer: Analyze existing codebase to produce focused guidance for technical design (data, contracts, dependencies, quality assurance mechanisms) 8. ui-analyzer: Read the project's external-resources file, fetch external UI sources (design origin, design system, guidelines) via MCP/URL/file, and analyze existing UI code. Frontend/fullstack features; runs in parallel with codebase-analyzer. Uses disallowedTools to inherit MCP access 9. prd-creator: Product Requirements Document creation 10. ui-spec-designer: UI Specification creation from PRD and optional prototype code (frontend/fullstack features) 11. technical-designer: ADR/Design Doc creation 12. work-planner: Work plan creation from Design Doc and test skeletons 13. document-reviewer: Single document quality and rule compliance check 14. code-verifier: Verify document-code consistency. Pre-implementation: Design Doc claims against existing codebase. Post-implementation: implementation against Design Doc 15. design-sync: Design Doc consistency verification across multiple documents 16. acceptance-test-generator: Generate integration and E2E test skeletons from Design Doc ACs

Orchestration Principles

Delegation Boundary: What vs How

The orchestrator passes what to accomplish and where to work. Each specialist determines how to execute autonomously.

Pass to specialists (what/where/constraints):

  • Target directory, package, or file paths
  • Task file path or scope description
  • Acceptance criteria and hard constraints from the user or design artifacts

Let specialists determine (how):

  • Specific commands to run (specialists discover these from project configuration and repo conventions)
  • Execution order and tool flags
  • Which files to inspect or modify within the given scope
Bad (orchestrator prescribes how) Good (orchestrator passes what)
quality-fixer "Run these checks: 1. lint 2. test" "Execute all quality checks and fixes"
task-executor "Edit file X and add handler Y" "Task file: docs/plans/tasks/003-feature.md"

Decision precedence when outputs conflict:

  1. User instructions (explicit requests or constraints)
  2. Task files and design artifacts (Design Doc, PRD, work plan)
  3. Objective repo state (git status, file system, project configuration)
  4. Specialist judgment

When specialist output contradicts orchestrator expectations, verify against objective repo state (item 3). If repo state confirms the specialist, follow the specialist. Override specialist output only when it conflicts with items 1 or 2.

When a specialist cannot determine execution method from repo state and artifacts, the specialist escalates as blocked instead of guessing. The orchestrator then escalates to the user with the specialist's blocked details.

Task Assignment with Responsibility Separation

Assign work based on each subagent's responsibilities:

What to delegate to task-executor:

  • Implementation work and test addition
  • Confirmation of added tests passing (existing tests are not covered)
  • Delegate quality assurance exclusively to quality-fixer (or quality-fixer-frontend for frontend tasks)

What to delegate to quality-fixer:

  • Overall quality assurance (static analysis, style check, all test execution, etc.)
  • Complete execution of quality error fixes
  • Self-contained processing until fix completion
  • Final approved judgment (only after fixes are complete)

Constraints Between Subagents

Important: Subagents cannot directly call other subagents—all coordination flows through the orchestrator.

Explicit Stop Points

Autonomous execution MUST stop and wait for user input at these points. Use AskUserQuestion to present confirmations and questions.

Phase Stop Point User Action Required
Requirements After requirement-analyzer completes Confirm requirements / Answer questions
PRD After document-reviewer completes PRD review Approve PRD
UI Spec After document-reviewer completes UI Spec review (frontend/fullstack) Approve UI Spec
ADR After document-reviewer completes ADR review (if ADR created) Approve ADR
Design After design-sync completes consistency verification Approve Design Doc
Work Plan After work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) or work-planner (Small) completes Batch approval for implementation phase

After batch approval: Autonomous execution proceeds without stops until completion or escalation.

Scale Determination and Document Requirements

Scale File Count PRD ADR Design Doc Work Plan
Small 1-2 Update※1 Not needed Not needed Simplified
Medium 3-5 Update※1 Conditional※2 Required Required
Large 6+ Required※3 Conditional※2 Required Required

※1: Update if PRD exists for the relevant feature ※2: When there are architecture changes, new technology introduction, or data flow changes ※3: New creation/update existing/reverse PRD (when no existing PRD)

How to Call Subagents

Execution Method

Each subagent invocation is a fresh Agent tool call, isolating each phase's context; a SendMessage resume reuses the prior agent's context and breaks that isolation. Each call uses:

  • subagent_type: Agent name (e.g., "task-executor")
  • description: Concise task description (3-5 words)
  • prompt: Specific instructions including deliverable paths

Orchestrator's Permitted Tools

The orchestrator coordinates work using only the following tools:

Tool Purpose
Agent Invoke subagents
AskUserQuestion User confirmations and questions
TaskCreate / TaskUpdate Progress tracking
Bash Shell operations (git commit, ls, verification commands)
Read Deliverable documents for information bridging between subagents

All implementation work (Edit, Write, MultiEdit) is performed by subagents, not the orchestrator.

Prompt Construction Rule

Every subagent prompt must include:

  1. Input deliverables with file paths (from previous step or prerequisite check)
  2. Expected action (what the agent should do)

Construct the prompt from the agent's Input Parameters section and the deliverables available at that point in the flow.

Two additional rules:

  • Subagents see only the Agent prompt and files they read. Include required paths, prior JSON, parameters, and scope constraints explicitly.
  • Replace every [placeholder] in examples below with concrete values before invoking the Agent tool.

Call Example (requirement-analyzer)

  • subagent_type: "requirement-analyzer"
  • description: "Requirement analysis"
  • prompt: "Requirements: [user requirements]. Context: [any relevant context]. Perform requirement analysis and scale determination."

Call Example (codebase-analyzer)

  • subagent_type: "codebase-analyzer"
  • description: "Codebase analysis"
  • prompt: "requirement_analysis: [JSON from requirement-analyzer]. prd_path: [path if exists]. requirements: [original user requirements]. Analyze the existing codebase and produce design guidance."

Call Example (ui-analyzer)

  • subagent_type: "ui-analyzer"
  • description: "UI fact gathering"
  • prompt: "requirement_analysis: [JSON from requirement-analyzer]. requirements: [original user requirements]. ui_spec_path: [path if exists]. target_components: [list if focused]. Read docs/project-context/external-resources.md, fetch external UI sources via the declared access methods (MCP / URL / file), and analyze the existing UI codebase. Output the consolidated UI fact JSON."

When invoked alongside codebase-analyzer for frontend or fullstack-frontend work, run both agents in parallel and pass both JSON outputs to consumers (ui-spec-designer for the design phase; technical-designer-frontend for the Design Doc phase).

Call Example (task-executor)

  • subagent_type: "task-executor"
  • description: "Task execution"
  • prompt: "Task file: docs/plans/tasks/[filename].md Please complete the implementation"

Structured Response Specification

Subagents respond in JSON format. Key fields for orchestrator decisions:

  • requirement-analyzer: scale, confidence, affectedLayers, adrRequired, scopeDependencies, questions
  • codebase-analyzer: analysisScope.categoriesDetected, dataModel.detected, qualityAssurance (mechanisms[], domainConstraints[]), focusAreas[], existingElements count, limitations
  • ui-analyzer: analysisScope.uiConventions, externalResources (designOrigin/designSystem/guidelines/visualVerification with fetch_status), componentStructure[], propsPatterns[], cssLayout[], stateDisplay[], displayConditions[], i18n, accessibility[], generatedArtifacts[], focusAreas[] (raw fact_id; consumers apply ui: prefix when merging with codebase analysis facts), candidateWriteSet[] (with confidence labels), limitations
  • code-verifier: status (consistent/mostly_consistent/needs_review/inconsistent), consistencyScore, discrepancies[], reverseCoverage (including dataOperationsInCode, testBoundariesSectionPresent). Pre-implementation: verifies Design Doc claims against existing codebase. Post-implementation: verifies implementation consistency against Design Doc (pass code_paths scoped to changed files)
  • task-executor: status (escalation_needed/completed), escalation_type (design_compliance_violation/similar_function_found/investigation_target_not_found/out_of_scope_file/dependency_version_uncertain/binding_decision_violation/test_environment_not_ready), testsAdded, requiresTestReview
  • quality-fixer: Input: task_file (path to current task file — always pass this in orchestrated flows). Status: approved/stub_detected/blocked. stub_detected → route back to task-executor with incompleteImplementations[] details for completion, then re-run quality-fixer. blocked → discriminate by reason field: "Cannot determine due to unclear specification" → read blockingIssues[] for specification details; "Execution prerequisites not met" → read missingPrerequisites[] with resolutionSteps — present these to the user as actionable next steps
  • document-reviewer: verdict.decision (approved/approved_with_conditions/needs_revision/rejected)
  • design-sync: sync_status (synced/conflicts_found)
  • integration-test-reviewer: status (approved/needs_revision/blocked), requiredFixes
  • security-reviewer: status (approved/approved_with_notes/needs_revision/blocked), findings, notes, requiredFixes
  • acceptance-test-generator: status, generatedFiles.{integration,fixtureE2e,serviceE2e} (path|null per lane), budgetUsage per lane, e2eAbsenceReason per E2E lane (null when emitted; reason enum is owned by acceptance-test-generator and integration-e2e-testing skill)

Handling Requirement Changes

Handling Requirement Changes in requirement-analyzer

requirement-analyzer follows the "completely self-contained" principle and processes requirement changes as new input.

How to Integrate Requirements

Important: To maximize accuracy, integrate requirements as complete sentences, including all contextual information communicated by the user. Result format: raw concatenation of all requirements, followed by a labeled summary (Initial requirement: … / Additional requirement: …).

Update Mode for Document Generation Agents

Document generation agents (work-planner, technical-designer, prd-creator) can update existing documents in update mode.

  • Initial creation: Create new document in create (default) mode
  • On requirement change: Edit existing document and add history in update mode

Criteria for timing when to call each agent:

  • work-planner: Request updates only before execution
  • technical-designer: Request updates according to design changes → Execute document-reviewer for consistency check
  • prd-creator: Request updates according to requirement changes → Execute document-reviewer for consistency check
  • document-reviewer: Always execute before user approval after PRD/ADR/Design Doc creation/update, and after Work Plan creation/update at Medium/Large scale (Small uses a simplified plan with no semantic review — no Design Doc to trace against)

Basic Flow: Planning and Implementation

Always start with requirement-analyzer, then select the minimum planning flow required by scale and affected layers.

Planning flow (per scale)

Scale Planning flow (ends at task-decomposer for Medium/Large; ends at work-planner for Small)
Large requirement-analyzer → PRD → PRD review → external resource hearing → optional ADR → codebase-analyzer (+ ui-analyzer in parallel for frontend/fullstack) → optional UI Spec → Design Doc → code-verifier → document-reviewer → design-sync → acceptance-test-generator → work-planner → work plan review (document-reviewer, doc_type WorkPlan) → task-decomposer
Medium requirement-analyzer → external resource hearing → codebase-analyzer (+ ui-analyzer in parallel for frontend/fullstack) → optional UI Spec → optional ADR → Design Doc → code-verifier → document-reviewer → design-sync → acceptance-test-generator → work-planner → work plan review (document-reviewer, doc_type WorkPlan) → task-decomposer
Small requirement-analyzer → work-planner

External resource hearing runs in the orchestrator (it requires AskUserQuestion). ui-analyzer joins codebase-analyzer in parallel only when the work has a frontend surface; for backend-only work the planning flow uses codebase-analyzer alone.

After the planning flow completes and the user grants batch approval, implementation proceeds. Verifying the plan is implementable end-to-end (verification lanes, fixtures, E2E environment) is an optional preflight the user runs at their discretion via the recipe-prepare-implementation recipe; this guide does not invoke any orchestrator above the agent layer.

Then execute the task execution cycle: task-executor → quality-fixer → commit for each task. See "Autonomous Execution Mode" below for full per-task details. At Small scale this cycle still applies — implementation runs through task-executor, not orchestrator-direct edits.

Each agent name in the chain is invoked via the Agent tool (per "Orchestrator's Permitted Tools" above).

Rules:

  • Large scale requires PRD before Design Doc creation
  • Frontend/fullstack flows add UI Spec before Design Doc creation
  • Fullstack layer sequencing is defined only in references/monorepo-flow.md
  • design-sync is required whenever multiple Design Docs exist
  • task-decomposer begins only after work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) and batch approval
  • Work plan review self-heals: on verdict.decision needs_revision, route back to work-planner (update) and re-review until approved/approved_with_conditions; rejected escalates to the user. The work plan is a derivation of the Design Doc, so plan-fidelity findings need no user adjudication

Autonomous Execution Mode

Pre-Execution Environment Check

Principle: Verify subagents can complete their responsibilities

Required environments:

  • Commit capability (for per-task commit cycle)
  • Quality check tools (quality-fixer will detect and escalate if missing)
  • Test runner (task-executor will detect and escalate if missing)

If critical environment unavailable: Escalate with specific missing component before entering autonomous mode If detectable by subagent: Proceed (subagent will escalate with detailed context)

Authority Delegation

After environment check passes:

  • Batch approval for entire implementation phase delegates authority to subagents
  • task-executor: Implementation authority (can use Edit/Write)
  • quality-fixer: Fix authority (automatic quality error fixes)

Definition of Autonomous Execution Mode

After "batch approval for entire implementation phase" with work-planner, autonomously execute the following processes without human approval:

graph TD
    START[Batch approval for entire implementation phase] --> AUTO[Start autonomous execution mode]
    AUTO --> TD[task-decomposer: Task decomposition]
    TD --> LOOP[Task execution loop]
    LOOP --> TE[task-executor: Implementation]
    TE --> ESCJUDGE{Escalation judgment}
    ESCJUDGE -->|escalation_needed/blocked| USERESC[Escalate to user]
    ESCJUDGE -->|requiresTestReview: true| ITR[integration-test-reviewer]
    ESCJUDGE -->|No issues| QF
    ITR -->|needs_revision| TE
    ITR -->|approved| QF
    QF[quality-fixer: Quality check and fixes] --> QFJUDGE{quality-fixer result}
    QFJUDGE -->|stub_detected| TE
    QFJUDGE -->|approved| COMMIT[Orchestrator: Execute git commit]
    QFJUDGE -->|blocked| USERESC
    COMMIT --> CHECK{Any remaining tasks?}
    CHECK -->|Yes| LOOP
    CHECK -->|No| VERIFY[Post-implementation verification]
    VERIFY --> CV[code-verifier: DD consistency check]
    VERIFY --> SEC[security-reviewer: Security review]
    CV --> VRESULT{Verification results}
    SEC --> VRESULT
    VRESULT -->|All passed| REPORT[Completion report]
    VRESULT -->|Any failed| VFIX[task-executor: Verification fixes]
    VFIX --> QF2[quality-fixer: Quality check]
    QF2 --> REVERIFY[Re-run failed verifiers only]
    REVERIFY --> VRESULT
    VRESULT -->|blocked| USERESC

    LOOP --> INTERRUPT{User input?}
    INTERRUPT -->|None| TE
    INTERRUPT -->|Yes| REQCHECK{Requirement change check}
    REQCHECK -->|No change| TE
    REQCHECK -->|Change| STOP[Stop autonomous execution]
    STOP --> RA[Re-analyze with requirement-analyzer]

Post-Implementation Verification Pass/Fail Criteria

Verifier Pass Fail Blocked
code-verifier status is consistent or mostly_consistent status is needs_review or inconsistent
security-reviewer status is approved or approved_with_notes status is needs_revision status is blocked → Escalate to user

Re-run rule: After fix cycle, re-run only verifiers that returned fail. Verifiers that passed on the previous run are not re-run.

Conditions for Stopping Autonomous Execution

Stop autonomous execution and escalate to user in the following cases:

  1. Escalation from subagent

    • When receiving response with status: "escalation_needed"
    • When receiving response with status: "blocked"
  2. When requirement change detected

    • Any match in requirement change detection checklist
    • Stop autonomous execution and re-analyze with integrated requirements in requirement-analyzer
  3. When work-planner update restriction is violated

    • Requirement changes after task-decomposer starts require overall redesign
    • Restart entire flow from requirement-analyzer
  4. When user explicitly stops

    • Direct stop instruction or interruption

Task Management: 4-Step Cycle

Per-task cycle:

  1. Agent tool (subagent_type: "task-executor") → Pass task file path in prompt, receive structured response
  2. Check task-executor response:
    • status: escalation_needed or blocked → Escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 1 with requiredFixes
      • approved → Proceed to step 3
    • Otherwise → Proceed to step 3
  3. quality-fixer → Quality check and fixes. Always pass the current task file path as task_file
    • stub_detected → Return to step 1 with incompleteImplementations[] details
    • blocked → Escalate to user
    • approved → Proceed to step 4
  4. git commit → Execute with Bash (on approved)

Progress Tracking

Register overall phases using TaskCreate. Update each phase with TaskUpdate as it completes.

Main Orchestrator Roles

  1. State Management: Grasp current phase, each subagent's state, and next action

  2. Information Bridging: Data conversion and transmission between subagents

    • Convert each subagent's output to next subagent's input format
    • Always pass deliverables from previous process to next agent
    • Extract necessary information from structured responses
    • Compose commit messages from changeSummary
    • Explicitly integrate initial and additional requirements when requirements change

    Handoff Contracts

    HC-01: requirement-analyzer → codebase-analyzer

    • Pass: requirement_analysis, prd_path (if exists), original user requirements

    HC-02: codebase-analyzer → technical-designer

    • Pass: full codebase-analyzer JSON as additional context
    • Required downstream uses:
      • focusAreas → canonical disposition-target list for the Fact Disposition Table
      • dataModel, dataTransformationPipelines, qualityAssurance → Existing Codebase Analysis / Verification Strategy / Quality Assurance sections

    HC-03: technical-designer → code-verifier

    • Pass: Design Doc path (doc_type: design-doc)
    • Do not pass code_paths; code-verifier discovers scope from the document

    HC-04: code-verifier + codebase-analyzer → document-reviewer

    • Pass: code_verification JSON and the same codebase_analysis JSON previously given to the designer
    • Purpose: reviewer validates both discrepancy integration and Fact Disposition coverage against focusAreas

    HC-05: code-verifier → next-layer technical-designer (fullstack only)

    • Defined only for multi-layer fullstack flow in references/monorepo-flow.md
    • Pass: prior-layer Design Doc path plus prior_layer_verification
    • Use only discrepancies[] as known issues to address or escalate. Do not infer verified claims that are not explicitly present in the verifier output.

    technical-designer → work-planner

    Pass to work-planner: Design Doc path. Work-planner reads the DD template from documentation-criteria skill, scans all DD sections, and extracts technical requirements in these categories:

    • Verification Strategy: Extracted to work plan header (Correctness Proof Method + Early Verification Point)
    • Implementation targets: Components, functions, or data structures to create or modify
    • Connection/switching/registration: Integration points, dependency wiring, switching methods
    • Contract changes and propagation: Interface changes, data contracts, field propagation across boundaries
    • Verification requirements: Verification methods, test boundaries, integration verification points
    • Prerequisite work: Migration steps, security measures, environment setup

    Work-planner produces a Design-to-Plan Traceability table mapping each extracted item to covering task(s). Items without a covering task must be marked as gap with justification. Unjustified gaps are errors. Justified gaps require user confirmation before plan approval.

    HC-06: acceptance-test-generator → work-planner

    Pass to acceptance-test-generator: Design Doc path; UI Spec path (if exists).

    Orchestrator verification: Every non-null generatedFiles.<lane> path exists on disk. For each null lane, e2eAbsenceReason.<lane> is present (intentional absence, not an error).

    Pass to work-planner: integration / fixture-e2e / service-integration-e2e file paths (or null per lane), per-lane absence reasons, plus timing guidance — integration tests are created alongside each phase implementation, fixture-e2e tests are created alongside the UI feature phase, service-integration-e2e tests are executed only in the final phase.

    On error: Escalate to user when status != completed and integration file generation failed unexpectedly. A null E2E lane with a valid absence reason is not an error.

  3. ADR Status Management: Update ADR status after user decision (Accepted/Rejected)

Important Constraints

Recap (defined above): quality-fixer approval before commit; inter-agent communication is JSON; document-reviewer + user approval before proceeding; check next step against work planning flow after approval; resolve conflicts via Decision precedence.

References

  • references/monorepo-flow.md: Fullstack (monorepo) orchestration flow
执行元认知任务分析与技能选择。通过解析任务本质、评估规模及类型,匹配相关技能并确定优先级,辅助决策复杂任务的执行策略与工具组合。
需要判断任务复杂度时 进行技能选择或估算工作量时
dev-workflows/skills/task-analyzer/SKILL.md
npx skills add shinpr/claude-code-workflows --skill task-analyzer -g -y
SKILL.md
Frontmatter
{
    "name": "task-analyzer",
    "description": "Performs metacognitive task analysis and skill selection. Use when determining task complexity, selecting appropriate skills, or estimating work scale."
}

Task Analyzer

Provides metacognitive task analysis and skill selection guidance.

Skills Index

See skills-index.yaml for available skills metadata.

Task Analysis Process

1. Understand Task Essence

Identify the fundamental purpose beyond surface-level work:

Surface Work Fundamental Purpose
"Fix this bug" Problem solving, root cause analysis
"Implement this feature" Feature addition, value delivery
"Refactor this code" Quality improvement, maintainability
"Update this file" Change management, consistency

Action: Map the user request to one row in the Surface Work → Fundamental Purpose table above. If no row matches, state the fundamental purpose explicitly before proceeding.

2. Estimate Task Scale

Scale File Count Indicators
Small 1-2 Single function/component change
Medium 3-5 Multiple related components
Large 6+ Cross-cutting concerns, architecture impact

Scale affects skill priority:

  • Scale >= Large → include documentation-criteria and implementation-approach in selectedSkills with priority high
  • Scale = Small → limit selectedSkills to task-type essential skills only (max 3)

3. Identify Task Type

Type Characteristics Key Skills
Implementation New code, features coding-principles, testing-principles
Fix Bug resolution ai-development-guide, testing-principles
Refactoring Structure improvement coding-principles, ai-development-guide
Design Architecture decisions documentation-criteria, implementation-approach
Quality Testing, review testing-principles, integration-e2e-testing

4. Tag-Based Skill Matching

Extract relevant tags from task description and match against skills-index.yaml:

Task: "Implement user authentication with tests"
Extracted tags: [implementation, testing, security]
Matched skills:
  - coding-principles (implementation, security)
  - testing-principles (testing)
  - ai-development-guide (implementation)

5. Implicit Relationships

Consider hidden dependencies:

Task Involves Also Include
Error handling debugging, testing
New features design, implementation, documentation
Performance profiling, optimization, testing
Frontend typescript-rules, test-implement
API/Integration integration-e2e-testing

Output Format

Return structured analysis with skill metadata from skills-index.yaml:

taskAnalysis:
  essence: <string>  # Fundamental purpose identified
  type: <implementation|fix|refactoring|design|quality>
  scale: <small|medium|large>
  estimatedFiles: <number>
  tags: [<string>, ...]  # Extracted from task description

selectedSkills:
  - skill: <skill-name>  # From skills-index.yaml
    priority: <high|medium|low>
    reason: <string>  # Why this skill was selected
    # Pass through metadata from skills-index.yaml
    tags: [...]
    typical-use: <string>
    size: <small|medium|large>
    sections: [...]  # All sections from yaml, unfiltered

Note: Section selection (choosing which sections are relevant) is done after reading the actual SKILL.md files.

Skill Selection Priority

  1. Essential - Directly related to task type
  2. Quality - Testing and quality assurance
  3. Process - Workflow and documentation
  4. Supplementary - Reference and best practices

Metacognitive Question Design

Generate 3-5 questions according to task nature:

Task Type Question Focus
Implementation Design validity, edge cases, performance
Fix Root cause (5 Whys), impact scope, regression testing
Refactoring Current problems, target state, phased plan
Design Requirement clarity, future extensibility, trade-offs

Warning Patterns

Detect and flag these patterns:

Pattern Warning Mitigation
Large change detected Pair with implementation-approach Split into phases per strategy
Implementation task detected Pair with testing-principles Apply TDD from start
Error fix requested Pair with ai-development-guide Apply 5 Whys before fixing
Multi-file task without plan Pair with documentation-criteria Create work plan first
提供语言无关的测试原则,涵盖TDD红绿重构循环、AAA模式及各类测试类型。指导编写高质量、快速且独立的测试,强调覆盖率为诊断信号而非目标,适用于测试编写、策略设计及质量审查。
编写单元测试或集成测试 设计测试策略 审查测试代码质量 实施TDD流程
dev-workflows/skills/testing-principles/SKILL.md
npx skills add shinpr/claude-code-workflows --skill testing-principles -g -y
SKILL.md
Frontmatter
{
    "name": "testing-principles",
    "description": "Language-agnostic testing principles including TDD, test quality, coverage standards, and test design patterns. Use when writing tests, designing test strategies, or reviewing test quality."
}

Language-Agnostic Testing Principles

Test-Driven Development (TDD)

The RED-GREEN-REFACTOR Cycle

Always follow this cycle:

  1. RED: Write a failing test first

    • Write the test before implementation
    • Ensure the test fails for the right reason
    • Verify test can actually fail
  2. GREEN: Write minimal code to pass

    • Implement just enough to make the test pass
    • Focus on making it work
  3. REFACTOR: Improve code structure

    • Clean up implementation
    • Eliminate duplication
    • Improve naming and clarity
    • Keep all tests passing
  4. VERIFY: Ensure all tests still pass

    • Run full test suite
    • Check for regressions
    • Validate refactoring didn't break anything

Quality Requirements

Coverage

  • Treat coverage as a diagnostic signal for finding untested areas, not a target — a target gets gamed into trivial tests (Goodhart's Law)
  • Concentrate tests on critical paths, business logic, and behavior whose regression would matter
  • Prioritize meaningful assertions over the coverage number; any CI threshold is the project's config, not a quality goal in itself

Test Characteristics

All tests must be:

  • Independent: No dependencies between tests (see Test Independence Verification for detailed criteria)
  • Reproducible: Same input always produces same output
  • Fast: Unit tests < 100ms each, integration tests < 1s each, full suite < 10 minutes
  • Self-checking: Clear pass/fail without manual verification
  • Timely: Written close to the code they test

Test Types

Unit Tests

Purpose: Test individual components in isolation

Characteristics:

  • Test single function, method, or class
  • Fast execution (milliseconds)
  • No external dependencies
  • Mock external services
  • Majority of your test suite

Integration Tests

Purpose: Test interactions between components

Characteristics:

  • Test multiple components together
  • May include database, file system, or APIs
  • Slower than unit tests
  • Verify contracts between modules
  • Smaller portion of test suite

End-to-End (E2E) Tests

Purpose: Test complete workflows from user perspective

Characteristics:

  • Test entire application stack
  • Simulate real user interactions
  • Slowest test type
  • Fewest in number
  • Highest confidence level

Test Design Principles

AAA Pattern (Arrange-Act-Assert)

Structure every test in three clear phases:

// Arrange: Setup test data and conditions
user = createTestUser()
validator = createValidator()

// Act: Execute the code under test
result = validator.validate(user)

// Assert: Verify expected outcome
assert(result.isValid == true)

Adaptation: Apply this structure using your language's idioms (methods, functions, procedures)

One Assertion Per Concept

  • Test one behavior per test case
  • Multiple assertions OK if testing single concept
  • Split unrelated assertions into separate tests

Example: prefer returns error when email is invalid over validates user.

Descriptive Test Names

Test names should clearly describe:

  • What is being tested
  • Under what conditions
  • What the expected outcome is

Recommended format: "should [expected behavior] when [condition]"

Examples:

test("should return error when email is invalid")
test("should calculate discount when user is premium")
test("should throw exception when file not found")

Adaptation: Follow your project's naming convention (camelCase, snake_case, describe/it blocks)

Test Independence

Setup and Teardown

  • Use setup hooks to prepare test environment
  • Use teardown hooks to clean up resources
  • Keep setup minimal and focused
  • Ensure teardown runs even if test fails

Mocking and Test Doubles

When to Use Mocks

  • Mock external dependencies: APIs, databases, file systems
  • Mock slow operations: Network calls, heavy computations
  • Mock unpredictable behavior: Random values, current time
  • Mock unavailable services: Third-party services

Mocking Principles

  • Mock at boundaries, not internally
  • Keep mocks simple and focused
  • Verify mock expectations when relevant
  • Wrap external libraries/frameworks behind adapters and mock the adapter

Data Layer Testing

Mock Limitations for Data Layer

Mocks validate call patterns but cannot verify data layer correctness. The following pass through undetected with mock-only testing:

  • Schema mismatches (table names, column names, data types)
  • Query correctness (joins, filters, aggregations, grouping)
  • Database constraints (NOT NULL, UNIQUE, foreign keys)
  • Migration drift (schema changes that make code out of sync)

When Mocks Are Appropriate for Data Access

  • Testing business logic that receives data from the data layer (mock the repository, test the service)
  • Testing error handling paths (simulating connection failures, timeouts)
  • Unit tests where data access is a dependency, not the subject under test

When Mocks Are Insufficient for Data Access

  • Testing repository or data access implementations themselves
  • Verifying query correctness (joins, filters, aggregations, grouping)
  • Testing data integrity constraints
  • Testing migration compatibility

Real Database Testing (Environment-Dependent)

Options for verifying data layer correctness against a real database engine:

  • Containerized databases for CI environments
  • In-memory databases for fast feedback (note: dialect differences may mask issues)
  • Dedicated test databases with seed data

The appropriate approach depends on project environment and CI/CD capabilities.

AI-Generated Code and Schema Awareness

  • AI-generated data access code has heightened schema hallucination risk
  • Generated queries may use correct syntax but reference nonexistent schema elements
  • Mock-based tests pass regardless of schema accuracy
  • Mitigation: Design Docs should include explicit schema references so that documented schemas can be cross-checked against data access code during review

Test Quality Practices

Keep Tests Active

  • Fix or delete failing tests: Resolve failures immediately
  • Remove commented-out tests: Fix them or delete entirely
  • Keep tests running: Broken tests lose value quickly
  • Maintain test suite: Refactor tests as needed

Test Helpers and Utilities

  • Create reusable test data builders
  • Extract common setup into helper functions
  • Build test utilities for complex scenarios
  • Share helpers across test files appropriately

What to Test

Focus on Behavior

Test observable behavior, not implementation:

Good: Test that function returns expected output ✓ Good: Test that correct API endpoint is called ✗ Bad: Test that internal variable was set ✗ Bad: Test order of private method calls

Test Public APIs

  • Test through public interfaces
  • Avoid testing private methods directly
  • Test return values, outputs, exceptions
  • Test side effects (database, files, logs)

Test Edge Cases

Always test:

  • Boundary conditions: Min/max values, empty collections
  • Error cases: Invalid input, null values, missing data
  • Edge cases: Special characters, extreme values
  • Happy path: Normal, expected usage

Test Quality Criteria

These criteria ensure reliable, maintainable tests.

Literal Expected Values

  • Use hardcoded literal values in assertions
  • Calculate expected values independently from the implementation
  • If the implementation has a bug, the test catches it through independent verification
  • If expected value equals mock return value unchanged, the test verifies nothing (no transformation occurred)

Result-Based Verification

  • Verify final results and observable outcomes
  • Assert on return values, output data, or system state changes
  • For mock verification, check that correct arguments were passed

Meaningful Assertions

  • Every test must include at least one assertion
  • Assertions must validate observable behavior
  • A test without assertions always passes and provides no value

Appropriate Mock Scope

  • Mock direct external I/O dependencies: databases, HTTP clients, file systems
  • Use real implementations for internal utilities and business logic
  • Over-mocking reduces test value by verifying wiring instead of behavior

Boundary Value Testing

Test at boundaries of valid input ranges:

  • Minimum valid value
  • Maximum valid value
  • Just below minimum (invalid)
  • Just above maximum (invalid)
  • Empty input (where applicable)

Test Independence Verification

Each test must:

  • Create its own test data
  • Not depend on execution order
  • Clean up its own state
  • Pass when run in isolation

Verification Requirements

Before Commit

  • ✓ All tests pass — fix failing tests immediately
  • ✓ No tests skipped or commented — delete or fix
  • ✓ No debug code left in tests
  • ✓ Test coverage meets standards
  • ✓ No flaky tests — make deterministic
  • ✓ Tests run within performance thresholds

Test Organization

File Structure

  • Mirror production structure: Tests follow code organization
  • Clear naming conventions: Follow project's test file patterns
    • Examples: UserService.test.*, user_service_test.*, test_user_service.*, UserServiceTests.*
  • Logical grouping: Group related tests together
  • Separate test types: Unit, integration, e2e in separate directories

Performance Considerations

Test Speed

  • Unit tests: < 100ms each
  • Integration tests: < 1s each
  • Full suite: Should run frequently (< 10 minutes)

Optimization Strategies

  • Run tests in parallel when possible
  • Use in-memory databases for tests
  • Mock expensive operations
  • Split slow test suites
  • Profile and optimize slow tests

Continuous Integration

CI/CD Requirements

  • Run full test suite on every commit
  • Block merges if tests fail
  • Run tests in isolated environments
  • Test on target platforms/versions

Test Reports

  • Generate coverage reports
  • Track test execution time
  • Identify flaky tests
  • Monitor test trends

Test Design Guardrails

Every Test Must

  • Include at least one meaningful assertion
  • Create its own test data and clean up its own state
  • Pass when run in any order and in isolation
  • Test observable behavior through public interfaces
  • Keep test logic simple (no branching, no loops)
  • Mock only external I/O boundaries, use real implementations for internal logic

Flaky Test Resolution

  • Use deterministic time mocking instead of real clocks
  • Use fixed seed values instead of random data
  • Ensure proper resource cleanup in teardown
  • Resolve race conditions with synchronization primitives

Regression Testing

Prevent Regressions

  • Add test for every bug fix
  • Maintain comprehensive test suite
  • Run full suite regularly
  • Keep all tests unless the tested functionality is removed

Legacy Code

  • Add characterization tests before refactoring
  • Test existing behavior first
  • Gradually improve coverage
  • Refactor with confidence

Testing Best Practices by Language Paradigm

Type System Utilization

For languages with static type systems:

  • Leverage compile-time verification for correctness
  • Focus tests on business logic and runtime behavior
  • Use language's type system to prevent invalid states

For languages with dynamic typing:

  • Add comprehensive runtime validation tests
  • Explicitly test data contract validation
  • Consider property-based testing for broader coverage

Programming Paradigm Considerations

Functional approach:

  • Test pure functions thoroughly (deterministic, no side effects)
  • Test side effects at system boundaries
  • Leverage property-based testing for invariants

Object-oriented approach:

  • Test behavior through public interfaces
  • Mock dependencies via abstraction layers
  • Test polymorphic behavior carefully

Common principle: Adapt testing strategy to leverage language strengths while ensuring comprehensive coverage

Documentation and Communication

Tests as Documentation

  • Tests document expected behavior
  • Use clear, descriptive test names
  • Include examples of usage
  • Show edge cases and error handling

Test Failure Messages

  • Provide clear, actionable error messages
  • Include actual vs expected values
  • Add context about what was being tested
  • Make debugging easier
提供技术决策标准、反模式检测及故障快速回退设计原则。用于识别代码异味、规避技术债务,指导错误传播与降级策略,确保系统可观测性与质量保障。
进行技术架构或代码设计决策 检测代码中的反模式或异味 执行代码质量保证审查 设计错误处理与容错机制
skills/ai-development-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill ai-development-guide -g -y
SKILL.md
Frontmatter
{
    "name": "ai-development-guide",
    "description": "Technical decision criteria, anti-pattern detection, debugging techniques, and quality check workflow. Use when making technical decisions, detecting code smells, or performing quality assurance."
}

AI Developer Guide - Technical Decision Criteria and Anti-pattern Collection

Technical Anti-patterns (Red Flag Patterns)

Immediately stop and reconsider design when detecting the following patterns:

Code Quality Anti-patterns

  1. Writing similar code 3 or more times - Violates Rule of Three
  2. Multiple responsibilities mixed in a single file - Violates Single Responsibility Principle (SRP)
  3. Defining same content in multiple files - Violates DRY principle
  4. Making changes without checking dependencies - Potential for unexpected impacts
  5. Disabling code with comments - Should use version control
  6. Error suppression - Hiding problems creates technical debt
  7. Bypassing safety mechanisms (type systems, validation, contracts) - Circumventing language's correctness guarantees

Design Anti-patterns

  • "Make it work for now" thinking - Accumulation of technical debt
  • Patchwork implementation - Unplanned additions to existing code
  • Optimistic implementation of uncertain technology - Designing unknown elements assuming "it'll probably work"
  • Symptomatic fixes - Surface-level fixes that don't solve root causes
  • Unplanned large-scale changes - Lack of incremental approach

Fail-Fast Fallback Design Principles

Core Principle

Make all errors visible and traceable with full context. Prioritize primary code reliability over fallback implementations. Excessive fallback mechanisms mask errors and make debugging difficult.

Implementation Guidelines

Default Approach

  • Propagate all errors explicitly unless a Design Doc specifies a fallback
  • Make failures explicit: Errors should be visible and traceable
  • Preserve error context: Include original error information when re-throwing

When Fallbacks Are Acceptable

  • Only with explicit Design Doc approval: Document why fallback is necessary
  • Business-critical continuity: When partial functionality is better than none
  • Graceful degradation paths: Clearly defined degraded service levels

Layer Responsibilities

  • Infrastructure Layer:

    • Always throw errors upward
    • No business logic decisions
    • Provide detailed error context
  • Application Layer:

    • Make business-driven error handling decisions
    • Implement fallbacks only when specified in requirements
    • Log all fallback activations for monitoring

Error Masking Detection

Review Triggers (require design review):

  • Writing 3rd error handler in the same feature
  • Multiple error handling blocks in single function/method
  • Nested error handling structures
  • Error handlers that return default values without logging

Before Implementing Any Fallback:

  1. Verify Design Doc explicitly defines this fallback
  2. Document the business justification
  3. Ensure error is logged with full context
  4. Add monitoring/alerting for fallback activation

Implementation Pattern

AVOID: Silent fallback that hides errors
    <handle error>:
        return DEFAULT_VALUE  // Error hidden, debugging impossible

PREFERRED: Explicit failure with context
    <handle error>:
        log_error('Operation failed', context, error)
        <propagate error>  // Re-throw exception, return Error, return error tuple

Adaptation: Use language-appropriate error handling (exceptions, Result types, error tuples, etc.)

Rule of Three - Criteria for Code Duplication

How to handle duplicate code based on Martin Fowler's "Refactoring":

Duplication Count Action Reason
1st time Inline implementation Cannot predict future changes
2nd time Consider future consolidation Pattern beginning to emerge
3rd time Implement commonalization Pattern established

Criteria for Commonalization

Cases for Commonalization

  • Business logic duplication
  • Complex processing algorithms
  • Areas likely requiring bulk changes
  • Validation rules

Cases to Avoid Commonalization

  • Accidental matches (coincidentally same code)
  • Possibility of evolving in different directions
  • Significant readability decrease from commonalization
  • Simple helpers in test code

Common Failure Patterns and Avoidance Methods

Pattern 1: Error Fix Chain

Symptom: Fixing one error causes new errors Cause: Surface-level fixes without understanding root cause Avoidance: Identify root cause with 5 Whys before fixing

Pattern 2: Circumventing Correctness Guarantees

Symptom: Bypassing safety mechanisms (type systems, validation, contracts) Cause: Impulse to avoid correctness errors Avoidance: Use language-appropriate safety mechanisms (static checking, runtime validation, contracts, assertions)

Pattern 3: Implementation Without Sufficient Testing

Symptom: Many bugs after implementation Cause: Ignoring Red-Green-Refactor process Avoidance: Always start with failing tests

Pattern 4: Ignoring Technical Uncertainty

Symptom: Frequent unexpected errors when introducing new technology Cause: Assuming "it should work according to official documentation" without prior investigation Avoidance:

  • Record certainty evaluation at the beginning of task files
    Certainty: low (Reason: no working examples found for this integration)
    Exploratory implementation: true
    Fallback: use established alternative approach
    
  • For low certainty cases, create minimal verification code first

Pattern 5: Insufficient Existing Code Investigation

Symptom: Duplicate implementations, architecture inconsistency, integration failures, adopting outdated patterns Cause: Insufficient understanding of existing code before implementation; referencing only nearby files without verifying representativeness Avoidance Methods:

  • Before implementation, always search for similar functionality (using domain, responsibility, configuration patterns as keywords)
  • Similar functionality found → Use that implementation (do not create new implementation)
  • Similar functionality is technical debt → Create ADR improvement proposal before implementation
  • No similar functionality exists → Implement new functionality following existing design philosophy
  • Record all decisions and rationale in "Existing Codebase Analysis" section of Design Doc
  • Reference representativeness check: When adopting a pattern or dependency from nearby code, verify it is representative across the repository before adopting — nearby files alone are an insufficient basis

Debugging Techniques

1. Error Analysis Procedure

  1. Read error message (first line) accurately
  2. Focus on first and last of stack trace
  3. Identify first line where your code appears

2. 5 Whys - Root Cause Analysis

Trace the failure through repeated "why" questions until the root cause is actionable.

3. Minimal Reproduction Code

To isolate problems, attempt reproduction with minimal code:

  • Remove unrelated parts
  • Replace external dependencies with mocks
  • Create minimal configuration that reproduces problem

4. Debug Log Output

Include operation context, relevant input data, current state, and timestamp.

Quality Assurance Mechanism Awareness

Before executing quality checks, identify what quality mechanisms exist for the change area:

  • Primary detection: inspect the change area's file types, project manifest, and configuration to identify applicable quality tools
    • Check CI pipeline definitions for checks that cover the affected paths
    • Check for domain-specific linter or validator configurations (e.g., schema validators, API spec validators, configuration file linters)
    • Check for domain-specific constraints in project configuration (naming rules, length limits, format requirements)
  • Supplementary hint: IF task file specifies Quality Assurance Mechanisms → use them as additional hints for which domain-specific checks to look for
  • Include discovered domain-specific checks alongside standard quality phases below

Quality Check Workflow

Universal quality assurance phases applicable to all languages:

Phase 1: Static Analysis

  1. Code Style Checking: Verify adherence to style guidelines
  2. Code Formatting: Ensure consistent formatting
  3. Unused Code Detection: Identify dead code and unused imports/variables
  4. Static Type Checking: Verify type correctness (for statically typed languages)
  5. Static Analysis: Detect potential bugs, security issues, code smells

Phase 2: Build Verification

  1. Compilation/Build: Verify code builds successfully (for compiled languages)
  2. Dependency Resolution: Ensure all dependencies are available and compatible
  3. Resource Validation: Check configuration files, assets are valid

Phase 3: Testing

  1. Unit Tests: Run all unit tests
  2. Integration Tests: Run integration tests
  3. Test Coverage: Measure and verify coverage meets standards
  4. E2E Tests: Run end-to-end tests

Phase 4: Final Quality Gate

All checks must pass before proceeding:

  • Zero static analysis errors
  • Build succeeds
  • All tests pass
  • Coverage meets project-configured threshold

Quality Check Pattern (Language-Agnostic)

Workflow:
1. Format check → 2. Lint/Style → 3. Static analysis →
4. Build/Compile → 5. Unit tests → 6. Coverage check →
7. Integration tests → 8. Final gate

Auto-fix capabilities (when available):
- Format auto-fix
- Lint auto-fix
- Dependency/import organization
- Simple code smell corrections

Situations Requiring Technical Decisions

Timing of Abstraction

  • Extract patterns after writing concrete implementation 3 times
  • Be conscious of YAGNI, implement only currently needed features
  • Prioritize current simplicity over future extensibility

Performance vs Readability

  • Prioritize readability unless profiling identifies a measurable bottleneck (e.g., response time exceeding SLA, memory exceeding allocation)
  • Measure before optimizing
  • Document reason with comments when optimizing

Granularity of Contracts and Interfaces

  • Overly detailed contracts reduce maintainability
  • Design interfaces where each method maps to a single domain operation and parameter types use domain vocabulary
  • Use abstraction mechanisms to reduce duplication

Scope Expansion

  • Apply implementation/edit instructions to the user's or task's specified scope. Escalate before expanding it.
  • Treat explicit quantities and targets ("one", "this file", "only X") as boundaries
  • Copy/move/mirror requests preserve content verbatim; edit content only when requested
  • Port/translation requests preserve intent and behavior; adapt only what the destination context requires
  • Before changing related files, symmetric locations, adjacent behavior, or adding helpful extras, escalate with the proposed expansion

Implementation Completeness Assurance

Impact Analysis: Mandatory 3-Stage Process

Complete these stages sequentially before any implementation:

1. Discovery - Identify all affected code:

  • Implementation references (imports, calls, instantiations)
  • Interface dependencies (contracts, types, data structures)
  • Test coverage
  • Configuration (build configs, env settings, feature flags)
  • Documentation (comments, docs, diagrams)

2. Understanding - Analyze each discovered location:

  • Role and purpose in the system
  • Dependency direction (consumer or provider)
  • Data flow (origin → transformations → destination)
  • Coupling strength

3. Identification - Produce structured report:

## Impact Analysis
### Direct Impact
- [Unit]: [Reason and modification needed]

### Indirect Impact
- [System]: [Integration path → reason]

### Data Flow
[Source] → [Transformation] → [Consumer]

### Risk Assessment
- High: [Complex dependencies, fragile areas]
- Medium: [Moderate coupling, test gaps]
- Low: [Isolated, well-tested areas]

### Implementation Order
1. [Start with lowest risk or deepest dependency]
2. [...]

Critical: Do not implement until all 3 stages are documented

Unused Code Deletion

When unused code is detected:

  • Will it be used in this work? Yes → Implement now | No → Delete now (Git preserves)
  • Applies to: Code, tests, docs, configs, assets

Existing Code Modification

In use? No → Delete
       Yes → Working? No → Delete + Reimplement
                     Yes → Fix/Extend

Principle: Prefer clean implementation over patching broken code

提供语言无关的代码原则,强调可维护性、简洁性和质量。适用于功能实现、代码重构和质量审查。核心包括优先长期健康、最小化设计表面、清晰命名、单一职责及规范错误处理。
实现新功能时参考编码标准 进行代码重构以优化结构 审查代码质量与可读性
skills/coding-principles/SKILL.md
npx skills add shinpr/claude-code-workflows --skill coding-principles -g -y
SKILL.md
Frontmatter
{
    "name": "coding-principles",
    "description": "Language-agnostic coding principles for maintainability, readability, and quality. Use when implementing features, refactoring code, or reviewing code quality."
}

Language-Agnostic Coding Principles

Core Philosophy

  1. Maintainability over Speed: Prioritize long-term code health over initial development velocity
  2. Simplicity First: Choose the simplest solution that meets requirements (YAGNI principle)
  3. Minimum Surface for Required Coverage: When introducing maintenance-surface-bearing elements (persistent state, public-contract or cross-boundary fields/props, behavioral modes/flags/variants, reusable abstractions, or component splits), select the smallest design surface that covers the current user-visible requirements and accepted technical constraints (audit, data integrity, compatibility, security, performance, accessibility). Adoption is justified by naming a current requirement or constraint that smaller alternatives fail to cover; value-based arguments serve as tiebreakers. Distinct from YAGNI (time-axis judgment of present vs. future need), this principle governs surface-area minimization at a fixed coverage point.
  4. Explicit over Implicit: Make intentions clear through code structure and naming
  5. Delete over Comment: Remove unused code instead of commenting it out

Code Quality

Continuous Improvement

  • Refactor related code within each change set — address style, naming, or structure issues in the files being modified
  • Improve code structure incrementally
  • Keep the codebase lean and focused
  • Delete unused code immediately

Readability

  • Use meaningful, descriptive names drawn from the problem domain
  • Use full words in names; abbreviations are acceptable only when widely recognized in the domain
  • Use descriptive names; single-letter names are acceptable only for loop counters or well-known conventions (i, j, x, y)
  • Extract magic numbers and strings into named constants
  • Keep code self-documenting where possible

Function Design

Parameter Management

  • Recommended: 0-2 parameters per function
  • For 3+ parameters: Use objects, structs, or dictionaries to group related parameters
  • Example (conceptual):
    // Instead of: createUser(name, email, age, city, country)
    // Use: createUser(userData)
    

Single Responsibility

  • Each function should do one thing well
  • Keep functions small and focused (typically < 50 lines)
  • Extract complex logic into separate, well-named functions
  • Functions should have a single level of abstraction

Function Organization

  • Pure functions when possible (no side effects)
  • Separate data transformation from side effects
  • Use early returns to reduce nesting
  • Keep nesting to a maximum of 3 levels; use early returns or extracted functions to flatten deeper nesting

Error Handling

Error Management Principles

  • Always handle errors: Log with context or propagate explicitly
  • Log appropriately: Include context for debugging
  • Protect sensitive data: Mask or exclude passwords, tokens, PII from logs
  • Fail fast: Detect and report errors as early as possible

Error Propagation

  • Use language-appropriate error handling mechanisms
  • Propagate errors to appropriate handling levels
  • Provide meaningful error messages
  • Include error context when re-throwing

Dependency Management

Loose Coupling via Parameterized Dependencies

  • Inject external dependencies as parameters (constructor injection for classes, function parameters for procedural/functional code)
  • Depend on abstractions, not concrete implementations
  • Minimize inter-module dependencies
  • Facilitate testing through mockable dependencies

Reference Representativeness

Verifying References Before Adoption

When adopting patterns, APIs, or dependencies from existing code:

  • IF referencing only 2-3 nearby files → THEN confirm the pattern is representative by checking usage across the repository before adopting
  • IF multiple approaches coexist in the repository → THEN identify the majority pattern and make a deliberate choice — selecting whichever is nearest is insufficient
  • IF adopting an external dependency (library, plugin, SDK) → THEN verify repository-wide usage distribution for the same dependency; if the appropriate version cannot be determined from repository state alone, escalate
  • IF following an existing pattern → THEN state the reason for following it when an alternative exists (e.g., consistency with surrounding code, avoiding breaking changes, pending coordinated update)

Principle

Nearby code is a starting point for investigation, not a sufficient basis for adoption. Verify that what you reference is representative of the repository's conventions and current best practices before using it as a model.

Performance Considerations

Optimization Approach

  • Measure first: Profile before optimizing
  • Focus on algorithms: Algorithmic complexity > micro-optimizations
  • Use appropriate data structures: Choose based on access patterns
  • Resource management: Handle memory, connections, and files properly

When to Optimize

  • After identifying actual bottlenecks through profiling
  • When performance issues are measurable
  • Optimize only after measurable bottlenecks are identified, not during initial development

Code Organization

Structural Principles

  • Group related functionality: Keep related code together
  • Separate concerns: Domain logic, data access, presentation
  • Consistent naming: Follow project conventions
  • Module cohesion: High cohesion within modules, low coupling between

File Organization

  • One primary responsibility per file
  • Logical grouping of related functions/classes
  • Clear folder structure reflecting architecture
  • Avoid "god files" (files > 500 lines)

Commenting Principles

Default: code first

Names, types, and structure are the primary medium. A comment earns its place only by carrying information the code itself cannot express. When in doubt, improve the name instead of adding a comment.

The test for every comment

A comment is justified only if it answers one of these:

  • Why: reasoning, trade-off, or constraint behind a non-obvious decision
  • Limitation / edge case: a boundary a reader cannot infer from the code
  • Public API contract: behavior, inputs, outputs of an exported interface

One comment per decision. If a comment restates what the names and control flow already show, delete it and rename instead.

Comment Scope

  • Comment the why, limits, and public contracts (per the test above); let names and structure carry everything else, including the "how"
  • Record historical context in version control commit messages, not in comments
  • Delete commented-out code (retrieve from git history when needed)

Comment Quality

  • Write comments that remain accurate regardless of future code changes; avoid references to dates, versions, or temporary state
  • Update comments when changing code
  • Use proper grammar and formatting
  • Write for future maintainers

Refactoring Approach

Safe Refactoring

  • Small steps: Make one change at a time
  • Maintain working state: Keep tests passing
  • Verify behavior: Run tests after each change
  • Incremental improvement: Don't aim for perfection immediately

Refactoring Triggers

  • Code duplication (DRY principle)
  • Functions > 50 lines
  • Complex conditional logic
  • Unclear naming or structure

Testing Considerations

Testability

  • Write testable code from the start
  • Avoid hidden dependencies
  • Keep side effects explicit
  • Design for parameterized dependencies

Test-Driven Development

  • Write tests before implementation when appropriate
  • Keep tests simple and focused
  • Test behavior, not implementation
  • Maintain test quality equal to production code

Security Principles

Secure Defaults

  • Store credentials and secrets through environment variables or dedicated secret managers
  • Use parameterized queries (prepared statements) for all database access
  • Use established cryptographic libraries provided by the language or framework
  • Generate security-critical values (tokens, IDs, nonces) with cryptographically secure random generators
  • Encrypt sensitive data at rest and in transit using standard protocols

Input and Output Boundaries

  • Validate all external input at system entry points for expected format, type, and length
  • Encode output appropriately for its rendering context (HTML, SQL, shell, URL)
  • Return only information necessary for the caller in error responses; log detailed diagnostics server-side

Access Control

  • Apply authentication to all entry points that handle user data or trigger state changes
  • Verify authorization for each resource access, not only at the entry point
  • Grant only the permissions required for the operation (files, database connections, API scopes)

Knowledge Cutoff Supplement (2026-03)

  • OWASP Top 10:2025 shifted from symptoms to root causes; added "Software Supply Chain Failures" (A03) and "Mishandling of Exceptional Conditions" (A10)
  • Recent research indicates AI-generated code shows elevated rates of access control gaps — treat authentication and authorization as high-priority review targets
  • OpenSSF published "Security-Focused Guide for AI Code Assistant Instructions" — recommends language-specific, actionable constraints over generic advice
  • For detailed detection patterns, see references/security-checks.md

Documentation

Code Documentation

  • Document public APIs and interfaces
  • Include usage examples for complex functionality
  • Maintain README files for modules
  • Update documentation in the same commit that changes the corresponding behavior

Architecture Documentation

  • Document high-level design decisions
  • Explain integration points
  • Clarify data flows and boundaries
  • Record trade-offs and alternatives considered

Version Control Practices

Commit Practices

  • Make atomic, focused commits
  • Write clear, descriptive commit messages
  • Commit working code (passes tests)
  • Commit only production-ready code; store secrets in environment variables or secret managers

Code Review Readiness

  • Self-review before requesting review
  • Keep changes focused and reviewable
  • Provide context in pull request descriptions
  • Respond to feedback constructively

Language-Specific Adaptations

While these principles are language-agnostic, adapt them to your specific programming language:

  • Static typing: Use strong types when available
  • Dynamic typing: Add runtime validation
  • OOP languages: Apply SOLID principles
  • Functional languages: Prefer pure functions and immutability
  • Concurrency: Follow language-specific patterns for thread safety
提供PRD、ADR、设计文档等模板及创建标准。根据功能类型和代码规模决定所需文档,明确ADR触发条件(如架构变更),指导技术文档的生成与审查流程。
创建或审查技术文档 确定项目所需的文档类型 评估是否需要进行架构决策记录
skills/documentation-criteria/SKILL.md
npx skills add shinpr/claude-code-workflows --skill documentation-criteria -g -y
SKILL.md
Frontmatter
{
    "name": "documentation-criteria",
    "description": "Documentation creation criteria including PRD, ADR, Design Doc, and Work Plan requirements with templates. Use when creating or reviewing technical documents, or determining which documents are required."
}

Documentation Creation Criteria

Templates

Creation Decision Matrix

Condition Required Documents Creation Order
New Feature Addition (backend) PRD → [ADR] → Design Doc → Work Plan After PRD approval
New Feature Addition (frontend/fullstack) PRD → UI Spec → [ADR] → Design Doc → Work Plan UI Spec before Design Doc
ADR Conditions Met (see below) ADR → Design Doc → Work Plan Start immediately
6+ Files [ADR if conditions apply] → Design Doc → Work Plan (Design Doc + Work Plan required) Start immediately
3-5 Files Design Doc → Work Plan (Required) Start immediately
1-2 Files None Direct implementation

ADR Creation Conditions (Required if Any Apply)

1. Contract System Changes

  • Adding nested contracts with 3+ levels: Contract A { Contract B { Contract C { field: T } } }
    • Rationale: Deep nesting has high complexity and wide impact scope
  • Changing/deleting contracts used in 3+ locations
    • Rationale: Multiple location impacts require careful consideration
  • Contract responsibility changes (e.g., DTO→Entity, Request→Domain)
    • Rationale: Conceptual model changes affect design philosophy

2. Data Flow Changes

  • Storage location changes (DB→File, Memory→Cache)
  • Processing order changes with 3+ steps
    • Example: "Input→Validation→Save" to "Input→Save→Async Validation"
  • Data passing method changes (parameter passing→shared state, direct reference→event-based communication)

3. Architecture Changes

  • Layer addition, responsibility changes, component relocation

4. External Dependency Changes

  • Library/framework/external API introduction or replacement

5. Complex Implementation Logic (Regardless of Scale)

  • Managing 3+ states
  • Coordinating 5+ asynchronous processes

Detailed Document Definitions

PRD (Product Requirements Document)

Purpose: Define business requirements and user value

Includes:

  • Business requirements and user value
  • Success metrics and KPIs (each metric specifies a numeric target and measurement method)
  • User stories and use cases
  • MoSCoW prioritization (Must/Should/Could/Won't)
  • Acceptance criteria with sequential IDs (AC-001, AC-002, ...) for downstream traceability
  • MVP and Future phase separation
  • User journey diagram (required)
  • Scope boundary diagram (required)

Scope: Business requirements, user value, success metrics, user stories, and prioritization only. Implementation details belong in Design Doc, technical selection rationale in ADR, phases and task breakdown in Work Plan.

ADR (Architecture Decision Record)

Purpose: Record technical decision rationale and background

Includes:

  • Decision (what was selected)
  • Rationale (why that selection was made)
  • Option comparison (minimum 3 options) and trade-offs
  • Architecture impact
  • Principled implementation guidelines (e.g., "Use dependency injection")

Scope: Decision, rationale, option comparison, architecture impact, and principled guidelines only. Implementation procedures and code examples belong in Design Doc, schedule and resource assignments in Work Plan.

UI Specification

Purpose: Define UI structure, screen transitions, component decomposition, and interaction design for frontend features

Includes:

  • Screen list and transition conditions
  • Component decomposition with state x display matrix (default/loading/empty/error/partial)
  • Interaction definitions linked to PRD acceptance criteria (EARS format)
  • Prototype management (code-based prototypes as attachments, not source of truth)
  • AC traceability from PRD to screens/components
  • Existing component reuse map and design tokens
  • Visual acceptance criteria (golden states, layout constraints)
  • Accessibility requirements (keyboard, screen reader, contrast)

Scope: Screen structure, transitions, component decomposition, interaction design, and visual acceptance criteria only. Technical implementation and API contracts belong in Design Doc, test implementation in test skeleton generation output, schedule in Work Plan.

Required Structural Elements:

  • At least one component with state x display matrix and interaction table
  • AC traceability table mapping PRD ACs to screens/states
  • Screen list with transition conditions
  • Existing component reuse map (reuse/extend/new decisions)

Prototype Code Handling:

  • Prototype code provided by user is placed in docs/ui-spec/assets/{feature-name}/
  • Prototype is an attachment to UI Spec, never the source of truth
  • UI Spec + Design Doc are the canonical specifications

Design Document

Purpose: Define technical implementation methods in detail

Includes:

  • Existing codebase analysis (required)
    • Implementation path mapping (both existing and new)
    • Integration point clarification (connection points with existing code even for new implementations)
  • Technical implementation approach (vertical/horizontal/hybrid)
  • Technical dependencies and implementation constraints (required implementation order)
  • Interface and contract definitions
  • Data flow and component design
  • Acceptance criteria (each criterion specifies a verifiable condition with pass/fail threshold)
  • Change impact map (clearly specify direct impact/indirect impact/no ripple effect)
  • Complete enumeration of integration points
  • Data contract clarification
  • Agreement checklist (agreements with stakeholders)
  • Code inspection evidence (inspected files/functions during investigation)
  • Field propagation map (when fields cross component boundaries)
  • Data representation decision (when introducing new structures)
  • Applicable standards (explicit/implicit classification)
  • Prerequisite ADRs (including common ADRs)
  • Verification Strategy (required)
    • Correctness proof method (what "correct" means for this change, how it's verified, when)
    • Early verification point (first target to prove the approach works, success criteria, failure response)

Required Structural Elements:

Change Impact Map:
  Change Target: [Component/Feature]
  Direct Impact: [Files/Functions]
  Indirect Impact: [Data format/Processing time]
  No Ripple Effect: [Unaffected features]

Interface Change Matrix:
  Existing: [Function/method/operation name]
  New: [Function/method/operation name]
  Conversion Required: [Yes/No]
  Compatibility Method: [Approach]

Scope: Technical implementation methods, interfaces, data flow, acceptance criteria, and verification strategy only. Technology selection rationale belongs in ADR, schedule and assignments in Work Plan.

Work Plan

Purpose: Implementation task management and progress tracking

Includes:

  • Task breakdown and dependencies (maximum 2 levels)
  • Schedule and duration estimates
  • Include test skeleton file paths produced for this work plan (integration and E2E)
  • Verification Strategy summary (extracted from Design Doc)
  • Final Quality Assurance Phase (required)
  • Progress records (checkbox format)

Scope: Task breakdown, dependencies, schedule, verification strategy summary, and progress tracking only. Technical rationale belongs in ADR, design details in Design Doc.

Phase Division Criteria (adapt to implementation approach from Design Doc):

When Vertical Slice selected:

  • Each phase = one value unit (feature, component, or migration target)
  • Each phase includes its own implementation + verification per Verification Strategy

When Horizontal Slice selected:

  1. Phase 1: Foundation Implementation - Contract definitions, interfaces/signatures, test preparation
  2. Phase 2: Core Feature Implementation - Business logic, unit tests
  3. Phase 3: Integration Implementation - External connections, presentation layer

When Hybrid selected:

  • Combine vertical and horizontal as defined in Design Doc implementation approach

All approaches: Final phase is always Quality Assurance (acceptance criteria achievement, all tests passing, quality checks). Each phase's verification method follows Verification Strategy from Design Doc.

Three Elements of Task Completion Definition:

  1. Implementation Complete: Code is functional
  2. Quality Complete: Tests, static checks, linting pass
  3. Integration Complete: Verified connection with other components

Creation Process

  1. Problem Analysis: Change scale assessment, ADR condition check
    • Identify explicit and implicit project standards before investigation
  2. ADR Option Consideration (ADR only): Compare 3+ options, specify trade-offs
  3. Creation: Use templates, include measurable conditions
  4. Approval: "Accepted" after review enables implementation

Storage Locations

Document Path Naming Convention Template
PRD docs/prd/ [feature-name]-prd.md prd-template.md
ADR docs/adr/ ADR-[4-digits]-[title].md adr-template.md
UI Spec docs/ui-spec/ [feature-name]-ui-spec.md ui-spec-template.md
UI Spec Assets docs/ui-spec/assets/{feature-name}/ Prototype code files -
Design Doc docs/design/ [feature-name]-design.md design-template.md
Work Plan docs/plans/ YYYYMMDD-{type}-{description}.md plan-template.md
Task File docs/plans/tasks/ {plan-name}-task-{number}.md task-template.md

*Note: Work plans are excluded by .gitignore

ADR Status

ProposedAcceptedDeprecated/Superseded/Rejected

AI Automation Rules

  • 6+ files: Suggest ADR creation
  • Contract/data flow change detected: ADR mandatory
  • Check existing ADRs before implementation

Diagram Requirements

Required diagrams for each document (using mermaid notation):

Document Required Diagrams Purpose
PRD User journey diagram, Scope boundary diagram Clarify user experience and scope
ADR Option comparison diagram (when needed) Visualize trade-offs
UI Spec Screen transition diagram, Component tree diagram Clarify screen flow and component structure
Design Doc Architecture diagram, Data flow diagram Understand technical structure
Work Plan Phase structure diagram, Task dependency diagram Clarify implementation order

Common ADR Relationships

  1. At creation: Identify common technical areas (logging, error handling, async processing, etc.), reference existing common ADRs
  2. When missing: Consider creating necessary common ADRs
  3. Design Doc: Specify common ADRs in "Prerequisite ADRs" section
  4. Compliance check: Verify design aligns with common ADR decisions
捕获并持久化外部资源(如设计稿、API、IaC)的访问方式,供下游工作确定性引用。通过两级存储和听音协议管理元数据,避免重复询问用户。
工作依赖外部资源 提及设计源、设计系统、API Schema、IaC或密钥库
skills/external-resource-context/SKILL.md
npx skills add shinpr/claude-code-workflows --skill external-resource-context -g -y
SKILL.md
Frontmatter
{
    "name": "external-resource-context",
    "description": "Captures and persists access methods for resources outside the repository (design source, design system, API schema, IaC source, secret store) so downstream work can reach them deterministically. Use when work depends on external resources, or when the user mentions design source, design system, API schema, IaC source, secret store, or canonical source."
}

External Resource Context

Purpose

AI agents understand the codebase but not the external resources surrounding it. This skill captures, in a deterministic location, the access methods to resources outside the repository so downstream work (design, planning, implementation, review) can reach them without re-asking the user.

Resources covered: design origin (where the canonical visual specification lives), design system (component library and tokens), guidelines (usage docs, accessibility rules), visual verification environment (how to confirm rendering), database schema source, migration history, secret store location, API schema source (OpenAPI / proto / GraphQL SDL), mock environment, IaC source, environment configuration.

Scope Boundaries

In scope: hearing protocol, storage location, single-source-of-truth ownership rule, reference protocol for downstream consumers.

Out of scope: enforcing that captured resources are correct or current — verification belongs to the agent that consumes the resource. Generating the resources themselves (e.g., creating a DESIGN.md from scratch).

Storage Locations (Two-Tier)

Tier Location Holds Update Frequency
Project docs/project-context/external-resources.md Environment-stable facts: which resources exist for this project and how to access them (URL, MCP name, file path, command) Rare — only when the project's environment changes
Feature ## External Resources Used section inside the relevant UI Spec or Design Doc The subset of project-tier resources actually used by this feature, plus feature-specific identifiers (e.g., a specific node id within the design tool, a specific endpoint path) Per feature

Single Source of Truth Rule

The project tier owns environment facts. Feature-tier sections list only feature-specific identifiers (node id within the design source, specific endpoint path within the API, specific IaC module name) and reference project-tier entries by label; URLs, MCP names, and access commands remain in the project-tier file. When the environment changes, only the project-tier file is updated.

Example feature-tier entry uses the table format defined in references/template.md: a row with the project-tier label in the first column and the feature-specific identifier in the second column.

Hearing Protocol

When to Hear

Condition Action
docs/project-context/external-resources.md does not exist Run full hearing for the relevant domain(s)
File exists Ask the user via AskUserQuestion: "Update external-resources.md? (no / yes-full / yes-diff-only)". On yes-full run full hearing. On yes-diff-only ask the user which axes changed, hear only those. On no skip hearing

Domain Routing

Load the domain reference matching the current task:

Task type References to load
Frontend (UI work) references/frontend.md
Backend (server / data work) references/backend.md
API contract work references/api.md
Infrastructure / deployment references/infra.md
Fullstack All of the above; per-axis "Not applicable" answers are expected

Each domain reference defines the axes and the question template.

Two-Phase Hearing

  1. Structured hearing — for each axis defined in the domain reference, present the user with AskUserQuestion using the choices listed there (always include "Not applicable" as an option). For each non-N/A axis, follow up with an access-method question (URL / MCP name / file path / command).

  2. Self-declaration — after the structured axes, present a single AskUserQuestion: "Are there any other external resources for this work that the structured questions did not cover? If yes, describe them in your next message." If the user describes additional resources, append them to the storage file under an "Additional resources" subsection.

The two phases are sequential. Self-declaration runs even if the user answered "Not applicable" to every structured axis.

Storage Protocol

After hearing completes:

  1. Build the project-tier content from the answers. Use references/template.md as the structure.
  2. Write to docs/project-context/external-resources.md. Create the directory if absent.
  3. When the calling workflow has a target UI Spec or Design Doc, also append or update the document's ## External Resources Used section with the feature-tier subset (label references + feature-specific identifiers only).
  4. Report the file paths back to the calling workflow.

Reference Protocol (For Downstream Consumers)

Agents that load this skill consult resources in this order:

  1. Read docs/project-context/external-resources.md first (if present) to learn what is available and how to access it.
  2. Read the target UI Spec or Design Doc's ## External Resources Used section for feature-specific identifiers.
  3. Use the access method declared in the project tier (e.g., the named MCP, the URL, the file path) to fetch the actual resource content.

Agents that only need to consult the saved file as input data (not actively hear) can read it directly without loading this skill — frontmatter declaration is reserved for agents that may need to trigger hearing or interpret the protocol semantics.

Output Format

The project-tier file follows the structure in references/template.md. The project-tier file's heading levels and section names are fixed so downstream agents can locate sections deterministically.

For feature-tier sections inside UI Spec or Design Doc, the heading text "External Resources Used" is fixed; the heading level matches the parent document's natural structure (h2 in UI Spec where it is a sibling of other top-level sections, h3 in Design Doc where it sits under Background and Context).

Quality Checklist

  • Each axis answered has both a presence indicator and an access method, or is marked "Not applicable"
  • Self-declaration phase ran even when all structured axes were "Not applicable"
  • Project-tier file does not contain feature-specific identifiers
  • Feature-tier sections reference project-tier entries by label, not by duplicating URLs / MCP names
  • When the project file already existed, the update decision (no / yes-full / yes-diff-only) was confirmed before any write

References

前端AI开发指南,提供技术决策标准、反模式识别(如代码重复、职责混乱)、降级设计原则及Rule of Three复用准则,用于指导前端技术选型与质量保证。
进行前端技术架构决策时 执行前端代码质量审查时 发现疑似反模式的代码实现时 评估是否需要提取公共逻辑时
skills/frontend-ai-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill frontend-ai-guide -g -y
SKILL.md
Frontmatter
{
    "name": "frontend-ai-guide",
    "description": "Frontend-specific technical decision criteria, anti-patterns, debugging techniques, and quality check workflow. Use when making frontend technical decisions or performing quality assurance."
}

AI Developer Guide - Technical Decision Criteria and Anti-pattern Collection (Frontend)

Technical Anti-patterns (Red Flag Patterns)

Immediately stop and reconsider design when detecting the following patterns:

Code Quality Anti-patterns

  1. Writing similar code 3 or more times - Violates Rule of Three
  2. Multiple responsibilities mixed in a single component - Violates Single Responsibility Principle (SRP)
  3. Defining same content in multiple components - Violates DRY principle
  4. Making changes without checking dependencies - Potential for unexpected impacts
  5. Disabling code with comments - Should use version control
  6. Error suppression - Hiding problems creates technical debt
  7. Excessive use of type assertions (as) - Abandoning type safety
  8. Prop drilling through 3+ levels - Should use Context API or state management
  9. Massive components (300+ lines) - Split into smaller components

Design Anti-patterns

  • "Make it work for now" thinking - Accumulation of technical debt
  • Patchwork implementation - Unplanned additions to existing components
  • Optimistic implementation of uncertain technology - Designing unknown elements assuming "it'll probably work"
  • Symptomatic fixes - Surface-level fixes that don't solve root causes
  • Unplanned large-scale changes - Lack of incremental approach

Fallback Design Principles

Core Principle: Fail-Fast

Design philosophy that prioritizes improving primary code reliability over fallback implementations.

Criteria for Fallback Implementation

  • Fallback rule: Implement fallbacks only when explicitly defined in Design Doc
  • Layer Responsibilities:
    • Component Layer: Use Error Boundary for error handling
    • Hook Layer: Implement decisions based on business requirements

Detection of Excessive Fallbacks

  • Require design review when writing the 3rd catch statement in the same feature
  • Verify Design Doc definition before implementing fallbacks
  • Properly log errors and make failures explicit

Rule of Three - Criteria for Code Duplication

How to handle duplicate code based on Martin Fowler's "Refactoring":

Duplication Count Action Reason
1st time Inline implementation Cannot predict future changes
2nd time Consider future consolidation Pattern beginning to emerge
3rd time Implement commonalization Pattern established

Criteria for Commonalization

Cases for Commonalization

  • Business logic duplication
  • Complex processing algorithms
  • Component patterns (form fields, cards, etc.)
  • Custom hooks
  • Validation rules

Cases to Avoid Commonalization

  • Accidental matches (coincidentally same code)
  • Possibility of evolving in different directions
  • Significant readability decrease from commonalization
  • Simple helpers in test code

Implementation Example

// 1st-2nd occurrence: keep separate, no commonalization yet
function UserEmailInput() { /* ... */ }
function ContactEmailInput() { /* ... */ }

// Commonalize on 3rd occurrence
function EmailInput({ context }: { context: 'user' | 'contact' | 'admin' }) { /* ... */ }

Common Failure Patterns and Avoidance Methods

Pattern 1: Error Fix Chain

Symptom: Fixing one error causes new errors Cause: Surface-level fixes without understanding root cause Avoidance: Identify root cause with 5 Whys before fixing

Pattern 2: Abandoning Type Safety

Symptom: Excessive use of any type or as Cause: Impulse to avoid type errors Avoidance: Handle safely with unknown type and type guards

Pattern 3: Implementation Without Sufficient Testing

Symptom: Many bugs after implementation Cause: Ignoring Red-Green-Refactor process Avoidance: Always start with failing tests

Pattern 4: Ignoring Technical Uncertainty

Symptom: Frequent unexpected errors when introducing new technology Cause: Assuming "it should work according to official documentation" without prior investigation Avoidance:

  • Record certainty evaluation at the beginning of task files
    Certainty: low (Reason: new experimental feature with limited production examples)
    Exploratory implementation: true
    Fallback: use established patterns
    
  • For low certainty cases, create minimal verification code first

Pattern 5: Insufficient Existing Code Investigation

Symptom: Duplicate implementations, architecture inconsistency, integration failures Cause: Insufficient understanding of existing code before implementation Avoidance Methods:

  • Before implementation, always search for similar functionality (using domain, responsibility, component patterns as keywords)
  • Similar functionality found → Use that implementation (do not create new implementation)
  • Similar functionality is technical debt → Create ADR improvement proposal before implementation
  • No similar functionality exists → Implement new functionality following existing design philosophy
  • Record all decisions and rationale in "Existing Codebase Analysis" section of Design Doc

Debugging Techniques

1. Error Analysis Procedure

  1. Read error message (first line) accurately
  2. Focus on first and last of stack trace
  3. Identify first line where your code appears
  4. Check React DevTools for component hierarchy

2. 5 Whys - Root Cause Analysis

Symptom: Component not rendering
Why1: Props are undefined → Why2: Parent component didn't pass props
Why3: Parent using old prop names → Why4: Component interface was updated
Why5: No update to parent after refactoring
Root cause: Incomplete refactoring, missing call-site updates

3. Minimal Reproduction Code

To isolate problems, attempt reproduction with minimal code:

  • Remove unrelated components
  • Replace API calls with mocks
  • Create minimal configuration that reproduces problem
  • Use React DevTools to inspect component tree

4. Debug Log Output (temporary)

Add structured debug logs to isolate the issue, then remove them before commit (per "Delete debug console.log()" in typescript-rules):

console.log('DEBUG:', {
  context: 'user-form-submission',
  props: { email, name },
  state: currentState,
  timestamp: new Date().toISOString()
})

Quality Check Workflow

Read package.json scripts and run them with the project's package manager (packageManager field). Map the project's actual script names to the phases below — do not assume fixed names.

Phases (run in order)

  1. Lint/format — the project's formatter + linter (e.g., Biome, or ESLint + Prettier)
  2. Type check — type check without emit
  3. Build — production build
  4. Test — unit/integration tests
  5. Coverage — coverage run when the task added or changed behavior

Troubleshooting

  • Port already in use — stop the stale dev/preview/test process holding the port
  • Stale cache — re-run with the project's fresh/clean-cache option
  • Dependency errors — clean reinstall dependencies

Situations Requiring Technical Decisions

Timing of Abstraction

  • Extract patterns after writing concrete implementation 3 times
  • Be conscious of YAGNI, implement only currently needed features
  • Prioritize current simplicity over future extensibility

Performance vs Readability

  • Prioritize readability unless React DevTools Profiler identifies a measurable bottleneck (e.g., render time exceeding 16ms, unnecessary re-renders)
  • Measure before optimizing with React DevTools Profiler
  • Document reason with comments when optimizing

Granularity of Component/Type Definitions

  • Overly detailed components/types reduce maintainability
  • Design components that appropriately express UI patterns
  • Use composition over inheritance

Implementation Completeness Assurance

Required Procedure for Impact Analysis

Completion Criteria: Complete all 3 stages

1. Discovery

Grep -n "ComponentName\|hookName" -o content
Grep -n "importedFunction" -o content
Grep -n "propsType\|StateType" -o content

2. Understanding

Mandatory: Read all discovered files and include necessary parts in context:

  • Caller's purpose and context
  • Component hierarchy
  • Data flow: Props → State → Event handlers → Callbacks

3. Identification

Structured impact report (mandatory):

## Impact Analysis
### Direct Impact: ComponentA, ComponentB (with reasons)
### Indirect Impact: FeatureX, PageY (with integration paths)
### Processing Flow: Props → Render → Events → Callbacks

Important: Execute all 3 stages to completion

Unused Code Deletion Rule

When unused code is detected → Will it be used?

  • Yes → Implement immediately (no deferral allowed)
  • No → Delete immediately (remains in Git history)

Target: Components, hooks, utilities, documentation, configuration files

Existing Code Deletion Decision Flow

In use? No → Delete immediately (remains in Git history)
       Yes → Working? No → Delete + Reimplement
                     Yes → Fix
用于规划实施策略、选择开发方法及定义验证标准的元认知框架。涵盖现状分析、策略探索(如绞杀者模式)、风险评估及约束验证,旨在通过创造性思维制定最优技术方案。
规划实施策略 选择开发方法 定义验证标准
skills/implementation-approach/SKILL.md
npx skills add shinpr/claude-code-workflows --skill implementation-approach -g -y
SKILL.md
Frontmatter
{
    "name": "implementation-approach",
    "description": "Implementation strategy selection framework. Use when planning implementation strategy, selecting development approach, or defining verification criteria."
}

Implementation Strategy Selection Framework (Meta-cognitive Approach)

Meta-cognitive Strategy Selection Process

Phase 1: Comprehensive Current State Analysis

Core Question: "What does the existing implementation look like?"

Analysis Framework

Architecture Analysis: Responsibility separation, data flow, dependencies, technical debt
Implementation Quality Assessment: Code quality, test coverage, performance, security
Historical Context Understanding: Current form rationale, past decision validity, constraint changes, requirement evolution

Meta-cognitive Question List

  • What is the true responsibility of this implementation?
  • Which parts are business essence and which derive from technical constraints?
  • What dependencies or implicit preconditions are unclear from the code?
  • What benefits and constraints does the current design bring?

Phase 2: Strategy Exploration and Creation

Core Question: "When determining before → after, what implementation patterns or strategies should be referenced?"

Strategy Discovery Process

Research and Exploration: Tech stack examples (WebSearch), similar projects, OSS references, literature/blogs
Creative Thinking: Strategy combinations, constraint-based design, phase division, extension point design

Reference Strategy Patterns (Creative Combinations Encouraged)

Legacy Handling Strategies:

  • Strangler Pattern: Gradual migration through phased replacement
  • Facade Pattern: Complexity hiding through unified interface
  • Adapter Pattern: Bridge with existing systems

New Development Strategies:

  • Feature-driven Development: Vertical implementation prioritizing user value
  • Foundation-driven Development: Foundation-first construction prioritizing stability
  • Risk-driven Development: Prioritize addressing maximum risk elements

Integration/Migration Strategies:

  • Proxy Pattern: Transparent feature extension
  • Decorator Pattern: Phased enhancement of existing features
  • Bridge Pattern: Flexibility through abstraction

Important: The optimal solution is discovered through creative thinking according to each project's context.

Phase 3: Risk Assessment and Control

Core Question: "What risks arise when applying this to existing implementation, and what's the best way to control them?"

Risk Analysis Matrix

Technical Risks: System impact, data consistency, performance degradation, integration complexity
Operational Risks: Service availability, deployment downtime, process changes, rollback procedures
Project Risks: Schedule delays, learning costs, quality achievement, team coordination

Risk Control Strategies

Preventive Measures: Phased migration, parallel operation verification, integration/regression tests, monitoring setup
Incident Response: Rollback procedures, log/metrics preparation, communication system, service continuation procedures

Phase 4: Constraint Compatibility Verification

Core Question: "What are this project's constraints?"

Constraint Checklist

Technical Constraints: Library compatibility, resource capacity, mandatory requirements, numerical targets
Temporal Constraints: Deadlines/priorities, dependencies, milestones, learning periods
Resource Constraints: Team/skills, work hours/systems, budget, external contracts
Business Constraints: Market launch timing, customer impact, regulatory compliance

Phase 5: Implementation Approach Decision

Select optimal solution from basic implementation approaches (creative combinations encouraged):

Vertical Slice (Feature-driven)

Characteristics: Vertical implementation across all layers by feature unit Application Conditions: Features share fewer than 2 data models, each feature is independently deliverable, changes touch 3+ architecture layers Verification Method: End-user value delivery at each feature completion

Horizontal Slice (Foundation-driven)

Characteristics: Phased construction by architecture layer Application Conditions: 3+ features depend on a common foundation layer, foundation changes require stability verification before consumers can proceed Verification Method: Integrated operation verification when all foundation layers complete

Hybrid (Creative Combination)

Characteristics: Flexible combination according to project characteristics Application Conditions: Unclear requirements, need to change approach per phase, transition from prototyping to full implementation Verification Method: Verify at appropriate L1/L2/L3 levels according to each phase's goals

Phase 6: Decision Rationale Documentation

Design Doc Documentation: Record in the Design Doc's implementation approach section:

  1. Selected strategy name and characteristics
  2. Alternatives considered and reason for rejection
  3. Risk mitigation plan (from Phase 3)
  4. Constraint compliance summary (from Phase 4)
  5. Verification level (L1/L2/L3) and integration point definition

Verification Level Definitions

Priority for completion verification of each task:

  • L1: Functional Operation Verification - Operates as end-user feature (e.g., search executable)
  • L2: Test Operation Verification - New tests added and passing
  • L3: Build Success Verification - Code builds/runs without errors

Priority: L1 > L2 > L3 in order of verifiability importance

Integration Point Definitions

Define integration points according to selected strategy:

  • Strangler-based: When switching between old and new systems for each feature
  • Feature-driven: When users can actually use the feature
  • Foundation-driven: When all architecture layers are ready and E2E tests pass
  • Hybrid: When individual goals defined for each phase are achieved

Quality Checks

  1. Verify at least one strategy combination beyond listed patterns was considered
  2. Confirm Phase 1 analysis framework is complete before selecting strategy
  3. Confirm Phase 3 risk analysis matrix is populated before implementation starts
  4. Confirm Phase 4 constraint checklist is reviewed before strategy decision
  5. Confirm Phase 6 documentation template is filled with selection rationale

Guidelines for Meta-cognitive Execution

  1. Leverage Known Patterns: Use as starting point, explore creative combinations
  2. Active WebSearch Use: Research implementation examples from similar tech stacks
  3. Apply 5 Whys: Pursue root causes to grasp essence
  4. Multi-perspective Evaluation: Comprehensively evaluate from each Phase 1-4 perspective
提供集成与E2E测试的设计原则、ROI计算模型及骨架规范。涵盖测试类型定义、行为优先原则及审查标准,用于指导测试设计、预算分配和质量评审。
设计集成测试或E2E测试方案 评估测试用例的ROI优先级 审查现有测试代码的质量与规范性
skills/integration-e2e-testing/SKILL.md
npx skills add shinpr/claude-code-workflows --skill integration-e2e-testing -g -y
SKILL.md
Frontmatter
{
    "name": "integration-e2e-testing",
    "description": "Integration and E2E test design principles, ROI calculation, test skeleton specification, and review criteria. Use when designing integration tests, E2E tests, or reviewing test quality."
}

Integration and E2E Testing Principles

References

E2E test design: See references/e2e-design.md for UI Spec-driven E2E test candidate selection and browser test architecture. The reference uses Playwright as the default browser harness; substitute the project's standard when different.

Test Type Definition and Limits

Test Type Purpose Scope External Deps Limit per Feature Implementation Timing
Integration Verify component interactions in-process Partial system integration (in-process modules; for UI components, the framework's in-process renderer e.g., RTL+MSW for React/TS) Mocked or in-process MAX 3 Created alongside implementation
fixture-e2e Verify UI behavior in a browser with deterministic fixtures Full UI flow with mocked backend / fixture-driven state Mocked / fixture only — no live services MAX 3 Created alongside the UI feature
service-integration-e2e Verify critical user journeys against a running local stack Full system across services Live local services or stubs MAX 1-2 Executed only in the final phase

Lane selection (E2E only):

  • Default lane for user-facing UI journeys is fixture-e2e — it runs a real browser against deterministic fixtures, catches the bugs that unit/integration tests miss (button no-op, state never updates, navigation breaks), and runs in CI without infrastructure setup
  • Add service-integration-e2e only when the journey's correctness depends on real cross-service behavior (data persistence, transactional consistency, external service contracts) that cannot be faked safely

The two E2E lanes are budgeted independently — having a fixture-e2e for a journey does not consume the service-integration-e2e budget and vice versa.

Behavior-First Principle

Include (High ROI)

  • Business logic correctness (calculations, state transitions, data transformations)
  • Data integrity and persistence behavior
  • User-visible functionality completeness
  • Error handling behavior (what user sees/experiences)

Redirect to Other Test Types

  • External service connections → Verify via contract/interface tests
  • Performance metrics → Verify via dedicated load testing
  • Implementation details → Verify observable behavior instead
  • UI layout specifics → Verify information availability instead

Principle: Test = User-observable behavior verifiable in isolated CI environment

ROI Calculation

ROI is used to rank candidates within the same test type (integration candidates against each other, E2E candidates against each other). Cross-type comparison is unnecessary because integration and E2E budgets are selected independently.

ROI Score = Business Value × User Frequency + Legal Requirement × 10 + Defect Detection
              (range: 0–120)

Higher ROI Score = higher priority within its test type. No normalization or capping is applied — the raw score is used directly for ranking. Deduplication is a separate step that removes candidates entirely; it does not modify scores.

ROI Thresholds by Lane

The two E2E lanes have very different ownership costs and use independent thresholds.

Lane ROI threshold Rationale
fixture-e2e ROI ≥ 20 (beyond reserved slot) Cost is comparable to integration tests once the harness exists; the floor avoids filling MAX 3 with low-signal tests when fewer would suffice
service-integration-e2e ROI > 50 (beyond reserved slot) Creation, execution, and maintenance cost is 3-10× higher than integration; reserve for journeys whose value cannot be proven any other way

Reserved slot rules (see Multi-Step User Journey Definition below) apply per lane and override the threshold (the reserved candidate is emitted regardless of its ROI score). Below-floor candidates beyond the reserved slot are not emitted, leaving budget intentionally unfilled rather than padding with low-value tests.

ROI Calculation Examples

Scenario BV Freq Legal Defect ROI Score Test Type Selection Outcome
Core checkout UI flow 10 9 true 9 109 fixture-e2e Selected (reserved slot: user-facing multi-step journey, browser-level verification with fixtures)
Core checkout against live payment service 10 9 true 9 109 service-integration-e2e Selected (real-service correctness above ROI threshold)
Dismiss button updates UI state 6 7 false 8 50 fixture-e2e Selected (rank 2 of 3 fixture-e2e budget)
Payment error message display 5 4 false 7 27 fixture-e2e Selected (rank 3 of 3 fixture-e2e budget)
Optional filter toggle 3 4 false 2 14 fixture-e2e Not selected (rank 4, budget full)
Payment retry against real provider 8 3 false 7 31 service-integration-e2e Below ROI threshold (31 < 50), not selected
DB persistence check 8 8 false 8 72 Integration Selected (rank 1 of 3)
Pure data transformation 5 3 false 4 19 Integration Selected (rank 2 of 3)

Multi-Step User Journey Definition

A feature qualifies as containing a multi-step user journey when ALL of the following are true:

  1. 2+ distinct interaction boundaries are traversed in sequence to complete a user goal. What counts as a boundary depends on the system type:
    • Web: distinct routes/pages
    • Mobile native: distinct screens/views
    • CLI: distinct command invocations or interactive prompts
    • API: distinct API calls forming a transaction (e.g., create → confirm → finalize)
  2. State carries across steps — data produced or actions taken in one step affect what the next step accepts or displays
  3. The journey has a completion point — a final state the user or caller reaches (e.g., confirmation page, saved record, API success response, completed workflow)

User-Facing vs Service-Internal Journeys

Multi-step journeys are classified for reserved-slot eligibility:

Classification Condition Reserved Slot Eligibility Example
User-facing A human user directly triggers and observes the steps (via UI, CLI, or direct API interaction) Eligible — defaults to fixture-e2e reserved slot. Add a service-integration-e2e reserved slot only when the journey's correctness depends on real cross-service behavior Web checkout flow, CLI setup wizard, mobile onboarding
Service-internal Steps are triggered by backend services without direct user interaction Not eligible for reserved slot — use integration tests. Service-integration-e2e through normal ROI > 50 path is still valid when full-system verification is warranted Async job pipeline, service-to-service saga, scheduled batch processing

This classification applies only to the reserved-slot rule and the E2E Gap Check. Other selection follows lane-specific ROI rules above.

Use this definition when evaluating E2E test candidates and E2E gap detection.

Test Skeleton Specification

Required Comment Patterns

Each test MUST include the following annotations:

AC: [Original acceptance criteria text]
Behavior: [Trigger] → [Process] → [Observable Result]
@category: core-functionality | integration | edge-case | fixture-e2e | service-integration-e2e
@lane: integration | fixture-e2e | service-integration-e2e
@dependency: none | [component names] | full-system
@complexity: low | medium | high
ROI: [score]

@lane selection rule:

  • integration — Component interaction in-process, no browser (e.g., RTL+MSW for React/TS, in-process module/handler integration in any language)
  • fixture-e2e — Browser-level UI verification with mocked backend / fixture-driven state
  • service-integration-e2e — Browser-level or end-to-end verification against running local services or stubs

Use the project's comment syntax to wrap these annotations (e.g., // for C-family, # for Python/Ruby/Shell).

Verification Items (Optional)

When verification points need explicit enumeration:

Verification items:
- [Item 1]
- [Item 2]

EARS Format Mapping

EARS Keyword Test Type Generation Approach
When Event-driven Trigger event → verify outcome
While State condition Setup state → verify behavior
If-then Branch coverage Both condition paths verified
(none) Basic functionality Direct invocation → verify result

Test File Naming Convention

  • Integration tests: *.int.test.* or *.integration.test.*
  • fixture-e2e tests: *.fixture.e2e.test.* (or organize under tests/e2e/fixture/)
  • service-integration-e2e tests: *.service.e2e.test.* (or organize under tests/e2e/service/)

The test runner or framework in the project determines the appropriate file extension. Repos that already use a single *.e2e.test.* convention may keep it as long as each file declares @lane: in its header — the lane annotation is the source of truth for routing and budget accounting.

Review Criteria

Skeleton and Implementation Consistency

Check Failure Condition
Behavior Verification No assertion for "observable result" in the implemented test
Verification Item Coverage Listed items not all covered by assertions
Mock Boundary Internal components mocked in integration test

Implementation Quality

Check Failure Condition
AAA Structure Arrange/Act/Assert separation unclear
Independence State sharing between tests, order dependency
Reproducibility Date/random dependency, varying results
Readability Test name doesn't match verification content

Quality Standards

Required

  • Each test verifies one behavior
  • Clear AAA (Arrange-Act-Assert) structure
  • No test interdependencies
  • Deterministic execution
规范LLM友好型上下文编写,通过明确指令、具体化模糊词、定义输出结构及分解步骤,确保下游智能体无需猜测即可执行。适用于提示词优化、任务交接及规划文档生成。
编写或修订面向LLM的提示词 创建任务交接说明 生成规划工件或报告 优化下游执行指令
skills/llm-friendly-context/SKILL.md
npx skills add shinpr/claude-code-workflows --skill llm-friendly-context -g -y
SKILL.md
Frontmatter
{
    "name": "llm-friendly-context",
    "description": "Clarifies inputs, outputs, success criteria, decisions, and unresolved conditions so downstream agents can execute without guessing. Use when writing or revising LLM-facing prompts, handoffs, planning artifacts, reviews, reports, or generated instructions."
}

LLM-Friendly Context

The goal is stable downstream execution: the next agent should know what to read, what to do, what counts as success, and when to stop or escalate.

Core Rules

  1. Use positive, executable instructions

    • State what the next agent should do.
    • Convert quality policies into positive criteria.
    • Example: "Preserve existing public API behavior across the documented compatibility cases."
  2. Make vague instructions concrete

    • Replace subjective terms with observable conditions, paths, commands, schemas, examples, or decision rules.
    • Terms that often need clarification when they leave a decision to the next agent: appropriate, proper, related, existing behavior, optional, as needed, if needed, per convention, unresolved alternatives, TBD, placeholder.
  3. Specify output shape

    • Define required sections, fields, table columns, JSON keys, or checklist items.
    • For handoffs, include paths to produced artifacts and the exact status fields the caller must inspect.
  4. Provide necessary context

    • Include the purpose, source artifacts, hard constraints, accepted decisions, and unresolved conditions.
    • Prefer concrete file paths and section hints over broad module names.
  5. Decompose complex work into verifiable steps

    • Split work with 3+ objectives or sequential dependencies into ordered steps.
    • Each step needs a checkpoint: what evidence proves it is complete.
  6. Permit uncertainty explicitly

    • If the source material is missing, contradictory, or not verifiable, state the uncertainty and the required escalation.
    • Record unknown business, product, security, or compatibility decisions as blocking unresolved items with the input needed to resolve them.
  7. Keep constraints proportionate

    • Add only constraints that reduce ambiguity or preserve a real requirement.
    • Keep simple downstream tasks lightweight when the target action, context, and success criteria are already clear.

Rewrite Patterns

Use these rewrites before treating a prompt, handoff, or artifact as complete.

Ambiguous form Rewrite as
optional used as an unresolved choice Required, omitted, or required only under a named condition
Multiple alternatives that the next agent must choose between The selected option, or a deterministic decision rule
as needed / if needed The triggering condition and required action
per convention The file, function, test, or documented convention to follow
related files Specific paths, globs, or search hints
existing behavior The observable behavior, source file, test, API response, or UI state to preserve
placeholder Exact temporary value/behavior, allowed dependencies, and verification expectation
TBD used as a placeholder for required information A blocking unresolved item with owner, required input, or escalation condition
appropriate / proper A measurable criterion or checklist

Handoff Checklist

Before sending a prompt or artifact to another agent, verify:

  • The target action is explicit.
  • Required input paths and source artifacts are named.
  • Accepted decisions and constraints are stated once, without alternate wording.
  • Output format or expected status fields are specified.
  • Success criteria are observable.
  • Ambiguous expressions have been rewritten or marked as unresolved.
  • The next agent can complete its scope with explicit choices, decision rules, or blocking unresolved items.

Generated Artifact Checklist

Before writing or finalizing a generated document:

  • Each requirement, claim, task, test skeleton, or review finding has enough source context to trace why it exists.
  • Every executable instruction names the target, action, and expected result.
  • Verification steps say what to run or observe and what result proves success.
  • If an artifact is derived from another artifact, copied decisions stay consistent in wording and meaning.
  • If downstream work is blocked by missing information, the artifact records the missing input and escalation condition.
根据设计文档为现有代码库添加集成和E2E测试。通过编排器协调发现文档、生成骨架、创建任务文件,并委派子代理执行实现与审查,确保测试质量。
需要为现有后端或前端代码添加集成测试 需要为现有系统添加端到端测试
skills/recipe-add-integration-tests/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-add-integration-tests -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-add-integration-tests",
    "description": "Add integration\/E2E tests to existing codebase using Design Docs",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Test addition workflow for existing implementations (backend, frontend, or fullstack)

Orchestrator Definition

Core Identity: "I am an orchestrator."

First Action: Register Steps 0-8 using TaskCreate before any execution.

Why Delegate: Orchestrator's context is shared across all steps. Direct implementation consumes context needed for review and quality check phases. Task files create context boundaries. Subagents work in isolated context.

Execution Method:

  • Skeleton generation → delegate to acceptance-test-generator
  • Task file creation → orchestrator creates directly (minimal context usage)
  • Test implementation → delegate to task-executor
  • Test review → delegate to integration-test-reviewer
  • Quality checks → delegate to quality-fixer

Document paths: $ARGUMENTS

Prerequisites

  • At least one Design Doc must exist (created manually or via reverse-engineer)
  • Existing implementation to test

Execution Flow

Step 0: Execute Skill

Execute Skill: documentation-criteria (for task file template in Step 3)

Step 1: Discover and Validate Documents

# Verify at least one document path was provided
test -n "$ARGUMENTS" || { echo "ERROR: No document paths provided"; exit 1; }

# Verify provided paths exist
ls $ARGUMENTS

# Discover additional documents
ls docs/design/*.md 2>/dev/null | grep -v template
ls docs/ui-spec/*.md 2>/dev/null

Classify discovered documents by filename:

  • Filename contains backendDesign Doc (backend)
  • Filename contains frontendDesign Doc (frontend)
  • Located in docs/ui-spec/UI Spec (optional)
  • None of the above → treat as single-layer Design Doc

Step 2: Skeleton Generation

Invoke acceptance-test-generator using Agent tool:

  • subagent_type: "dev-workflows:acceptance-test-generator"
  • description: "Generate test skeletons"
  • prompt: List only the documents that exist from Step 1:
    Generate test skeletons from the following documents:
    - Design Doc (backend): [path]    ← include only if exists
    - Design Doc (frontend): [path]   ← include only if exists
    - UI Spec: [path]                 ← include only if exists
    

Expected output: generatedFiles containing integration and e2e paths

Step 3: Create Task Files [GATE]

Create one task file per layer, using the monorepo-flow.md naming convention for deterministic agent routing:

  • Backend skeletons exist → docs/plans/tasks/integration-tests-backend-task-YYYYMMDD.md
  • Frontend skeletons exist → docs/plans/tasks/integration-tests-frontend-task-YYYYMMDD.md
  • Single-layer (no backend/frontend distinction) → docs/plans/tasks/integration-tests-backend-task-YYYYMMDD.md

Template (per task file):

---
name: Implement [layer] integration tests for [feature name]
type: test-implementation
---

## Objective

Implement test cases defined in skeleton files.

## Target Files

- Skeleton: [layer-specific paths from Step 2 generatedFiles]
- Design Doc: [layer-specific Design Doc from Step 1]

## Tasks

- [ ] Implement each test case in skeleton
- [ ] Verify all tests pass
- [ ] Ensure coverage meets requirements

## Acceptance Criteria

- All skeleton test cases implemented
- All tests passing
- quality-fixer reports approved

Output: "Task file(s) created at [path(s)]. Ready for Step 4."

Step 4: Test Implementation

For each task file from Step 3, invoke task-executor routed by filename pattern (per monorepo-flow.md):

  • *-backend-task-*subagent_type: "dev-workflows:task-executor"
  • *-frontend-task-*subagent_type: "dev-workflows-frontend:task-executor-frontend"
  • description: "Implement integration tests"
  • prompt: "Task file: [task file path from Step 3]. Implement tests following the task file."

Execute one task file at a time through Steps 4→5→6→7 before starting the next.

Expected output: status, testsAdded

Step 5: Test Review

Invoke integration-test-reviewer using Agent tool:

  • subagent_type: "dev-workflows:integration-test-reviewer"
  • description: "Review test quality"
  • prompt: "Review test quality. Test files: [paths from Step 4 testsAdded]. Skeleton files: [layer-specific paths from Step 2 generatedFiles matching current task's layer]"

Expected output: status (approved/needs_revision), requiredFixes

Step 6: Apply Review Fixes

Check Step 5 result:

  • status: approved → Mark complete, proceed to Step 7
  • status: needs_revision → Invoke task-executor with requiredFixes, then return to Step 5

Invoke task-executor routed by task filename pattern:

  • *-backend-task-*subagent_type: "dev-workflows:task-executor"
  • *-frontend-task-*subagent_type: "dev-workflows-frontend:task-executor-frontend"
  • description: "Fix review findings"
  • prompt: "Fix the following issues in test files: [requiredFixes from Step 5]"

Step 7: Quality Check

Invoke quality-fixer routed by task filename pattern:

  • *-backend-task-*subagent_type: "dev-workflows:quality-fixer"
  • *-frontend-task-*subagent_type: "dev-workflows-frontend:quality-fixer-frontend"
  • description: "Final quality assurance"
  • prompt: "Final quality assurance for test files added in this workflow. Run all tests and verify coverage."

Expected output: status (approved/stub_detected/blocked)

Check quality-fixer response:

  • stub_detected → Return to Step 4 with incompleteImplementations[] details, then re-execute Steps 4→5→6→7
  • blocked → Escalate to user
  • approved → Proceed to Step 8

Step 8: Commit

On approved from quality-fixer:

  • Commit test files using Bash with message format: "test: add [layer] integration tests for [feature name]"

Step 9: Final Cleanup

After all task files have been processed and committed, delete the task files this recipe created. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file matching docs/plans/tasks/integration-tests-backend-task-*.md and docs/plans/tasks/integration-tests-frontend-task-*.md created during this run

If task files cannot be deleted (filesystem error), report the failure but do not block completion.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.
自主执行分解任务的编排技能。通过解析工作计划和任务文件集,遵循四步循环(执行、检查、修复、提交),委托子代理完成开发任务,并在每次提交前运行质量修复器,确保全流程自动化与质量管控。
用户指令使用现有任务文件进行批量审批和自主执行 需要执行已分解的特定计划任务并自动处理交付物
skills/recipe-build/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-build -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-build",
    "description": "Execute decomposed tasks in autonomous execution mode",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Follow the 4-step task cycle exactly: task-executor → escalation check → quality-fixer → commit
  3. Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
  4. Scope: Complete when all tasks are committed or escalation occurs

CRITICAL: Run quality-fixer before every commit.

Work plan: $ARGUMENTS

Pre-execution Prerequisites

Work Plan Resolution

Before any task processing, locate the work plan. Resolution rule:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md. Layer-aware fullstack tasks ({plan-name}-backend-task-*.md / {plan-name}-frontend-task-*.md) are excluded here so a stale fullstack run does not redirect this recipe to the wrong work plan
  2. From the matched files, also exclude every file matching any of these patterns — they originate from other workflow phases and are not implementation tasks for this run's plan: *-task-prep-*.md (readiness preflight tasks), _overview-*.md (decomposition overview file), *-phase*-completion.md (per-phase completion files), review-fixes-*.md (post-implementation review fixes), integration-tests-*-task-*.md (integration-test add-on scaffolding)
  3. For each remaining file, extract the {plan-name} prefix as the segment that appears before -task-
  4. When at least one task file matches, the work plan is docs/plans/{plan-name}.md for the prefix that has the most recent task-file mtime; ties broken by the lexicographically last {plan-name}
  5. When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template .md in docs/plans/

Consumed Task Set

Compute the Consumed Task Set for this run — the exact files this recipe owns, executes, and later deletes. Use the same restricted pattern as Work Plan Resolution:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md for the {plan-name} resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded
  2. Exclude every file matching: *-task-prep-*.md, _overview-*.md, *-phase*-completion.md, review-fixes-*.md, integration-tests-*-task-*.md (these originate from other workflow phases)

Every subsequent reference to "task files" in this recipe — Task Generation Decision Flow, Task Execution Cycle iteration, and Final Cleanup — uses this set, not the unrestricted docs/plans/tasks/*.md glob.

Task Generation Decision Flow

Analyze the Consumed Task Set and determine the action required:

State Criteria Next Action
Tasks exist Consumed Task Set is non-empty User's execution instruction serves as batch approval → Enter autonomous execution immediately
No tasks + plan exists Consumed Task Set is empty but the resolved work plan exists Confirm with user → run task-decomposer
Neither exists + Design Doc exists No plan, no Consumed Task Set, but docs/design/*.md exists Invoke work-planner to create work plan from Design Doc, then run document-reviewer (dev-workflows:document-reviewer, doc_type: WorkPlan); branch on the reviewer's verdict.decision — on needs_revision, re-invoke work-planner (update) and re-review until approved/approved_with_conditions, then present the reviewed plan for batch approval before task decomposition; on rejected, stop before task decomposition and escalate to the user
Neither exists No plan, no Consumed Task Set, no Design Doc Report missing prerequisites to user and stop

Task Decomposition Phase (Conditional)

When the Consumed Task Set is empty:

1. User Confirmation

No task files in the Consumed Task Set.
Work plan: docs/plans/[plan-name].md

Generate tasks from the work plan? (y/n):

2. Task Decomposition (if approved)

Invoke task-decomposer using Agent tool:

  • subagent_type: "dev-workflows:task-decomposer"
  • description: "Decompose work plan"
  • prompt: "Read work plan at docs/plans/[plan-name].md and decompose into atomic tasks. Output: Individual task files in docs/plans/tasks/. Granularity: 1 task = 1 commit = independently executable"

3. Verify Generation

Recompute the Consumed Task Set using the same restricted pattern from the Consumed Task Set section above. Confirm it is now non-empty. If it is still empty, escalate to the user — task-decomposer either failed silently or produced files that don't match the expected pattern.

Flow: Task generation → Consumed Task Set recompute → Autonomous execution (in this order)

Pre-execution Checklist

  • Confirmed Consumed Task Set is non-empty (computed in the Consumed Task Set section above)
  • Identified task execution order within the Consumed Task Set (dependencies)
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Task Execution Cycle (4-Step Cycle)

MANDATORY EXECUTION CYCLE: task-executor → escalation check → quality-fixer → commit

For EACH task in the Consumed Task Set, YOU MUST:

  1. Register tasks using TaskCreate: Register work steps. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON"
  2. Agent tool (subagent_type: "dev-workflows:task-executor") → Pass task file path in prompt, receive structured response
  3. CHECK task-executor response:
    • status: "escalation_needed" or "blocked" → STOP and escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 2 with requiredFixes
      • approved → Proceed to step 4
    • readyForQualityCheck: true → Proceed to step 4
  4. INVOKE quality-fixer: Execute all quality checks and fixes. Always pass the current task file path as task_file
  5. CHECK quality-fixer response:
    • stub_detected → Return to step 2 with incompleteImplementations[] details
    • blocked → STOP and escalate to user
    • approved → Proceed to step 6
  6. COMMIT on approval: Execute git commit

CRITICAL: Parse every sub-agent response for status fields. Execute the matching branch in the 4-step cycle. Proceed to next task only after quality-fixer returns approved.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Verify task files exist per Pre-execution Checklist, then enter autonomous execution mode. When requirement changes are detected during execution, escalate to the user with the change summary before continuing.

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows:code-verifier") → doc_type: design-doc, Design Doc path, code_paths: implementation file list (git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows:security-reviewer") → Design Doc path, implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute task-executor with consolidated fixes → quality-fixer
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file in the Consumed Task Set
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer for this {plan-name})
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Completion Report Contract

Final report must include:

  • Task decomposition status
  • Implemented task count
  • Quality check result
  • Commit count
  • Cleanup result
  • Escalation or blocking summary, if any
作为编排器,通过委托子代理执行代码库分析、范围确认、技术设计、验证及文档审查,最终生成并批准架构决策记录或设计文档。
需要创建技术设计文档时 需要进行架构决策记录(ADR)时
skills/recipe-design/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-design -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-design",
    "description": "Execute from codebase analysis to design document creation",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the design phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results. The one exception is the Step 1 scope bootstrap, a recipe-local orchestrator task limited to locating seed files.
  2. Run the design flow below in order:
    • Execute: scope bootstrap → codebase-analyzer → [Stop: Scope confirmation] → technical-designer → code-verifier → document-reviewer → design-sync
    • code-verifier and design-sync apply when the design output is a Design Doc; both are skipped for ADR-only
    • Stop at every [Stop: ...] marker → Wait for user approval before proceeding
  3. Scope: Complete when design documents receive approval

subagents-orchestration-guide usage: Reference the guide only for orchestration principles (Delegation Boundary, Decision precedence, permitted tools), the Scale Determination table, and handoff contracts HC-02 onward. This recipe defines its own start order and subagent prompts. The guide's requirement-analyzer-origin flow, First Action Rule, HC-01, and Call Examples do not apply to this recipe.

CRITICAL: Execute document-reviewer, design-sync (for Design Docs), and all stopping points — each serves as a quality gate. Skipping any step risks undetected inconsistencies.

Workflow Overview

Requirements → scope bootstrap → codebase-analyzer → [Stop: Scope confirmation]
                                                            ↓
                                                    technical-designer
                                                            ↓
                                                    code-verifier → document-reviewer
                                                            ↓
                                                       design-sync → [Stop: Design approval]

Scope Boundaries

Included in this skill:

  • Scope bootstrap: locating seed files so codebase-analyzer receives a populated input
  • Codebase analysis with codebase-analyzer (entry point of the design phase)
  • Scope confirmation with the user, grounded in codebase-analyzer findings
  • ADR creation (if architecture changes, new technology, or data flow changes)
  • Design Doc creation with technical-designer
  • Design Doc verification with code-verifier (before document review)
  • Document review with document-reviewer
  • Design Doc consistency verification with design-sync

Responsibility Boundary: This skill completes with design document (ADR/Design Doc) approval. Work planning and beyond are outside scope.

Execution Flow

Requirements: $ARGUMENTS

Step 1: Scope Bootstrap

codebase-analyzer requires a populated requirement_analysis.affectedFiles. Build that seed with a lightweight, orchestrator-local pass — locating files only, with no deep reading and no design decisions:

  1. Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
  2. Search the repository with Bash (rg, or grep when rg is unavailable) for files matching those keywords.
  3. Collect the matched file paths as the seed affectedFiles.
  4. When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as affectedFiles before invoking codebase-analyzer. If the user confirms no related code exists, report that codebase-grounded design does not apply and confirm with the user how to proceed.
  5. When the search returns more than ~20 files: the keywords are too broad for a focused design scope. Present the most relevant candidates to the user (AskUserQuestion) and confirm the seed affectedFiles before invoking codebase-analyzer.

This step locates seed files only. Reading files in full, tracing dependencies, and analysis remain codebase-analyzer's responsibility.

Step 2: Codebase Analysis

Invoke codebase-analyzer with its existing schema. The orchestrator constructs requirement_analysis from the Step 1 seed.

  • Invoke codebase-analyzer using Agent tool
    • subagent_type: "dev-workflows:codebase-analyzer", description: "Codebase analysis"
    • prompt: include
      • requirements: the user requirements verbatim
      • requirement_analysis: a JSON object with all four fields — affectedFiles (Step 1 seed), purpose (the user requirements), scale (provisional value from the Scale Determination table applied to the seed file count), technicalConsiderations ({ constraints: [], risks: [], dependencies: [] } — the bootstrap performs no analysis, so the object is present with empty lists)
      • Expected action: analyze the seed files and produce design guidance

Step 3: Scope Confirmation

After codebase-analyzer returns, confirm the design scope with the user before any design work. This is a recipe-local confirmation step. Use AskUserQuestion.

Present, sourced from the codebase-analyzer JSON:

  • Target files/modules: analysisScope.filesAnalyzed and the modules they belong to
  • Affected layers: layers touched, derived from analysisScope.categoriesDetected and focusAreas
  • Unknowns/assumptions: limitations plus any assumptions codebase-analyzer recorded
  • Questions before design: open points that need a user answer before design proceeds

Ask the user to choose one:

  • Proceed to design with this scope — continue to Step 4 (Design Doc)
  • Correct the scope and re-run — return to Step 1 with the corrected scope; when the user names the corrected files or modules, use those directly as the Step 1 seed instead of re-deriving them by search
  • Hold additional hearing, then proceed — gather the missing answers, then continue to Step 4
  • Produce an ADR — when the confirmed scope involves architecture changes, new technology, or data flow changes, continue to Step 4 with technical-designer in ADR mode

After the user confirms the scope, count the confirmed target files and set the scale from the subagents-orchestration-guide Scale Determination table. This confirmed scale supersedes the Step 2 provisional value and determines the design document.

[STOP]: Wait for the user's choice before proceeding.

Step 4: Design Document Creation

Pass the full codebase-analyzer JSON to technical-designer (handoff contract HC-02). technical-designer presents at least two design alternatives with trade-offs for each.

  • Invoke technical-designer using Agent tool
    • For Design Doc: subagent_type: "dev-workflows:technical-designer", description: "Design Doc creation", prompt: "Create Design Doc based on the requirements. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. Confirmed scope: [Step 3 confirmed scope]. Apply the code: prefix to codebase-analyzer fact_ids when filling the Fact Disposition Table. Present at least two architecture alternatives with trade-offs."
    • For ADR: subagent_type: "dev-workflows:technical-designer", description: "ADR creation", prompt: "Create ADR for [technical decision]. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. Confirmed scope: [Step 3 confirmed scope]. Present at least two alternatives with trade-offs."
  • (Design Doc only) Invoke code-verifier to verify the Design Doc against existing code. Skip for ADR.
    • subagent_type: "dev-workflows:code-verifier", description: "Design Doc verification", prompt: "doc_type: design-doc document_path: [Design Doc path] Verify Design Doc against existing code."
  • Invoke document-reviewer to verify consistency (pass code-verifier results for Design Doc; omit for ADR)
    • subagent_type: "dev-workflows:document-reviewer", description: "Document review", prompt: "Review [document path] for consistency and completeness. codebase_analysis: [codebase-analyzer JSON from Step 2]. code_verification: [code-verifier output from this step] (Design Doc only)"
  • (Design Doc only) Invoke design-sync to verify consistency across design documents. Skip for ADR-only.
    • subagent_type: "dev-workflows:design-sync", description: "Design consistency check", prompt: "Check consistency across all Design Docs in docs/design/. Report conflicts and overlaps."

[STOP]: Present the design document, plus design-sync results for a Design Doc, and obtain user approval.

Completion Criteria

  • Built the Step 1 scope bootstrap seed (or obtained target files from the user when the search returned none)
  • Executed codebase-analyzer with a populated requirement_analysis
  • Confirmed the design scope with the user and set the scale from the confirmed target files
  • Created appropriate design document (ADR or Design Doc) with technical-designer
  • Executed code-verifier on Design Doc and passed results to document-reviewer (skip for ADR-only)
  • Executed document-reviewer and addressed feedback
  • Executed design-sync for consistency verification (skip for ADR-only)
  • Obtained user approval for design document

Output Example

Design phase completed.

  • Design document: docs/design/[document-name].md or docs/adr/[document-name].md
  • Approval status: User approved
该技能用于系统化诊断问题,通过结构化流程协调调查、验证和求解子代理。首先确定问题类型并补充信息,利用规则顾问分析本质,随后迭代执行调查与验证,最终生成解决方案报告,旨在精准定位根因并提供有效对策。
需要排查技术故障或系统错误时 寻求复杂问题的根因分析与解决方案时
skills/recipe-diagnose/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-diagnose -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-diagnose",
    "description": "Investigate problem, verify findings, and derive solutions",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Diagnosis flow to identify root cause and present solutions

Target problem: $ARGUMENTS

Orchestrator Definition

Core Identity: "I am not a worker. I am an orchestrator."

Execution Method:

  • Investigation → performed by investigator
  • Verification → performed by verifier
  • Solution derivation → performed by solver

Orchestrator invokes sub-agents and passes structured JSON between them.

Task Registration: Register execution steps using TaskCreate and proceed systematically. Update status using TaskUpdate.

Step 0: Problem Structuring (Before investigator invocation)

0.1 Problem Type Determination

Type Criteria
Change Failure Indicates some change occurred before the problem appeared
New Discovery No relation to changes is indicated

If uncertain, ask the user whether any changes were made right before the problem occurred.

0.2 Information Supplementation for Change Failures

If the following are unclear, ask with AskUserQuestion before proceeding:

  • What was changed (cause change)
  • What broke (affected area)
  • Relationship between both (shared components, etc.)

0.3 Problem Essence Understanding

Invoke rule-advisor via Agent tool:

subagent_type: rule-advisor
description: "Problem essence analysis"
prompt: Identify the essence and required rules for this problem: [Problem reported by user]

Confirm from rule-advisor output:

  • taskAnalysis.mainFocus: Primary focus of the problem
  • mandatoryChecks.taskEssence: Root problem beyond surface symptoms
  • selectedRules: Applicable rule sections
  • warningPatterns: Patterns to avoid

0.4 Reflecting in investigator Prompt

Include the following in investigator prompt:

  1. Problem essence (taskEssence)
  2. Key applicable rules summary (from selectedRules)
  3. Investigation focus (investigationFocus): Convert warningPatterns to "points prone to confusion or oversight in this investigation"
  4. For change failures, additionally include:
    • Detailed analysis of the change content
    • Commonalities between cause change and affected area
    • Determination of whether the change is a "correct fix" or "new bug" with comparison baseline selection

Diagnosis Flow Overview

Problem → investigator → verifier → solver ─┐
                 ↑                          │
                 └── coverage insufficient ─┘
                      (max 2 iterations)

coverage sufficient → Report

Context Separation: Pass only structured JSON output to each step. Each step starts fresh with the JSON data only.

Execution Steps

Register the following using TaskCreate and execute:

Step 1: Investigation (investigator)

Agent tool invocation:

subagent_type: investigator
description: "Investigate problem"
prompt: |
  Comprehensively collect information related to the following phenomenon.

  Phenomenon: [Problem reported by user]

  Problem essence: [taskEssence from Step 0.3]
  Investigation focus: [investigationFocus from Step 0.4]

  [For change failures, additionally include:]
  Change details: [What was changed]
  Affected area: [What broke]
  Shared components: [Commonalities between cause and effect]

Expected output: pathMap (execution paths per symptom), failurePoints (faults found at each node), impactAnalysis per failure point, unexplored areas, investigation limitations

Step 2: Investigation Quality Check

Review investigation output:

Quality Check (verify JSON output contains the following):

  • pathMap exists with at least one symptom, and each symptom has at least one path with nodes listed
  • Each failure point has: location, upstreamDependency, symptomExplained, causalChain (reaching a stop condition), checkStatus, evidence with a source citing a specific file or location
  • Each failure point has comparisonAnalysis (normalImplementation found or explicitly null)
  • causeCategory for each failure point is one of: typo / logic_error / missing_constraint / design_gap / external_factor
  • investigationSources covers at least 3 distinct source types (code, history, dependency, config, document, external)
  • Investigation covers investigationFocus items (when provided in Step 0.4)
  • All nodes on mapped paths have been checked (no path was abandoned after finding the first fault)

If quality insufficient: Re-run investigator specifying missing items explicitly:

prompt: |
  Re-investigate with focus on the following gaps:
  - Missing: [list specific missing items from quality check]

  Previous investigation results (for context, do not re-investigate covered areas):
  [Previous investigation JSON]

design_gap Escalation:

When investigator output contains causeCategory: design_gap or recurrenceRisk: high:

  1. Insert user confirmation before verifier execution
  2. Use AskUserQuestion: "A design-level issue was detected. How should we proceed?"
    • A: Attempt fix within current design
    • B: Include design reconsideration
  3. If user selects B, pass includeRedesign: true to solver

Proceed to verifier once quality is satisfied.

Step 3: Verification (verifier)

Agent tool invocation:

subagent_type: verifier
description: "Verify investigation results"
prompt: Verify the following investigation results.

Investigation results: [Investigation JSON output]

Expected output: Coverage check (missing paths, unchecked nodes), Devil's Advocate evaluation per failure point, failure point evaluation with checkStatus, coverage assessment

Coverage Criteria:

  • sufficient: Main paths traced, all critical nodes checked, each failure point individually evaluated
  • partial: Main paths traced, some nodes unchecked or some failure points at blocked/not_reached
  • insufficient: Significant paths untraced, or critical nodes not investigated

Step 4: Solution Derivation (solver)

Agent tool invocation:

subagent_type: solver
description: "Derive solutions"
prompt: Derive solutions based on the following verified failure points.

Confirmed failure points: [verifier's conclusion.confirmedFailurePoints]
Refuted failure points: [verifier's conclusion.refutedFailurePoints]
Failure point relationships: [verifier's conclusion.failurePointRelationships]
Impact analysis: [investigator's impactAnalysis]
Coverage assessment: [sufficient/partial/insufficient]

Expected output: Multiple solutions (at least 3), tradeoff analysis, recommendation and implementation steps, residual risks

Completion condition: coverageAssessment=sufficient

When not reached:

  1. Return to Step 1 with unchecked areas identified by verifier as investigation targets
  2. Maximum 2 additional investigation iterations
  3. After 2 iterations without reaching sufficient, present user with options:
    • Continue additional investigation
    • Execute solution at current coverage level

Step 5: Final Report Creation

Prerequisite: coverageAssessment=sufficient achieved

After diagnosis completion, report to user in the following format:

## Diagnosis Result Summary

### Identified Failure Points
[Confirmed failure points from verification results]
- Per failure point: location, symptom explained, finalStatus

### Verification Process
- Path coverage: [Paths traced and nodes checked]
- Additional investigation iterations: [0/1/2]
- Coverage assessment: [sufficient/partial/insufficient]

### Recommended Solution
[Solution derivation recommendation]

Rationale: [Selection rationale]

### Implementation Steps
1. [Step 1]
2. [Step 2]
...

### Alternatives
[Alternative description]

### Residual Risks
[solver's residualRisks]

### Post-Resolution Verification Items
- [Verification item 1]
- [Verification item 2]

Completion Criteria

  • Executed investigator and obtained pathMap, failurePoints, and impactAnalysis
  • Performed investigation quality check and re-ran if insufficient
  • Executed verifier and obtained coverage assessment
  • Executed solver
  • Achieved coverageAssessment=sufficient (or obtained user approval after 2 additional iterations)
  • Presented final report to user
用于在会话中调整已实现的UI,通过与设计源比对进行验证。流程包括资源获取、代码分析、写入集确认、规模判断、执行修改及质量检查,确保端到端完成并符合标准。
需要调整现有UI功能 需根据设计稿验证并修正前端实现
skills/recipe-front-adjust/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-adjust -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-adjust",
    "description": "Adjust an already-implemented UI in-session with verification against the design source",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: UI adjustment on already-implemented features. The verification loop (edit → check against the design source → refine) runs in the parent session.

Execution Pattern

Core Identity: "I am a guided executor. I run the adjustment and the verification loop myself; subagents handle one-shot tasks."

Execution Protocol:

  1. Delegate to subagents (one-shot calls): ui-analyzer, work-planner, quality-fixer-frontend.
  2. Run in the parent session (multi-step loops and user dialogs): external-resource hearing via AskUserQuestion, write-set confirmation, scale judgment, adjustment edits, verification against the design source, iteration until acceptance.
  3. Stop at every [Stop: ...] marker before proceeding.

Initial Mandatory Tasks

Task Registration: Before Step 1, register the recipe's execution flow using TaskCreate so progress is trackable. Register Steps 1-7 below as individual tasks plus a final task "Verify completion against Completion Criteria". Update status using TaskUpdate as each step starts and completes.

Workflow Overview

Adjustment request → external resource hearing (parent session, AskUserQuestion)
                                  ↓
                     ui-analyzer (subagent: fetch external sources + analyze code + propose candidateWriteSet)
                                  ↓
                     write-set confirmation (parent session, AskUserQuestion)
                                  ↓
                     scale judgment on confirmed write set (documentation-criteria matrix)
                                  ↓
            ┌────────────────────┴────────────────────┐
            ↓                                          ↓
   (1-2 files: inline)                  (3-5 files: work-planner subagent → [Stop])
            ↓                                          ↓
            └─→ adjustment + verification (parent session) ←──┘
                                  ↓
                     quality-fixer-frontend (subagent: typecheck/lint/test)
                                  ↓
                     commit

Scope Boundaries

Included in this skill:

  • External resource hearing per the external-resource-context skill
  • UI fact gathering via ui-analyzer
  • Scale judgment via documentation-criteria's Creation Decision Matrix
  • Optional work plan creation via work-planner
  • Adjustment edits and verification against the design source (run in this session)
  • Quality verification via quality-fixer-frontend
  • Commit per adjustment unit

Responsibility Boundary: This skill completes when the adjustment is committed and quality has passed. Adjustment work is end-to-end within this recipe; parent session owns edits, verification loops, quality-result routing, and commits.

Escalation Boundary: Escalate to the full frontend design phase when the request requires PRD, UI Spec, Design Doc, new architecture, multi-screen redesign, or any ADR Creation Condition from documentation-criteria.

Adjustment request: $ARGUMENTS

Execution Flow

Step 1: External Resource Hearing

Run the hearing protocol per the external-resource-context skill (frontend domain).

Step 2: UI Fact Gathering

  • Invoke ui-analyzer using Agent tool
    • subagent_type: "dev-workflows-frontend:ui-analyzer"
    • description: "UI fact gathering for adjustment"
    • prompt: "requirement_analysis: { affectedFiles: [files inferred from the adjustment request], scale: 'small', purpose: 'UI adjustment', technicalConsiderations: [] }. requirements: [adjustment request]. target_components: [components named in the request]. ui_spec_path: [path if an existing UI Spec covers the affected components, else absent]. Read docs/project-context/external-resources.md, fetch external UI sources via the declared access methods, and analyze the existing UI codebase. Populate candidateWriteSet[] with the files most likely to require modification."

Step 3: Scale Judgment

Execute Skill: documentation-criteria (loads the Creation Decision Matrix and ADR Creation Conditions used in this step and in the Escalation Boundary).

  1. Read candidateWriteSet[] from ui-analyzer output.
  2. Present the candidate list to the user via AskUserQuestion: "Confirmed write set for this adjustment? (a) accept high-confidence entries / (b) accept all entries / (c) edit list manually". On c, send a follow-up plain message asking the user to paste the edited file list, then proceed with that list.
  3. Apply the Creation Decision Matrix from the documentation-criteria skill to the confirmed write set count:
    • 0 files: The adjustment request did not map to any existing file. Escalate to the user with the message "No write target identified from the adjustment request. Please clarify which component(s) should change, or run the full frontend design phase if this is a new feature." Stop this recipe.
    • 1-2 files: Direct adjustment, no work plan.
    • 3-5 files: Work plan required.
    • 6+ files OR any ADR Creation Condition triggered (architecture changes, contract changes affecting 3+ locations, complex multi-state logic, etc.): Adjustment scope exceeded. Escalate the user to the full frontend design phase. Stop this recipe.

Step 4: Plan Creation (Conditional)

Branch on the scale outcome.

Branch A — 1-2 files

No work plan. Build a minimal adjustment context for the parent session:

  • Adjustment request (verbatim)
  • ui-analyzer focusAreas[] (raw fact_id; the ui: prefix is only applied when merging with codebase-analysis facts in a Fact Disposition Table, which Branch A does not do)
  • Affected files list
  • External resources fetched_summary and access methods that the verification loop will use

Present the adjustment context to the user for review.

  • [STOP]: User confirms the adjustment context covers the work.

Branch B — 3-5 files

Create a right-sized work plan. Invoke work-planner using Agent tool:

  • subagent_type: "dev-workflows-frontend:work-planner"
  • description: "Adjustment work plan"
  • prompt: "Create a work plan for this UI adjustment. Adjustment request: [verbatim]. ui_analysis: [ui-analyzer JSON]. External resources: docs/project-context/external-resources.md. Scale: 3-5 files (no Design Doc, no ADR). Each phase should be implementable as 1-3 commits. Include a quality checklist matched to the affected components: visual verification, accessibility, i18n parity, generated artifact regeneration when relevant. Output path: docs/plans/[YYYYMMDD]-adjust-[short-description].md."

After work-planner returns:

  • Present the work plan to the user.
  • [STOP]: Wait for plan approval or revision request. If the user requests changes, re-invoke work-planner with revised guidance.

Step 5: Adjustment + Verification (parent session)

For each adjustment unit (per file in Branch A; per work plan phase in Branch B):

  1. Plan the edit based on ui-analyzer focusAreas and the relevant external resource (e.g., design origin's fetched_summary).
  2. Apply the edit using Edit / Write / MultiEdit on the affected files.
  3. Verify against external sources using whichever access method docs/project-context/external-resources.md declares for each axis:
    • Design origin: compare current rendering against the design source via the declared access method (e.g., design-tool MCP, WebFetch from a public URL, file read from a specification path)
    • Visual rendering: capture screenshot or run a smoke check via the declared visual verification method (e.g., browser MCP, E2E test runner CLI invoked via Bash, dev-server URL inspection, Storybook URL)
    • Design system tokens / variants: confirm against the declared design system source (e.g., design-system MCP, package import, Storybook URL, internal documentation path)
  4. Refine and re-verify until the adjustment matches the design source, or matches the user-confirmed adjustment target when no separate design source exists.
  5. When the adjustment unit converges, proceed to Step 6 for that unit.

When the project-tier file declares no automated verification mechanism for an axis, ask the user to confirm the result manually, or use file-based comparison when a specification file is available.

Step 6: Quality Verification (per adjustment unit)

  • Invoke quality-fixer-frontend using Agent tool
    • subagent_type: "dev-workflows-frontend:quality-fixer-frontend"
    • description: "Quality verification for adjustment unit"
    • Build the prompt by branch. Scope is always filesModified; task_file (when passed) is a supplementary hint that quality-fixer-frontend may use to read the document's "Quality Assurance Mechanisms" section.
      • Branch A (1-2 files): omit task_file. Pass filesModified: [list of files edited in this adjustment unit].
      • Branch B (3-5 files): pass task_file: <work plan path> (supplementary hint) AND filesModified: [list of files edited in this adjustment unit] (primary scope).
    • Example (Branch A): prompt: "filesModified: [src/components/Card/Card.tsx, src/components/Card/Card.module.css]. Run quality checks across the listed files."
    • Example (Branch B): prompt: "task_file: docs/plans/[plan-name].md. filesModified: [src/components/Card/Card.tsx, src/components/Card/Card.module.css]. Run quality checks across the listed files."
  • Route the quality-fixer-frontend response by status:
    • approved → proceed to Step 7
    • stub_detected → return to Step 5 to complete the implementation for this unit, then re-invoke quality-fixer-frontend
    • blocked → read reason. When "Cannot determine due to unclear specification", surface blockingIssues[] to the user and stop. When "Execution prerequisites not met", surface missingPrerequisites[] with resolutionSteps to the user and stop

Step 7: Commit (per adjustment unit)

Commit the adjustment unit on quality approval. Include the affected files and any regenerated artifacts (CSS module typings, message catalog typings, etc.) flagged by ui-analyzer's generatedArtifacts section.

Then loop back to Step 5 for the next unit (Branch B work plan phase, or next file in Branch A) until all units are committed.

Completion Criteria

  • External resource hearing executed (project-tier file written or update explicitly skipped)
  • ui-analyzer returned a JSON output, including externalResources fetch_status per axis and candidateWriteSet
  • Write set confirmed by the user before scale judgment
  • Scale judgment applied to the confirmed write set; 6+ files or ADR conditions escalated to the design phase
  • Branch A: adjustment context presented and confirmed; Branch B: work plan approved
  • All adjustment units edited and verified using the project's declared verification mechanism (manual confirmation when no automated mechanism is declared)
  • Each adjustment unit passed quality-fixer-frontend with explicit filesModified scoping
  • Each adjustment unit committed

Output Example

Frontend adjustment completed.
- External resources: docs/project-context/external-resources.md (updated|unchanged)
- UI fact gathering: ui-analyzer focused on [N] components, [M] focus areas, external sources [fetched|partial|not_recorded]
- Scale: <1-2 files | 3-5 files>
- Work plan: <path | not required>
- Adjustment units committed: [count]
- Quality status: all passed
前端构建编排技能,用于自主执行前端实现。通过解析任务文件确定工作计划,严格遵循4步循环(执行、升级检查、质量修复、提交),在每次提交前强制运行质量修复器,确保任务批量批准与完成。
用户提供包含现有任务文件的执行指令 需要自主执行前端实现任务
skills/recipe-front-build/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-build -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-build",
    "description": "Execute frontend implementation in autonomous execution mode",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Follow the 4-step task cycle exactly: task-executor-frontend → escalation check → quality-fixer-frontend → commit
  3. Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
  4. Scope: Complete when all tasks are committed or escalation occurs

CRITICAL: Run quality-fixer-frontend before every commit.

Work plan: $ARGUMENTS

Pre-execution Prerequisites

Work Plan Resolution

Before any task processing, locate the work plan. Resolution rule:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md. Layer-aware fullstack tasks ({plan-name}-backend-task-*.md / {plan-name}-frontend-task-*.md) are excluded here so a stale fullstack run does not redirect this recipe to the wrong work plan
  2. From the matched files, also exclude every file matching any of these patterns — they originate from other workflow phases and are not implementation tasks for this run's plan: *-task-prep-*.md (readiness preflight tasks), _overview-*.md (decomposition overview file), *-phase*-completion.md (per-phase completion files), review-fixes-*.md (post-implementation review fixes), integration-tests-*-task-*.md (integration-test add-on scaffolding)
  3. For each remaining file, extract the {plan-name} prefix as the segment that appears before -task-
  4. When at least one task file matches, the work plan is docs/plans/{plan-name}.md for the prefix that has the most recent task-file mtime; ties broken by the lexicographically last {plan-name}
  5. When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template .md in docs/plans/

Consumed Task Set

Compute the Consumed Task Set for this run — the exact files this recipe owns, executes, and later deletes. Use the same restricted pattern as Work Plan Resolution:

  1. List task files in docs/plans/tasks/ matching the single-layer pattern {plan-name}-task-*.md for the {plan-name} resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded
  2. Exclude every file matching: *-task-prep-*.md, _overview-*.md, *-phase*-completion.md, review-fixes-*.md, integration-tests-*-task-*.md (these originate from other workflow phases)

Every subsequent reference to "task files" in this recipe — Task Generation Decision Flow, Task Execution Cycle iteration, and Final Cleanup — uses this set, not the unrestricted docs/plans/tasks/*.md glob.

Task Generation Decision Flow

Analyze the Consumed Task Set and determine the action required:

State Criteria Next Action
Tasks exist Consumed Task Set is non-empty User's execution instruction serves as batch approval → Enter autonomous execution immediately
No tasks + plan exists Consumed Task Set is empty but the resolved work plan exists Confirm with user → run task-decomposer
Neither exists + Design Doc exists No plan, no Consumed Task Set, but docs/design/*.md exists Invoke work-planner to create work plan from Design Doc, then run document-reviewer (dev-workflows-frontend:document-reviewer, doc_type: WorkPlan); branch on the reviewer's verdict.decision — on needs_revision, re-invoke work-planner (update) and re-review until approved/approved_with_conditions, then present the reviewed plan for batch approval before task decomposition; on rejected, stop before task decomposition and escalate to the user
Neither exists No plan, no Consumed Task Set, no Design Doc Report missing prerequisites to user and stop

Task Decomposition Phase (Conditional)

When the Consumed Task Set is empty:

1. User Confirmation

No task files in the Consumed Task Set.
Work plan: docs/plans/[plan-name].md

Generate tasks from the work plan? (y/n):

2. Task Decomposition (if approved)

Invoke task-decomposer using Agent tool:

  • subagent_type: "dev-workflows-frontend:task-decomposer"
  • description: "Decompose work plan"
  • prompt: "Read work plan at docs/plans/[plan-name].md and decompose into atomic tasks. Output: Individual task files in docs/plans/tasks/. Granularity: 1 task = 1 commit = independently executable"

3. Verify Generation

Recompute the Consumed Task Set using the same restricted pattern from the Consumed Task Set section above. Confirm it is now non-empty. If it is still empty, escalate to the user — task-decomposer either failed silently or produced files that don't match the expected pattern.

Flow: Task generation → Consumed Task Set recompute → Autonomous execution (in this order)

Pre-execution Checklist

  • Confirmed Consumed Task Set is non-empty (computed in the Consumed Task Set section above)
  • Identified task execution order within the Consumed Task Set (dependencies)
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Task Execution Cycle (4-Step Cycle)

MANDATORY EXECUTION CYCLE: task-executor-frontend → escalation check → quality-fixer-frontend → commit

For EACH task in the Consumed Task Set, YOU MUST:

  1. Register tasks using TaskCreate: Register work steps. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON"
  2. Agent tool (subagent_type: "dev-workflows-frontend:task-executor-frontend") → Pass task file path in prompt, receive structured response
  3. CHECK task-executor-frontend response:
    • status: "escalation_needed" or "blocked" → STOP and escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 2 with requiredFixes
      • approved → Proceed to step 4
    • readyForQualityCheck: true → Proceed to step 4
  4. INVOKE quality-fixer-frontend: Execute all quality checks and fixes. Always pass the current task file path as task_file
  5. CHECK quality-fixer-frontend response:
    • stub_detected → Return to step 2 with incompleteImplementations[] details
    • blocked → STOP and escalate to user
    • approved → Proceed to step 6
  6. COMMIT on approval: Execute git commit

CRITICAL: Parse every sub-agent response for status fields. Execute the matching branch in the 4-step cycle. Proceed to next task only after quality-fixer-frontend returns approved.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Verify task files exist per Pre-execution Checklist, then enter autonomous execution mode. When requirement changes are detected during execution, escalate to the user with the change summary before continuing.

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows-frontend:code-verifier") → doc_type: design-doc, Design Doc path, code_paths: implementation file list (git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows-frontend:security-reviewer") → Design Doc path, implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute task-executor-frontend with consolidated fixes → quality-fixer-frontend
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file in the Consumed Task Set
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer for this {plan-name})
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Completion Report Contract

Final report must include:

  • Task decomposition status
  • Implemented task count
  • Quality check result
  • Commit count
  • Cleanup result
  • Escalation or blocking summary, if any
前端设计编排技能,通过协调多个子代理完成从代码库分析到前端设计文档生成的全流程。包含范围引导、UI分析与设计、技术设计、代码验证及文档审查等步骤,并在关键节点暂停等待用户确认以确保质量。
需要生成前端设计文档 进行前端架构与技术设计
skills/recipe-front-design/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-design -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-design",
    "description": "Execute from codebase analysis to frontend design document creation",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the frontend design phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results. The one exception is the Step 1 scope bootstrap, a recipe-local orchestrator task limited to locating seed files.
  2. Run the frontend design flow below in order (this recipe covers medium/large frontend):
    • Execute: scope bootstrap → codebase-analyzer → [Stop: Scope confirmation] → external resource hearing → ui-analyzer → ui-spec-designer → technical-designer-frontend → code-verifier → document-reviewer → design-sync
    • ui-spec-designer, code-verifier, and design-sync apply when the design output is a Design Doc; all are skipped for ADR-only
    • Stop at every [Stop: ...] marker → Wait for user approval before proceeding
  3. Scope: Complete when design documents receive approval

subagents-orchestration-guide usage: Reference the guide only for orchestration principles (Delegation Boundary, Decision precedence, permitted tools), the Scale Determination table, and handoff contracts HC-02 onward. This recipe defines its own start order and subagent prompts. The guide's requirement-analyzer-origin flow, First Action Rule, HC-01, and Call Examples do not apply to this recipe.

CRITICAL: Execute document-reviewer, design-sync (for Design Docs), and all stopping points — each serves as a quality gate. Skipping any step risks undetected inconsistencies.

Workflow Overview

Requirements → scope bootstrap → codebase-analyzer → [Stop: Scope confirmation]
                                                            ↓
                                          external resource hearing (frontend domain)
                                                            ↓
                                                       ui-analyzer
                                                            ↓
                                              ui-spec-designer → [Stop: UI Spec approval]
                                                            ↓
                                              technical-designer-frontend
                                                            ↓
                                              code-verifier → document-reviewer
                                                            ↓
                                                 design-sync → [Stop: Design approval]

Scope Boundaries

Included in this skill:

  • Scope bootstrap: locating seed files so codebase-analyzer receives a populated input
  • Codebase analysis with codebase-analyzer (entry point of the frontend design phase)
  • Scope confirmation with the user, grounded in codebase-analyzer findings
  • External resource hearing per the external-resource-context skill
  • UI fact gathering with ui-analyzer
  • UI Specification creation with ui-spec-designer (prototype code inquiry included)
  • ADR creation (if architecture changes, new technology, or data flow changes)
  • Design Doc creation with technical-designer-frontend
  • Design Doc verification with code-verifier (before document review)
  • Document review with document-reviewer
  • Design Doc consistency verification with design-sync

Responsibility Boundary: This skill completes with frontend design document (UI Spec/ADR/Design Doc) approval. Work planning and beyond are outside scope.

Execution Flow

Requirements: $ARGUMENTS

Step 1: Scope Bootstrap

codebase-analyzer requires a populated requirement_analysis.affectedFiles. Build that seed with a lightweight, orchestrator-local pass — locating files only, with no deep reading and no design decisions:

  1. Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
  2. Search the repository with Bash (rg, or grep when rg is unavailable) for files matching those keywords.
  3. Collect the matched file paths as the seed affectedFiles.
  4. When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as affectedFiles before invoking codebase-analyzer. If the user confirms no related code exists, report that codebase-grounded design does not apply and confirm with the user how to proceed.
  5. When the search returns more than ~20 files: the keywords are too broad for a focused design scope. Present the most relevant candidates to the user (AskUserQuestion) and confirm the seed affectedFiles before invoking codebase-analyzer.

This step locates seed files only. Reading files in full, tracing dependencies, and analysis remain codebase-analyzer's responsibility.

Step 2: Codebase Analysis

Invoke codebase-analyzer with its existing schema. The orchestrator constructs requirement_analysis from the Step 1 seed.

  • Invoke codebase-analyzer using Agent tool
    • subagent_type: "dev-workflows-frontend:codebase-analyzer", description: "Codebase analysis"
    • prompt: include
      • requirements: the user requirements verbatim
      • requirement_analysis: a JSON object with all four fields — affectedFiles (Step 1 seed), purpose (the user requirements), scale (provisional value from the Scale Determination table applied to the seed file count), technicalConsiderations ({ constraints: [], risks: [], dependencies: [] } — the bootstrap performs no analysis, so the object is present with empty lists)
      • Expected action: analyze the seed files for frontend design guidance (data, contracts, dependencies, quality assurance mechanisms)

Step 3: Scope Confirmation

After codebase-analyzer returns, confirm the design scope with the user before any design work. This is a recipe-local confirmation step. Use AskUserQuestion.

Present, sourced from the codebase-analyzer JSON:

  • Target files/modules: analysisScope.filesAnalyzed and the modules they belong to
  • Affected layers: layers touched, derived from analysisScope.categoriesDetected and focusAreas
  • Unknowns/assumptions: limitations plus any assumptions codebase-analyzer recorded
  • Questions before design: open points that need a user answer before design proceeds

Ask the user to choose one:

  • Proceed to design with this scope — continue to Step 4
  • Correct the scope and re-run — return to Step 1 with the corrected scope; when the user names the corrected files or modules, use those directly as the Step 1 seed instead of re-deriving them by search
  • Hold additional hearing, then proceed — gather the missing answers, then continue to Step 4
  • Produce an ADR — when the confirmed scope involves architecture changes, new technology, or data flow changes, continue through the flow with an ADR as the design document; Step 6 (UI Specification) is skipped for ADR

After the user confirms the scope, count the confirmed target files and set the scale from the subagents-orchestration-guide Scale Determination table. This confirmed scale supersedes the Step 2 provisional value and determines the design document.

[STOP]: Wait for the user's choice before proceeding.

Step 4: External Resource Hearing

Run the hearing protocol per the external-resource-context skill (frontend domain). The orchestrator owns this step because it requires AskUserQuestion. The skill defines file-existence branching, two-phase hearing (structured axes + self-declaration), and persistence to docs/project-context/external-resources.md.

Step 5: UI Fact Gathering

Invoke ui-analyzer to gather UI facts. It reads the project-tier external-resources file, fetches external UI sources via the inherited MCP/URL access methods, then analyzes the UI codebase. Its output complements the codebase-analyzer output from Step 2 (data, contracts, dependencies, quality assurance mechanisms).

  • Invoke ui-analyzer using Agent tool
    • subagent_type: "dev-workflows-frontend:ui-analyzer", description: "UI fact gathering"
    • prompt: include
      • requirements: the user requirements
      • requirement_analysis: a JSON object with all four fields — affectedFiles (analysisScope.filesAnalyzed from Step 2 codebase-analyzer), purpose (the user requirements), scale (the Step 3 confirmed scale), technicalConsiderations ({ constraints: [], risks: [], dependencies: [] })
      • Expected action: read docs/project-context/external-resources.md, fetch external UI sources via the declared access methods, and analyze the existing UI codebase

Both outputs (codebase-analyzer JSON from Step 2 and ui-analyzer JSON from Step 5) are reused by ui-spec-designer in Step 6 and by technical-designer-frontend in Step 7.

Step 6: UI Specification Phase

When the design document is a Design Doc (this step is skipped for ADR-only): after Step 5 output is received, ask the user about prototype code:

Ask the user: "Do you have prototype code for this feature? If so, please provide the path to the code. The prototype will be placed in docs/ui-spec/assets/ as reference material for the UI Spec."

  • [STOP]: Wait for user response about prototype code availability

Then create the UI Specification:

  • Invoke ui-spec-designer using Agent tool
    • subagent_type: "dev-workflows-frontend:ui-spec-designer"
    • description: "UI Spec creation"
    • Build the prompt by including:
      • Source: an existing PRD in docs/prd/ when one exists for this feature; otherwise the user requirements with the Step 2 codebase-analyzer JSON and the Step 3 confirmed scope
      • ui_analysis: ui-analyzer JSON from Step 5 (includes externalResources fetched_summary and componentStructure / propsPatterns / cssLayout / etc.)
      • Prototype path when provided
    • Example (existing PRD): prompt: "Create UI Spec from PRD at [path]. ui_analysis: [JSON from Step 5 ui-analyzer]. Prototype code is at [user-provided path]. Place prototype in docs/ui-spec/assets/{feature-name}/."
    • Example (no PRD): prompt: "Create UI Spec from these requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. Confirmed scope: [Step 3 confirmed scope]. ui_analysis: [JSON from Step 5 ui-analyzer]. Prototype code is at [user-provided path]. Place prototype in docs/ui-spec/assets/{feature-name}/."
  • Invoke document-reviewer to verify UI Spec
    • subagent_type: "dev-workflows-frontend:document-reviewer", description: "UI Spec review", prompt: "doc_type: UISpec target: [ui-spec path] Review for consistency and completeness"
  • [STOP]: Present UI Spec for user approval

Step 7: Design Document Creation Phase

technical-designer-frontend presents at least two architecture alternatives (technology selection, data flow design) with trade-offs for each. Pass the Step 2 codebase-analyzer output and the Step 5 ui-analyzer output:

  • Invoke technical-designer-frontend using Agent tool
    • For ADR: subagent_type: "dev-workflows-frontend:technical-designer-frontend", description: "ADR creation", prompt: "Create ADR for [technical decision]. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. UI analysis: [ui-analyzer JSON from Step 5]. Confirmed scope: [Step 3 confirmed scope]. Present at least two alternatives with trade-offs."
    • For Design Doc: subagent_type: "dev-workflows-frontend:technical-designer-frontend", description: "Design Doc creation", prompt: "Create Design Doc based on the requirements. Requirements: [user requirements verbatim]. Codebase analysis: [codebase-analyzer JSON from Step 2]. UI analysis: [ui-analyzer JSON from Step 5]. UI Spec is at [ui-spec path]. Inherit component structure and state design from UI Spec. Apply code: prefix to codebase-analyzer fact_ids and ui: prefix to ui-analyzer fact_ids when filling the Fact Disposition Table. Present at least two architecture alternatives with trade-offs."
  • (Design Doc only) Invoke code-verifier to verify Design Doc against existing code. Skip for ADR.
    • subagent_type: "dev-workflows-frontend:code-verifier", description: "Design Doc verification", prompt: "doc_type: design-doc document_path: [Design Doc path] Verify Design Doc against existing code."
  • Invoke document-reviewer to verify consistency (pass code-verifier results for Design Doc; omit for ADR)
    • subagent_type: "dev-workflows-frontend:document-reviewer", description: "Document review", prompt: "Review [document path] for consistency and completeness. codebase_analysis: [codebase-analyzer JSON from Step 2]. ui_analysis: [ui-analyzer JSON from Step 5]. code_verification: [code verification output from this step] (Design Doc only)"

Step 8: Design Consistency Verification

  • (Design Doc only) Invoke design-sync using Agent tool. Skip for ADR-only.
    • subagent_type: "dev-workflows-frontend:design-sync", description: "Design consistency check", prompt: "Check consistency across all Design Docs in docs/design/. Report conflicts and overlaps."
  • [STOP]: Present the design document, plus design-sync results for a Design Doc, and obtain user approval

Completion Criteria

  • Built the Step 1 scope bootstrap seed (or obtained target files from the user when the search returned none)
  • Executed codebase-analyzer with a populated requirement_analysis
  • Confirmed the design scope with the user and set the scale from the confirmed target files
  • Executed external resource hearing per the external-resource-context skill (file written or update explicitly skipped by user)
  • Executed ui-analyzer; codebase-analyzer (Step 2) and ui-analyzer (Step 5) outputs reused by ui-spec-designer and technical-designer-frontend
  • Created UI Specification with ui-spec-designer (when applicable) — its External Resources Used section is filled
  • Created appropriate design document (ADR or Design Doc) with technical-designer-frontend — its External Resources Used subsection is filled when present
  • Executed code-verifier on Design Doc and passed results to document-reviewer (skip for ADR-only)
  • Executed document-reviewer and addressed feedback
  • Executed design-sync for consistency verification (skip for ADR-only)
  • Obtained user approval for design document

Output Example

Frontend design phase completed.

  • UI Specification: docs/ui-spec/[feature-name]-ui-spec.md
  • Design document: docs/design/[document-name].md or docs/adr/[document-name].md
  • Approval status: User approved
该技能用于根据设计文档制定前端工作计划。通过委托子代理生成测试骨架和工作计划,经审阅后获取用户批准,完成前端规划阶段任务。
需要根据设计文档创建前端工作计划 请求生成前端工作规划并获取审批
skills/recipe-front-plan/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-plan -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-plan",
    "description": "Create frontend work plan from design document and obtain plan approval",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the frontend planning phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
  2. Follow subagents-orchestration-guide skill planning flow:
    • Execute steps defined below
    • Stop and obtain approval for plan content before completion
  3. Scope: See Scope Boundaries below

CRITICAL: When the user requests test generation, always execute acceptance-test-generator first — it provides the test skeleton that work-planner depends on.

Scope Boundaries

Included in this skill:

  • Design document selection
  • Test skeleton generation with acceptance-test-generator
  • Work plan creation with work-planner
  • Work plan review with document-reviewer
  • Plan approval obtainment

Responsibility Boundary: This skill completes with work plan approval.

Follow the planning process below:

Execution Process

Step 1: Design Document Selection

! ls -la docs/design/*.md | head -10

  • Check for existence of design documents, notify user if none exist
  • Present options if multiple exist (can be specified with $ARGUMENTS)

Step 2: Test Skeleton Generation Confirmation

  • Confirm with user whether to generate test skeletons (integration + fixture-e2e + service-integration-e2e) first
  • If user wants generation: acceptance-test-generator generates skeletons across all applicable lanes
    • Invoke acceptance-test-generator using Agent tool:
      • subagent_type: "dev-workflows-frontend:acceptance-test-generator"
      • description: "Test skeleton generation"
      • If UI Spec exists: prompt: "Generate test skeletons from Design Doc at [path]. UI Spec at [ui-spec path]."
      • If no UI Spec: prompt: "Generate test skeletons from Design Doc at [path]."
  • Pass integration test file path, fixture-e2e and service-integration-e2e file paths (or null per lane), and e2eAbsenceReason (per lane) to work-planner according to subagents-orchestration-guide "acceptance-test-generator → work-planner" section

Step 3: Work Plan Creation

Invoke work-planner using Agent tool:

  • subagent_type: "dev-workflows-frontend:work-planner"

  • description: "Work plan creation"

  • If test skeletons were generated in Step 2, build the prompt by listing every lane's status:

    • Always include: "Integration test file: [path or 'not generated']"
    • For each E2E lane (fixtureE2e, serviceE2e):
      • When generatedFiles.<lane> is not null: "[lane] test file: [path]"
      • When generatedFiles.<lane> is null: "No [lane] skeleton generated (reason: [e2eAbsenceReason.])"
    • Append placement guidance: "Integration tests are created simultaneously with each phase implementation. fixture-e2e tests are created alongside the UI feature phase. service-integration-e2e tests are executed only in the final phase."
  • If test skeletons were not generated: prompt: "Create work plan from Design Doc at [path]."

  • Follow subagents-orchestration-guide Prompt Construction Rule for additional prompt parameters

Step 4: Work Plan Review

Invoke document-reviewer to review the work plan:

  • subagent_type: "dev-workflows-frontend:document-reviewer"
  • description: "Work plan review"
  • prompt: "doc_type: WorkPlan target: docs/plans/[plan-name].md. Review semantic traceability to the Design Doc, early verification placement, real-boundary verification coverage, Failure Mode Checklist, and Review Scope."
  • The work plan is a derivation of the Design Doc, so plan-fidelity findings are resolved without user input. Branch on the reviewer's verdict.decision: on needs_revision, re-invoke work-planner in update mode with the findings and re-review, repeating until approved or approved_with_conditions. On rejected, escalate to the user.

Step 5: Present for Approval

  • Present the reviewed work plan to the user for batch approval. If the user requests changes, re-invoke work-planner with revised parameters and re-run Step 4.
  • Highlight steps with unclear scope or external dependencies and ask the user to confirm

Response at Completion

Recommended: End with the following standard response after plan content approval

Frontend planning phase completed.
- Work plan: docs/plans/[plan-name].md
- Status: Approved

Please provide separate instructions for implementation.
针对React/TypeScript前端实施后的设计文档合规性与安全验证Orchestrator。通过调用代码与安全审查员生成报告,根据结果自动路由至代码修复或设计文档更新路径,确保实现与设计一致且无安全隐患。
需要验证前端代码是否符合设计文档规范 执行前端实施后的质量与安全审计 发现代码与设计文档不一致需决定修复方向
skills/recipe-front-review/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-front-review -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-front-review",
    "description": "Design Doc compliance and security validation with optional auto-fixes",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Post-implementation quality assurance for React/TypeScript frontend

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

First Action: Register Steps 1-11 using TaskCreate before any execution.

Execution Method

  • Compliance validation → performed by code-reviewer
  • Security validation → performed by security-reviewer
  • Code-side fix path: Fix implementation → task-executor-frontend; Quality checks → quality-fixer-frontend; Re-validation → code-reviewer / security-reviewer
  • Design-side update path: DD revision → technical-designer-frontend (update mode); DD review → document-reviewer; cross-DD consistency → design-sync (when multiple DDs exist); Re-validation → code-reviewer

The design-side path applies when the discrepancy reflects code that was correct but the Design Doc became stale, rather than code that violated the Design Doc.

Design Doc (uses most recent if omitted): $ARGUMENTS

Execution Flow

Step 1: Prerequisite Check

# Identify Design Doc
ls docs/design/*.md | grep -v template | tail -1

# Check implementation files
git diff --name-only main...HEAD

Step 2: Execute code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows-frontend:code-reviewer"
  • description: "Code compliance review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review mode: full. Validate Design Doc compliance and return structured JSON report."

Store output as: $STEP_2_OUTPUT

Step 3: Execute security-reviewer

Invoke security-reviewer using Agent tool:

  • subagent_type: "dev-workflows-frontend:security-reviewer"
  • description: "Security review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review security compliance."

Store output as: $STEP_3_OUTPUT

Step 4: Verdict and Response

If security-reviewer returned blocked: Stop immediately. Report the blocked finding and escalate to user. Do not proceed to fix steps.

Code compliance criteria (considering project stage):

  • Prototype: Pass at 70%+
  • Production: 90%+ recommended

Security criteria:

  • approved or approved_with_notes → Pass
  • needs_revision → Fail

Report both results independently using subagent output fields only:

Before presenting to the user, the orchestrator computes a recommended route per finding using the rule below (this rule is internal — do not include it in the user-facing prompt):

Finding pattern Recommended route
dd_violation where the code intent matches the original requirement but the Design Doc captured a different design d (Design-side update)
dd_violation where the code drifted from a still-correct Design Doc c (Code-side fix)
reliability / security / maintainability findings c (Code-side fix)

Then present to the user (label each finding with its recommended route, grouped by route):

Code Compliance: [complianceRate from code-reviewer]
  Verdict: [verdict from code-reviewer]
  Identifier Match Rate: [identifierMatchRate from code-reviewer]
  Acceptance Criteria:
  - [fulfilled] [item] (confidence: [high/medium/low])
  - [partially_fulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  - [unfulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  Identifier Mismatches:
  - [identifier]: DD=[designDocValue] Code=[codeValue] at [location] [recommended: c | d]
  Quality Findings:
  - [category] [location]: [description] — [rationale] [recommended: c]

Security Review: [status from security-reviewer]
  Findings by category:
  - [confirmed_risk] [location]: [description] — [rationale] [recommended: c]
  - [defense_gap] [location]: [description] — [rationale] [recommended: c]
  - [hardening] [location]: [description] — [rationale] [recommended: c]
  - [policy] [location]: [description] — [rationale] [recommended: c]
  Notes: [notes from security-reviewer, if present]

Resolve discrepancies — confirm or override the recommended route per finding:
  c) Code-side fix       — code violates Design Doc; modify code to match
  d) Design-side update  — code is correct; Design Doc is stale, revise it
  s) Skip                — accept current state without changes

Use AskUserQuestion. The default offer is "accept all recommended routes" — a single confirmation for the typical case where the orchestrator's recommendations are correct. When the user wants to override, collect per-finding c/d/s decisions instead. If the user selects s for everything: skip Steps 5-10, proceed to Step 11.

Step 5: Execute Skill

Execute Skill: documentation-criteria (for task file template)

Step 5d: Design-Side Update

Run this step only when the user routed at least one finding to d. When all routes are c or s, skip directly to Step 6.

  1. Invoke technical-designer-frontend in update mode using Agent tool:

    • subagent_type: "dev-workflows-frontend:technical-designer-frontend"
    • description: "Design Doc update from review findings"
    • prompt: "Update Design Doc at [path] in update mode. The implementation has diverged in the following ways that the team has decided to ratify in the design rather than in the code: [list of d-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
  2. Invoke document-reviewer to verify the updated Design Doc:

    • subagent_type: "dev-workflows-frontend:document-reviewer"
    • description: "Document review of updated Design Doc"
    • prompt: "Review updated Design Doc at [path] for consistency and completeness."
  3. When multiple Design Docs exist (ls docs/design/*.md | grep -v template | wc -l > 1), invoke design-sync:

    • subagent_type: "dev-workflows-frontend:design-sync"
    • description: "Cross-DD consistency check"
    • prompt: "source_design: [updated DD path]. Detect conflicts across all Design Docs after the update."
    • When sync_status: conflicts_found: present conflicts to the user; resolution requires re-invoking technical-designer-frontend for affected DDs.
  4. After Step 5d completes:

    • If the user selected d for all findings (no c routes) → skip Steps 6-8, proceed to Step 9 for re-validation
    • If the user selected both d and c → re-evaluate the c-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remaining c findings

Step 6: Create Task File

Create task file at docs/plans/tasks/review-fixes-YYYYMMDD.md Include both code compliance issues and security requiredFixes.

Step 7: Execute Fixes

Invoke task-executor-frontend using Agent tool:

  • subagent_type: "dev-workflows-frontend:task-executor-frontend"
  • description: "Execute review fixes"
  • prompt: "Task file: docs/plans/tasks/review-fixes-YYYYMMDD.md. Apply staged fixes (stops at 5 files)."

Step 8: Quality Check

Invoke quality-fixer-frontend using Agent tool:

  • subagent_type: "dev-workflows-frontend:quality-fixer-frontend"
  • description: "Quality gate check"
  • prompt: "Confirm quality gate passage for fixed files."

Step 9: Re-validate code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows-frontend:code-reviewer"
  • description: "Re-validate compliance"
  • prompt: "Re-validate Design Doc compliance after fixes. Design Doc: [path]. Implementation files: [file list]. Prior compliance issues: $STEP_2_OUTPUT. Verify each prior issue is resolved (whether resolved code-side or design-side)."

Step 10: Re-validate security-reviewer

Invoke security-reviewer using Agent tool (only if security fixes were applied):

  • subagent_type: "dev-workflows-frontend:security-reviewer"
  • description: "Re-validate security"
  • prompt: "Re-validate security after fixes. Prior findings: $STEP_3_OUTPUT. Design Doc: [path]. Implementation files: [file list]."

Step 11: Final Cleanup and Report

Delete the review-fix task file this recipe created (if any). Its work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete docs/plans/tasks/review-fixes-YYYYMMDD.md if it exists

If the file cannot be deleted (filesystem error), report the failure but do not block the final report.

Then present the final report:

Code Compliance:
  Initial: [X]%
  Final: [Y]% (if fixes executed)

Security Review:
  Initial: [status]
  Final: [status] (if fixes executed)
  Notes: [notes from approved_with_notes, if any]

Remaining issues:
- [items requiring manual intervention]

Cleanup: review-fixes task file removed

Auto-fixable Items (code-side path)

  • Simple unimplemented acceptance criteria
  • Error handling additions
  • Contract definition fixes
  • Function splitting (length/complexity improvements)
  • Security confirmed_risk and defense_gap fixes (input validation, auth checks, output encoding)

Non-fixable Items

  • Fundamental business logic changes
  • Architecture-level modifications
  • Committed secrets (blocked → human intervention)

Design-Side Update Triggers

Discrepancies suitable for the design-side path (code is correct, DD became stale):

  • Identifier renames where the new identifier reflects the team's current naming
  • Behavioral changes that match the original requirement intent better than what the DD captured
  • Component splits or merges where the new structure is sound and the DD documented the prior structure
  • New ACs that the implementation already satisfies but the DD never enumerated

Scope: Design Doc compliance validation, security review, code-side auto-fixes, and design-side update routing.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the review scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.
全栈构建编排技能,通过Agent工具路由并执行前后端任务。自动解析工作计划,按模式分配子代理,严格执行执行-检查-修复-提交流程,确保代码质量与完整交付。
用户要求执行分解的全栈开发任务 提供包含前后端任务文件的执行指令
skills/recipe-fullstack-build/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-fullstack-build -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-fullstack-build",
    "description": "Execute decomposed fullstack tasks with layer-aware agent routing",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Required Reference

MANDATORY: Read references/monorepo-flow.md from subagents-orchestration-guide skill BEFORE proceeding. Follow the Extended Task Cycle and Agent Routing defined there.

Execution Protocol

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Route agents by task filename pattern (see monorepo-flow.md reference):
    • *-backend-task-* → task-executor + quality-fixer
    • *-frontend-task-* → task-executor-frontend + quality-fixer-frontend
  3. Follow the 4-step task cycle exactly: executor → escalation check → quality-fixer → commit
  4. Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
  5. Scope: Complete when all tasks are committed or escalation occurs

CRITICAL: Run layer-appropriate quality-fixer(s) before every commit.

Work plan: $ARGUMENTS

Pre-execution Prerequisites

Work Plan Resolution

Before any task processing, locate the work plan. Resolution rule:

  1. List task files in docs/plans/tasks/ matching the layer-aware patterns {plan-name}-backend-task-*.md and {plan-name}-frontend-task-*.md only. Single-layer tasks ({plan-name}-task-*.md) are excluded here so a stale single-layer run does not redirect this recipe to the wrong work plan
  2. From the matched files, also exclude every file matching any of these patterns — they originate from other workflow phases and are not implementation tasks for this run's plan: *-task-prep-*.md (readiness preflight tasks), _overview-*.md (decomposition overview file), *-phase*-completion.md (per-phase completion files), review-fixes-*.md (post-implementation review fixes), integration-tests-*-task-*.md (integration-test add-on scaffolding)
  3. For each remaining file, extract the {plan-name} prefix as the segment that appears before -backend-task- or -frontend-task-
  4. When at least one task file matches, the work plan is docs/plans/{plan-name}.md for the prefix that has the most recent task-file mtime; ties broken by the lexicographically last {plan-name}
  5. When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template .md in docs/plans/

Consumed Task Set

Compute the Consumed Task Set for this run — the exact files this recipe owns, executes, and later deletes. Use the same restricted pattern as Work Plan Resolution:

  1. List task files in docs/plans/tasks/ matching the layer-aware patterns {plan-name}-backend-task-*.md and {plan-name}-frontend-task-*.md for the {plan-name} resolved by Work Plan Resolution. Single-layer tasks are excluded
  2. Exclude every file matching: *-task-prep-*.md, _overview-*.md, *-phase*-completion.md, review-fixes-*.md, integration-tests-*-task-*.md (these originate from other workflow phases)

Every subsequent reference to "task files" in this recipe — Task Generation Decision Flow, Task Execution Cycle iteration, and Final Cleanup — uses this set, not the unrestricted docs/plans/tasks/*.md glob.

Task Generation Decision Flow

Analyze the Consumed Task Set and determine the action required:

State Criteria Next Action
Tasks exist Consumed Task Set is non-empty User's execution instruction serves as batch approval → Enter autonomous execution immediately
No tasks + plan exists Consumed Task Set is empty but the resolved work plan exists Confirm with user → run task-decomposer
Neither exists + Design Doc exists No plan, no Consumed Task Set, but docs/design/*.md exists Invoke work-planner to create work plan from Design Doc(s), then run document-reviewer (dev-workflows:document-reviewer, doc_type: WorkPlan); branch on the reviewer's verdict.decision — on needs_revision, re-invoke work-planner (update) and re-review until approved/approved_with_conditions, then present the reviewed plan for batch approval before task decomposition; on rejected, stop before task decomposition and escalate to the user
Neither exists No plan, no Consumed Task Set, no Design Doc Report missing prerequisites to user and stop

Task Decomposition Phase (Conditional)

When the Consumed Task Set is empty:

1. User Confirmation

No task files in the Consumed Task Set.
Work plan: docs/plans/[plan-name].md

Generate tasks from the work plan? (y/n):

2. Task Decomposition (if approved)

Invoke task-decomposer using Agent tool:

  • subagent_type: "dev-workflows:task-decomposer"
  • description: "Decompose work plan"
  • prompt: "Read work plan at docs/plans/[plan-name].md and decompose into atomic tasks. Output: Individual task files in docs/plans/tasks/. Granularity: 1 task = 1 commit = independently executable. Use layer-aware naming: {plan}-backend-task-{n}.md, {plan}-frontend-task-{n}.md based on Target files paths."

3. Verify Generation

Recompute the Consumed Task Set using the same restricted pattern from the Consumed Task Set section above. Confirm it is now non-empty. If it is still empty, escalate to the user — task-decomposer either failed silently or produced files that don't match the expected pattern.

Pre-execution Checklist

  • Confirmed Consumed Task Set is non-empty (computed in the Consumed Task Set section above)
  • Identified task execution order within the Consumed Task Set (dependencies)
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Task Execution Cycle (Filename-Pattern-Based)

MANDATORY: For each task in the Consumed Task Set, route agents by task filename pattern from monorepo-flow.md reference.

Agent Routing Table

Filename Pattern Executor Quality Fixer
*-backend-task-* dev-workflows:task-executor dev-workflows:quality-fixer
*-frontend-task-* dev-workflows-frontend:task-executor-frontend dev-workflows-frontend:quality-fixer-frontend
*-task-* (no layer prefix) dev-workflows:task-executor dev-workflows:quality-fixer (default)

Task Execution (4-Step Cycle)

For EACH task, YOU MUST:

  1. Register tasks using TaskCreate: Register work steps. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON"
  2. Agent tool (subagent_type per routing table) → Pass task file path in prompt, receive structured response
  3. CHECK executor response:
    • status: "escalation_needed" or "blocked" → STOP and escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 2 with requiredFixes
      • approved → Proceed to step 4
    • readyForQualityCheck: true → Proceed to step 4
  4. INVOKE quality-fixer: Execute all quality checks and fixes (layer-appropriate per routing table). Always pass the current task file path as task_file
  5. CHECK quality-fixer response:
    • stub_detected → Return to step 2 with incompleteImplementations[] details
    • blocked → STOP and escalate to user
    • approved → Proceed to step 6
  6. COMMIT on approval: Execute git commit

CRITICAL: Parse every sub-agent response for status fields. Execute the matching branch in the 4-step cycle. Proceed to next task only after layer-appropriate quality-fixer returns approved.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Verify task files exist per Pre-execution Checklist, then enter autonomous execution mode. When requirement changes are detected during execution, escalate to the user with the change summary before continuing.

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows:code-verifier") → invoke once per Design Doc (doc_type: design-doc, single document_path, code_paths: implementation file list from git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows:security-reviewer") → Design Doc path(s), implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute layer-appropriate task-executor with consolidated fixes → quality-fixer
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file in the Consumed Task Set
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer for this {plan-name})
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Completion Report Contract

Final report must include:

  • Task decomposition status
  • Implemented task count, including backend/frontend counts
  • Quality check result
  • Commit count
  • Cleanup result
  • Escalation or blocking summary, if any
全栈实现编排技能,协调前后端全周期流程。依据monorepo-flow规范,通过子代理完成需求、设计、规划及实施。支持新需求启动、断点续传及质量修复,确保多层架构一致性与自动化交付。
需要执行全栈功能开发或重构 请求跨前后端的复杂系统实现 全栈项目流程中断需继续推进
skills/recipe-fullstack-implement/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-fullstack-implement -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-fullstack-implement",
    "description": "Orchestrate full-cycle implementation across backend and frontend layers",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Full-cycle fullstack implementation management (Requirements Analysis → Design (backend + frontend) → Planning → Implementation → Quality Assurance)

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Required Reference

MANDATORY: Read references/monorepo-flow.md from subagents-orchestration-guide skill BEFORE proceeding. Follow the Fullstack Flow defined there instead of the standard single-layer flow.

Execution Protocol

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Follow monorepo-flow.md for the design phase (multiple Design Docs, design-sync, vertical slicing)
  3. Follow subagents-orchestration-guide skill for all other orchestration rules (stop points, structured responses, escalation)
  4. Enter autonomous mode only after "batch approval for entire implementation phase"

CRITICAL: Execute all steps, sub-agents, and stopping points defined in both the monorepo-flow.md reference and subagents-orchestration-guide skill.

Execution Decision Flow

1. Current Situation Assessment

Instruction Content: $ARGUMENTS

Assess the current situation:

Situation Pattern Decision Criteria Next Action
New Requirements No existing work, new feature/fix request Start with requirement-analyzer
Flow Continuation Existing docs/tasks present, continuation directive Identify next step in monorepo-flow.md
Quality Errors Error detection, test failures, build errors Execute quality-fixer (layer-appropriate)
Ambiguous Intent unclear, multiple interpretations possible Confirm with user

2. Progress Verification for Continuation

When continuing existing flow, verify:

  • Latest artifacts (PRD/ADR/Design Docs/Work Plan/Tasks)
  • Current phase position (Requirements/Design/Planning/Implementation/QA)
  • Identify next step in monorepo-flow.md

3. Design through Planning Phase

Follow monorepo-flow.md for the complete design-through-planning flow (Steps 1-16 for Large scale, Steps 1-14 for Medium scale). The flow table in that reference defines every step, agent invocation, parallelization rule, and stop point.

Key points to enforce as the orchestrator runs the flow:

  • Create separate Design Docs per layer (see monorepo-flow.md "Layer Context in Design Doc Creation")
  • Frontend Design Doc references the approved UI Spec (pass UI Spec path to technical-designer-frontend) and reuses the ui-analyzer output produced earlier in the flow
  • Execute document-reviewer once per Design Doc (separate invocations)
  • Run design-sync for cross-layer consistency verification
  • Pass all Design Docs to work-planner (subagent_type: "dev-workflows:work-planner") with vertical slicing instruction

4. Register All Flow Steps Using TaskCreate (MANDATORY)

After scale determination, register all steps of the monorepo-flow.md using TaskCreate:

  • First task: "Map preloaded skills to applicable concrete rules"
  • Register each step as individual task
  • Set currently executing step to in_progress using TaskUpdate
  • Complete task registration before invoking subagents

After requirement-analyzer [Stop]

When user responds to questions:

  • If response matches any scopeDependencies.question → Check impact for scale change
  • If scale changes → Re-execute requirement-analyzer with updated context
  • If confidence: "confirmed" or no scale change → Proceed to next step

Subagents Orchestration Guide Compliance Execution

Pre-execution Checklist (MANDATORY):

  • Read monorepo-flow.md reference
  • Confirmed relevant flow steps
  • Identified current progress position
  • Clarified next step
  • Recognized stopping points
  • codebase-analyzer included before each Design Doc creation
  • code-verifier included before document-reviewer for each Design Doc
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Required Flow Compliance:

  • Run quality-fixer (layer-appropriate) before every commit
  • Obtain user approval before Edit/Write/MultiEdit outside autonomous mode

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Mandatory Orchestrator Responsibilities

Task Execution Quality Cycle (Filename-Pattern-Based)

Agent routing by task filename (see monorepo-flow.md reference):

*-backend-task-*   → dev-workflows:task-executor + dev-workflows:quality-fixer
*-frontend-task-*  → dev-workflows-frontend:task-executor-frontend + dev-workflows-frontend:quality-fixer-frontend

Rules:

  1. Execute ONE task completely before starting next (each task goes through the full 4-step cycle via Agent tool, using the correct executor per filename pattern)
  2. Check executor status before quality-fixer (escalation check)
  3. Quality-fixer MUST run after each executor before proceeding to commit. Always pass the current task file path as task_file
  4. Check quality-fixer response:
    • stub_detected → Return to executor with incompleteImplementations[] details
    • blocked → Escalate to user
    • approved → Proceed to commit

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows:code-verifier") → invoke once per Design Doc (doc_type: design-doc, single document_path, code_paths: implementation file list from git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows:security-reviewer") → Design Doc path(s), implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute layer-appropriate task-executor with consolidated fixes → quality-fixer
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file matching docs/plans/tasks/{plan-name}-backend-task-*.md and docs/plans/tasks/{plan-name}-frontend-task-*.md (the {plan-name} derived from the work plan path used in this run)
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer)
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Test Information Communication

After acceptance-test-generator execution, when invoking work-planner (subagent_type: "dev-workflows:work-planner"), communicate:

  • Generated integration test file path (from generatedFiles.integration)
  • Generated fixture-e2e test file path or null (from generatedFiles.fixtureE2e)
  • Generated service-integration-e2e test file path or null (from generatedFiles.serviceE2e)
  • Per-lane E2E absence reason (from e2eAbsenceReason.fixtureE2e and e2eAbsenceReason.serviceE2e, when each lane is null)
  • Explicit note: integration tests are created simultaneously with implementation, fixture-e2e tests are created alongside the UI feature phase, service-integration-e2e tests are executed only in the final phase

Execution Method

All work is executed through sub-agents. Sub-agent selection follows monorepo-flow.md reference and subagents-orchestration-guide skill.

作为编排者,全周期管理从需求到部署的实施流程。通过子代理工具委托工作,严格遵循编排指南的分步执行与审批停止点,根据当前状况评估决定下一步行动,并强制注册所有流程步骤至任务系统。
需要启动或继续完整的项目实施生命周期 涉及需求分析、设计、规划、实现或质量保证的全流程协调
skills/recipe-implement/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-implement -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-implement",
    "description": "Orchestrate the complete implementation lifecycle from requirements to deployment",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Full-cycle implementation management (Requirements Analysis → Design → Planning → Implementation → Quality Assurance)

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Follow subagents-orchestration-guide skill flows exactly:
    • Execute one step at a time in the defined flow (Large/Medium/Small scale)
    • When flow specifies "Execute document-reviewer" → Execute it immediately
    • Stop at every [Stop: ...] marker → Use AskUserQuestion for confirmation and wait for approval before proceeding
  3. Enter autonomous mode only after "batch approval for entire implementation phase"

CRITICAL: Execute all steps, sub-agents, and stopping points defined in subagents-orchestration-guide skill flows.

Execution Decision Flow

1. Current Situation Assessment

Instruction Content: $ARGUMENTS

Assess the current situation:

Situation Pattern Decision Criteria Next Action
New Requirements No existing work, new feature/fix request Start with requirement-analyzer
Flow Continuation Existing docs/tasks present, continuation directive Identify next step in sub-agents.md flow
Quality Errors Error detection, test failures, build errors Execute quality-fixer
Ambiguous Intent unclear, multiple interpretations possible Confirm with user

2. Progress Verification for Continuation

When continuing existing flow, verify:

  • Latest artifacts (PRD/ADR/Design Doc/Work Plan/Tasks)
  • Current phase position (Requirements/Design/Planning/Implementation/QA)
  • Identify next step in subagents-orchestration-guide skill corresponding flow

3. Next Action Execution

MANDATORY subagents-orchestration-guide skill reference:

  • Verify scale-based flow (Large/Medium/Small scale)
  • Confirm autonomous execution mode conditions
  • Recognize mandatory stopping points
  • Invoke next sub-agent defined in flow

After requirement-analyzer [Stop]

When user responds to questions:

  • If response matches any scopeDependencies.question → Check impact for scale change
  • If scale changes → Re-execute requirement-analyzer with updated context
  • If confidence: "confirmed" or no scale change → Proceed to next step

4. Register All Flow Steps Using TaskCreate (MANDATORY)

After scale determination, register all steps of the applicable flow using TaskCreate:

  • First task: "Map preloaded skills to applicable concrete rules"
  • Register each step as individual task
  • Set currently executing step to in_progress using TaskUpdate
  • Complete task registration before invoking subagents

Subagents Orchestration Guide Compliance Execution

Pre-execution Checklist (MANDATORY):

  • Confirmed relevant subagents-orchestration-guide skill flow
  • Identified current progress position
  • Clarified next step
  • Recognized stopping points
  • codebase-analyzer included before Design Doc creation (Medium/Large scale)
  • code-verifier included before document-reviewer for Design Doc review (Medium/Large scale)
  • Environment check: Can I execute per-task commit cycle?
    • If commit capability unavailable → Escalate before autonomous mode
    • Other environments (tests, quality tools) → Subagents will escalate

Required Flow Compliance:

  • Run quality-fixer before every commit
  • Obtain user approval before Edit/Write/MultiEdit outside autonomous mode

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Mandatory Orchestrator Responsibilities

Task Execution Quality Cycle (4-Step Cycle per Task)

Per-task cycle (complete each task before starting next):

  1. Agent tool (subagent_type: "dev-workflows:task-executor") → Pass task file path in prompt, receive structured response
  2. Check task-executor response:
    • status: escalation_needed or blocked → Escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 1 with requiredFixes
      • approved → Proceed to step 3
    • Otherwise → Proceed to step 3
  3. quality-fixer → Quality check and fixes. Always pass the current task file path as task_file
    • stub_detected → Return to step 1 with incompleteImplementations[] details
    • blocked → Escalate to user
    • approved → Proceed to step 4
  4. git commit → Execute with Bash (on approved)

Post-Implementation Verification (After All Tasks Complete)

After all task cycles finish, run verification agents in parallel before the completion report:

  1. Invoke both in parallel using Agent tool:

    • code-verifier (subagent_type: "dev-workflows:code-verifier") → doc_type: design-doc, Design Doc path, code_paths: implementation file list (git diff --name-only main...HEAD)
    • security-reviewer (subagent_type: "dev-workflows:security-reviewer") → Design Doc path, implementation file list
  2. Consolidate results — check pass/fail for each:

    • code-verifier: pass when status is consistent or mostly_consistent. fail when needs_review or inconsistent. Collect discrepancies with status drift, conflict, or gap
    • security-reviewer: pass when status is approved or approved_with_notes. fail when needs_revision. blocked → Escalate to user
    • Present unified verification report to user
  3. Fix cycle (when any verifier failed):

    • Consolidate all actionable findings into a single task file
    • Execute task-executor with consolidated fixes → quality-fixer
    • Re-run only the failed verifiers (by the criteria in step 2)
    • Repeat until all pass or blocked → Escalate to user
  4. All passed → Proceed to Final Cleanup

Final Cleanup

Before the completion report, delete the implementation task files this recipe consumed. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete every file matching docs/plans/tasks/{plan-name}-task-*.md (the {plan-name} derived from the work plan path used in this run)
  • Delete every file matching docs/plans/tasks/{plan-name}-phase*-completion.md (the per-phase completion files generated by task-decomposer)
  • Delete the corresponding docs/plans/tasks/_overview-{plan-name}.md if present
  • Preserve the work plan itself (docs/plans/{plan-name}.md) — the user decides whether to delete it after final review

If task files cannot be deleted (filesystem error), report the failure but do not block the completion report.

Test Information Communication

After acceptance-test-generator execution, when invoking work-planner (subagent_type: "dev-workflows:work-planner"), communicate:

  • Generated integration test file path (from generatedFiles.integration)
  • Generated fixture-e2e test file path or null (from generatedFiles.fixtureE2e)
  • Generated service-integration-e2e test file path or null (from generatedFiles.serviceE2e)
  • Per-lane E2E absence reason (from e2eAbsenceReason.fixtureE2e and e2eAbsenceReason.serviceE2e, when each lane is null)
  • Explicit note: integration tests are created simultaneously with implementation, fixture-e2e tests are created alongside the UI feature phase, service-integration-e2e tests are executed only in the final phase

Execution Method

All work is executed through sub-agents. Sub-agent selection follows subagents-orchestration-guide skill.

该技能用于根据设计文档创建工作执行计划并获取审批。流程包括选择设计文档、可选生成测试骨架、调用工作规划器创建计划、审查计划并最终获得批准,全程遵循编排指南。
用户请求基于设计文档创建工作执行计划 用户请求进行项目规划或任务分解
skills/recipe-plan/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-plan -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-plan",
    "description": "Create work plan from design document and obtain plan approval",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to the planning phase.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
  2. Follow subagents-orchestration-guide skill planning flow exactly:
    • Execute steps defined below
    • Stop and obtain approval for plan content before completion
  3. Scope: See Scope Boundaries below

CRITICAL: When the user requests test generation, always execute acceptance-test-generator first — it provides the test skeleton that work-planner depends on.

Scope Boundaries

Included in this skill:

  • Design document selection
  • Test skeleton generation with acceptance-test-generator
  • Work plan creation with work-planner
  • Work plan review with document-reviewer
  • Plan approval obtainment

Responsibility Boundary: This skill completes with work plan approval.

Follow the planning process below:

Execution Process

Step 1: Design Document Selection

! ls -la docs/design/*.md | head -10

  • Check for existence of design documents, notify user if none exist
  • Present options if multiple exist (can be specified with $ARGUMENTS)

Step 2: Test Skeleton Generation Confirmation

  • Confirm with user whether to generate test skeletons (integration + E2E lanes) first
  • If user wants generation: invoke acceptance-test-generator
  • Pass generation results to next process according to subagents-orchestration-guide skill coordination specification

Step 3: Work Plan Creation

Invoke work-planner using Agent tool:

  • subagent_type: "dev-workflows:work-planner"

  • description: "Work plan creation"

  • If test skeletons were generated in Step 2, build the prompt by listing every lane's status:

    • Always include: "Integration test file: [path or 'not generated']"
    • For each E2E lane (fixtureE2e, serviceE2e):
      • When generatedFiles.<lane> is not null: "[lane] test file: [path]"
      • When generatedFiles.<lane> is null: "No [lane] skeleton generated (reason: [e2eAbsenceReason.])"
    • Append placement guidance: "Integration tests are created simultaneously with each phase implementation. fixture-e2e tests are created alongside the UI feature phase. service-integration-e2e tests are executed only in the final phase."
  • If test skeletons were not generated: prompt: "Create work plan from Design Doc at [path]."

  • Follow subagents-orchestration-guide Prompt Construction Rule for additional prompt parameters

Step 4: Work Plan Review

Invoke document-reviewer to review the work plan:

  • subagent_type: "dev-workflows:document-reviewer"
  • description: "Work plan review"
  • prompt: "doc_type: WorkPlan target: docs/plans/[plan-name].md. Review semantic traceability to the Design Doc, early verification placement, real-boundary verification coverage, Failure Mode Checklist, and Review Scope."
  • The work plan is a derivation of the Design Doc, so plan-fidelity findings are resolved without user input. Branch on the reviewer's verdict.decision: on needs_revision, re-invoke work-planner in update mode with the findings and re-review, repeating until approved or approved_with_conditions. On rejected, escalate to the user.

Step 5: Present for Approval

  • Present the reviewed work plan to the user for batch approval. If the user requests changes, re-invoke work-planner with revised parameters and re-run Step 4.
  • Highlight steps with unclear scope or external dependencies and ask the user to confirm

Response at Completion

Recommended: After plan approval, output the standard block below.

Planning phase completed.
- Work plan: docs/plans/[plan-name].md
- Status: Approved

Please provide separate instructions for implementation.

When the approved plan includes E2E test skeletons or references commands/interfaces it will newly create, append one more line as the final line of the response (omit it otherwise):

Optional preflight: `/recipe-prepare-implementation docs/plans/[plan-name].md` verifies these are implementable before build (exits no-op if all resolve).
在构建前验证工作计划的端到端可实施性,解决验证、Fixture及E2E环境缺口。通过扫描R1-R4标准确保实现可观测且无依赖缺失,若就绪则直接退出,否则生成并执行修复任务。
提及 implement-ready/verification readiness/lane setup/E2E environment missing 在任何未预检就绪的工作计划开始构建阶段前
skills/recipe-prepare-implementation/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-prepare-implementation -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-prepare-implementation",
    "description": "Verifies the work plan is implementable end-to-end and resolves verification-lane \/ fixture \/ E2E-environment gaps before the build phase begins. Use when \"implement-ready\/verification readiness\/lane setup\/E2E environment missing\" is mentioned, or before any build phase begins on a work plan whose readiness has not been preflight-checked.",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Optional readiness phase between work-plan approval and recipe-*-build. Confirms the implementation will be observable from Phase 1 onward and resolves any gaps via Phase 0 tasks. Exits no-op when the readiness criteria already pass, so the recipe is safe to invoke unconditionally.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Self-contained scope: When gaps are found, this recipe BOTH generates resolution tasks AND executes them through the standard 4-step cycle. Recipe completes only when readiness criteria pass or remaining gaps are escalated.
  3. No-op exit: When the readiness scan finds no failing criteria, generate no resolution tasks and exit immediately, presenting the Readiness Report to the user. No files are modified in this branch.

Work plan: $ARGUMENTS

When This Recipe Applies

Run before any recipe-*-build invocation when ANY of the following hold:

  • Work plan was created from a Design Doc whose Verification Strategy references commands, files, functions, or endpoints not yet present in the codebase
  • Work plan includes E2E test skeletons (seed data, auth fixture, environment variables, or external mocks may be unaddressed)
  • Work plan touches UI components without a fixture entry or development route to render their visual states
  • The team has not previously confirmed the local lane runs end-to-end for this feature area

When none of the above hold, the readiness scan in Step 2 will find zero failing criteria and the recipe exits no-op (see Context at the top of this skill).

Readiness Criteria

Each criterion is a measurable check producing pass, fail, or not_applicable with cited evidence.

ID Criterion Pass evidence
R1 Verification Strategy references resolve Every command, file path, function, endpoint, and test referenced in the work plan's Verification Strategy section either exists in the codebase (verified via Glob/Grep) or is the deliverable of a task already in this plan
R2 E2E preconditions addressed When E2E skeletons exist: every precondition mentioned in skeleton comments (seed data, auth fixture, env var, external mock) is present in the codebase or covered by a Phase 0 task in this plan
R3 Phase 1 observability The first implementation phase contains at least one task whose Operation Verification Methods can execute at task completion using only artifacts that exist before the task starts (existing code, prior Phase 0 task deliverables, or the task's own outputs)
R4 UI rendering surface When the plan implements UI components: a fixture entry, dev route, Storybook story, or equivalent rendering surface exists for the impacted components, OR a Phase 0 task adds one
R5 Local lane procedure The work plan or a referenced doc records the commands needed to start the system locally for manual verification (start commands, default ports, seed steps)

R4 and R5 are evaluated only when their triggering signals appear in the work plan; otherwise mark not_applicable.

Pre-execution Prerequisites

# Verify the work plan exists
! ls -la docs/plans/*.md | grep -v template | tail -5

State check:

  • Work plan exists → Proceed to Step 1
  • No work plan → Stop and report: "An approved work plan is required. Complete the upstream planning phase first, then re-invoke this recipe."

Execution Flow

Step 1: Load Inputs

Read the work plan path passed in $ARGUMENTS. Extract:

  • Verification Strategy section (Correctness Proof Method + Early Verification Point)
  • Quality Assurance Mechanisms table
  • Design-to-Plan Traceability table
  • Test skeleton references listed in the plan header
  • Phase structure with each phase's tasks
  • Referenced Design Doc(s) and UI Spec (when present)

Step 2: Readiness Scan

For each criterion R1–R5:

  1. Execute the scan defined in Readiness Criteria using Read / Glob / Grep
  2. Record the result: pass / fail / not_applicable
  3. Cite evidence: file:line for pass, the unresolved reference for fail, the missing trigger signal for not_applicable

Build the Readiness Report (see Output Format) regardless of outcome.

Step 3: No-op Check

When every applicable criterion is pass (zero fail):

  • Present the Readiness Report (see Output Format below) to the user
  • Exit with outcome: ready, gaps_resolved: 0
  • No files are modified in this branch

When one or more criteria are fail → proceed to Step 4.

Step 4: Plan Resolution Tasks

For each fail criterion:

  1. Determine the smallest concrete task that closes the gap (examples: "Add fixture entry for ComponentX covering loading/empty/error states", "Add seed script for E2E user fixtures", "Document local startup commands in docs/run/local.md")

  2. Decide the task's layer by matching every target file path against the markers below:

    • backend when every target file path matches one of: **/api/**, **/server/**, **/services/**, **/backend/**, **/handlers/**, **/repositories/**
    • frontend when every target file path matches one of: **/components/**, **/pages/**, **/web/**, **/frontend/**, **/*.tsx, **/*.jsx
    • mixed (target files span both backend and frontend markers) → escalate to user; ask the user to split the gap into per-layer tasks
    • unrecognized (any target file matches neither backend nor frontend markers — e.g., docs/**, scripts/**, root-level configs, fixture data files outside the markers above) → escalate to user; ask the user to either (a) decide which layer's executor / quality-fixer should run the task, or (b) update the markers if the project uses different paths

    Apply the rules in the order above. The first matching rule wins; "unrecognized" is the final fallback rather than a catch-all that defaults to backend.

  3. Create a Phase 0 task file at docs/plans/tasks/{plan-name}-backend-task-prep-{NN}.md (backend) or docs/plans/tasks/{plan-name}-frontend-task-prep-{NN}.md (frontend) using the task template from documentation-criteria skill. The -task-prep- segment lets recipe-prepare-implementation distinguish prep tasks from implementation tasks while keeping the existing {plan-name}-{layer}-task-* matcher used by other recipes

  4. Update the work plan to insert these tasks as Phase 0 (before Phase 1)

Present the proposed resolution task list to the user with AskUserQuestion. Proceed only after explicit approval — this is the single human gate inside this recipe.

Step 5: Execute Resolution Tasks

For each resolution task, run the standard 4-step cycle (see subagents-orchestration-guide "Task Management: 4-Step Cycle"):

  1. Agent tool — route by filename layer segment:
    • *-backend-task-prep-*subagent_type: "dev-workflows:task-executor"
    • *-frontend-task-prep-*subagent_type: "dev-workflows-frontend:task-executor-frontend"
    • Filename without a recognized layer segment → escalate (the file should not exist; Step 4 prevents this)
  2. Check escalation per orchestration-guide
  3. quality-fixer — route by the same filename layer segment:
    • *-backend-task-prep-*"dev-workflows:quality-fixer"
    • *-frontend-task-prep-*"dev-workflows-frontend:quality-fixer-frontend"
  4. Commit when quality-fixer returns approved

Append the Scope Boundary block (below) to every subagent prompt.

Step 6: Re-scan, Present Readiness Report, Cleanup, Exit

  1. Re-scan: Re-run the Step 2 readiness scan after all resolution tasks are committed.

  2. Present Readiness Report: Present the Readiness Report (see Output Format below) to the user. The report is shown in-session and is not written into the work plan — the durable output of this recipe is the committed Phase 0 resolution tasks, not a persisted report.

  3. Final Cleanup: Delete every prep task file this recipe created for the current {plan-name} (docs/plans/tasks/{plan-name}-backend-task-prep-*.md and docs/plans/tasks/{plan-name}-frontend-task-prep-*.md) AND the phase-completion file generated for prep phases (docs/plans/tasks/{plan-name}-phase0-completion.md when present, since prep tasks live in Phase 0). Prep task files for other plans are out of scope — this recipe deletes only what it created for the current run. Their work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs. The work plan itself is preserved for the downstream recipe--build / recipe--implement.

  4. Exit:

    Re-scan result Action
    All applicable criteria pass Exit with outcome: ready, gaps_resolved: N and final Readiness Report
    One or more fail remain Exit with outcome: escalated — present remaining failures to the user with the next-action recommendation. Treat the re-scan as the terminal evaluation; further resolution requires the user to re-invoke this recipe with updated inputs.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the task scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.

Output Format

Final report presented to the user at exit:

## Implementation Readiness Report

Work plan: [path]
Outcome: ready | escalated
Gaps resolved: [N]

### Readiness Criteria

| ID | Result | Evidence |
|----|--------|----------|
| R1 | pass / fail / not_applicable | [file:line OR "missing: <unresolved reference>"] |
| R2 | ... | ... |
| R3 | ... | ... |
| R4 | ... | ... |
| R5 | ... | ... |

### Resolution Tasks Executed (when gaps_resolved > 0)
- [task file path] — [one-line summary] — committed
- ...

### Remaining Gaps (when outcome is escalated)
- [criterion ID]: [unresolved reference] — Next action: [recommendation]

Completion Criteria

  • Work plan loaded and Verification Strategy / E2E references / Phase structure extracted
  • Readiness scan run with per-criterion result and evidence recorded
  • No-op exit when all pass, OR resolution tasks generated, approved, and executed via the 4-step cycle
  • Re-scan run after the last resolution task commits
  • Prep task files (and Phase 0 phase-completion file when generated) deleted from docs/plans/tasks/
  • Final report presented to the user
从现有代码库逆向生成PRD和设计文档。通过发现、生成、验证和审查工作流,支持配置目标路径、架构风格及是否包含前端设计,按单元逐步执行并输出标准化文档。
需要从代码逆向生成产品需求文档 需要为现有模块生成技术设计文档
skills/recipe-reverse-engineer/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-reverse-engineer -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-reverse-engineer",
    "description": "Generate PRD and Design Docs from existing codebase through discovery, generation, verification, and review workflow",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Reverse engineering workflow to create documentation from existing code

Target: $ARGUMENTS

Orchestrator Definition

Core Identity: "I am an orchestrator."

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Process one step at a time: Execute steps sequentially within each unit (2 → 3 → 4 → 5). Each step's output is the required input for the next step. Complete all steps for one unit before starting the next
  3. Pass $STEP_N_OUTPUT as-is to sub-agents — the orchestrator bridges data without processing or filtering it

Task Registration: Register phases first using TaskCreate, then steps within each phase as you enter it. Update status using TaskUpdate.

Step 0: Initial Configuration

0.1 Scope Confirmation

Use AskUserQuestion to confirm:

  1. Target path: Which directory/module to document
  2. Depth: PRD only, or PRD + Design Docs
  3. Reference Architecture: layered / mvc / clean / hexagonal / none
  4. Human review: Yes (recommended) / No (fully autonomous)
  5. Fullstack design: Yes / No
    • Yes: For each functional unit, generate backend + frontend Design Docs
    • Note: Requires both agents (technical-designer, technical-designer-frontend)

0.2 Output Configuration

  • PRD output: docs/prd/ or existing PRD directory
  • Design Doc output: docs/design/ or existing design directory
  • Verify directories exist, create if needed

Workflow Overview

Phase 1: PRD Generation
  Step 1: Scope Discovery (unified, single pass → group into PRD units → human review)
  Step 2-5: Per-unit loop (Generation → Verification → Review → Revision)

Phase 2: Design Doc Generation (if requested)
  Step 6: Design Doc Scope Mapping (reuse Step 1 results, no re-discovery)
  Step 7-10: Per-unit loop (Generation → Verification → Review → Revision)
  ※ fullstack=Yes: each unit produces backend + frontend Design Docs

Phase 1: PRD Generation

Register using TaskCreate:

  • Step 1: PRD Scope Discovery
  • Per-unit processing (Steps 2-5 for each unit)

Step 1: PRD Scope Discovery

Agent tool invocation:

subagent_type: dev-workflows:scope-discoverer
description: "Discover functional scope"
prompt: |
  Discover functional scope targets in the codebase.

  target_path: $USER_TARGET_PATH
  reference_architecture: $USER_RA_CHOICE
  focus_area: $USER_FOCUS_AREA (if specified)

Store output as: $STEP_1_OUTPUT

Quality Gate:

  • At least one unit discovered → proceed
  • No units discovered → ask user for hints
  • $STEP_1_OUTPUT.prdUnits exists
  • All sourceUnits across prdUnits (flattened, deduplicated) match the set of discoveredUnits IDs — no unit missing, no unit duplicated
  • Each discovered unit's unitInventory has at least one non-empty category (routes, testFiles, or publicExports). Units with all three empty indicate incomplete discovery — re-run scope-discoverer with focus on that unit's relatedFiles

Human Review Point (if enabled): Present $STEP_1_OUTPUT.prdUnits with their source unit mapping. The user confirms, adjusts grouping, or excludes units from scope. This is the most important review point — incorrect grouping cascades into all downstream documents.

Step 2-5: Per-Unit Processing

FOR each unit in $STEP_1_OUTPUT.prdUnits (sequential, one unit at a time):

Step 2: PRD Generation

Agent tool invocation:

subagent_type: dev-workflows:prd-creator
description: "Generate PRD"
prompt: |
  Create reverse-engineered PRD for the following feature.

  Operation Mode: reverse-engineer
  External Scope Provided: true

  Feature: $PRD_UNIT_NAME (from $STEP_1_OUTPUT)
  Description: $PRD_UNIT_DESCRIPTION
  Related Files: $PRD_UNIT_COMBINED_RELATED_FILES
  Entry Points: $PRD_UNIT_COMBINED_ENTRY_POINTS

  Use provided scope as investigation starting point.
  If tracing entry points reveals files outside this scope, include them.
  Create final version PRD based on thorough code investigation.

Store output as: $STEP_2_OUTPUT (PRD path)

Step 3: Code Verification

Prerequisite: $STEP_2_OUTPUT (PRD path from Step 2)

Agent tool invocation:

subagent_type: dev-workflows:code-verifier
description: "Verify PRD consistency"
prompt: |
  Verify consistency between PRD and code implementation.

  doc_type: prd
  document_path: $STEP_2_OUTPUT
  verbose: false

Note: Omit code_paths — the verifier independently discovers code scope from the document, ensuring independent verification not constrained by scope-discoverer's output.

Store output as: $STEP_3_OUTPUT

Quality Gate:

  • consistencyScore >= 70 AND verifiableClaimCount >= 20 → proceed to review
  • consistencyScore >= 70 BUT verifiableClaimCount < 20 → re-run verifier (investigation too shallow)
  • consistencyScore < 70 → flag for detailed review

Step 4: Review

Required Input: $STEP_3_OUTPUT (verification JSON from Step 3)

Agent tool invocation:

subagent_type: dev-workflows:document-reviewer
description: "Review PRD"
prompt: |
  Review the following PRD considering code verification findings.

  doc_type: PRD
  target: $STEP_2_OUTPUT
  mode: composite
  code_verification: $STEP_3_OUTPUT

  ## Additional Review Focus
  - Alignment between PRD claims and verification evidence
  - Resolution recommendations for each discrepancy
  - Completeness of undocumented feature coverage

Store output as: $STEP_4_OUTPUT

Step 5: Revision (conditional)

Trigger Conditions (any one of the following):

  • Review status is "Needs Revision" or "Rejected"
  • Critical discrepancies exist in $STEP_3_OUTPUT
  • consistencyScore < 70

Agent tool invocation:

subagent_type: dev-workflows:prd-creator
description: "Revise PRD"
prompt: |
  Update PRD based on review feedback and code verification results.

  Operation Mode: update
  Existing PRD: $STEP_2_OUTPUT

  ## Review Feedback
  $STEP_4_OUTPUT

  ## Code Verification Results
  $STEP_3_OUTPUT

  Address discrepancies by severity. Critical and major items require correction.
  Minor items: correct if straightforward, otherwise leave as-is with rationale.

Loop Control: Maximum 2 revision cycles. After 2 cycles, flag for human review regardless of status.

Unit Completion

  • Review status is "Approved" or "Approved with Conditions"
  • Human review passed (if enabled in Step 0)

Next: Proceed to next unit. After all units → Phase 2.

Phase 2: Design Doc Generation

Execute only if Design Docs were requested in Step 0

Register using TaskCreate:

  • Step 6: Design Doc Scope Mapping
  • Per-unit processing (Steps 7-10 for each unit)

Step 6: Design Doc Scope Mapping

No additional discovery required. Use $STEP_1_OUTPUT.discoveredUnits (implementation-granularity units) for technical profiles. Use $STEP_1_OUTPUT.prdUnits[].sourceUnits to trace which discovered units belong to each PRD unit.

Each PRD unit from Phase 1 maps to Design Doc unit(s):

  • Standard mode (fullstack=No): 1 PRD unit → 1 Design Doc (using technical-designer)
  • Fullstack mode (fullstack=Yes): 1 PRD unit → 2 Design Docs (technical-designer + technical-designer-frontend)

Map $STEP_1_OUTPUT units to Design Doc generation targets, carrying forward:

  • technicalProfile.primaryModules → Primary Files
  • technicalProfile.publicInterfaces → Public Interfaces
  • dependencies → Dependencies
  • relatedFiles → Scope boundary
  • unitInventory → Unit Inventory (routes, test files, public exports)

Store output as: $STEP_6_OUTPUT

Step 7-10: Per-Unit Processing

FOR each unit in $STEP_6_OUTPUT (sequential, one unit at a time):

Step 7: Design Doc Generation

Scope: Document the current architecture exactly as implemented in code.

Standard mode (fullstack=No):

Agent tool invocation:

subagent_type: dev-workflows:technical-designer
description: "Generate Design Doc"
prompt: |
  Create Design Doc for the following feature based on existing code.

  Operation Mode: reverse-engineer

  Feature: $UNIT_NAME (from $STEP_6_OUTPUT)
  Description: $UNIT_DESCRIPTION
  Primary Files: $UNIT_PRIMARY_MODULES
  Public Interfaces: $UNIT_PUBLIC_INTERFACES
  Dependencies: $UNIT_DEPENDENCIES
  Unit Inventory: $UNIT_INVENTORY (routes, test files, public exports from scope discovery)

  Parent PRD: $APPROVED_PRD_PATH

  Document current architecture as-is. Use Unit Inventory as a completeness baseline — all routes and exports should be accounted for in the Design Doc.

Store output as: $STEP_7_OUTPUT

Fullstack mode (fullstack=Yes):

For each unit, invoke 7a then 7b sequentially (7b depends on 7a output):

7a. Backend Design Doc:

subagent_type: dev-workflows:technical-designer
description: "Generate backend Design Doc"
prompt: |
  Create a backend Design Doc for the following feature based on existing code.

  Operation Mode: reverse-engineer

  Feature: $UNIT_NAME (from $STEP_6_OUTPUT)
  Description: $UNIT_DESCRIPTION
  Primary Files: $UNIT_PRIMARY_MODULES
  Public Interfaces: $UNIT_PUBLIC_INTERFACES
  Dependencies: $UNIT_DEPENDENCIES
  Unit Inventory: $UNIT_INVENTORY

  Parent PRD: $APPROVED_PRD_PATH

  Focus on: API contracts, data layer, business logic, service architecture.
  Document current architecture as-is. Use Unit Inventory as completeness baseline.

Store output as: $STEP_7a_OUTPUT

7b. Frontend Design Doc:

subagent_type: dev-workflows-frontend:technical-designer-frontend
description: "Generate frontend Design Doc"
prompt: |
  Create a frontend Design Doc for the following feature based on existing code.

  Operation Mode: reverse-engineer

  Feature: $UNIT_NAME (from $STEP_6_OUTPUT)
  Description: $UNIT_DESCRIPTION
  Primary Files: $UNIT_PRIMARY_MODULES
  Public Interfaces: $UNIT_PUBLIC_INTERFACES
  Dependencies: $UNIT_DEPENDENCIES
  Unit Inventory: $UNIT_INVENTORY

  Parent PRD: $APPROVED_PRD_PATH
  Backend Design Doc: $STEP_7a_OUTPUT

  Reference backend Design Doc for API contracts.
  Focus on: component hierarchy, state management, UI interactions, data fetching.
  Document current architecture as-is. Use Unit Inventory as completeness baseline.

Store output as: $STEP_7b_OUTPUT

Step 8: Code Verification

Standard mode: Verify $STEP_7_OUTPUT.

Fullstack mode: Verify each Design Doc separately.

Agent tool invocation (per Design Doc):

subagent_type: dev-workflows:code-verifier
description: "Verify Design Doc consistency"
prompt: |
  Verify consistency between Design Doc and code implementation.

  doc_type: design-doc
  document_path: $STEP_7_OUTPUT (or $STEP_7a_OUTPUT / $STEP_7b_OUTPUT)
  verbose: false

Note: Omit code_paths — the verifier independently discovers code scope from the document.

Store output as: $STEP_8_OUTPUT

Step 9: Review

Required Input: $STEP_8_OUTPUT (verification JSON from Step 8)

Agent tool invocation (per Design Doc):

subagent_type: dev-workflows:document-reviewer
description: "Review Design Doc"
prompt: |
  Review the following Design Doc considering code verification findings.

  doc_type: DesignDoc
  target: $STEP_7_OUTPUT (or $STEP_7a_OUTPUT / $STEP_7b_OUTPUT)
  mode: composite
  code_verification: $STEP_8_OUTPUT

  ## Parent PRD
  $APPROVED_PRD_PATH

  ## Additional Review Focus
  - Technical accuracy of documented interfaces
  - Consistency with parent PRD scope
  - Completeness of unit boundary definitions

Store output as: $STEP_9_OUTPUT

Step 10: Revision (conditional)

Trigger Conditions (same as Step 5):

  • Review status is "Needs Revision" or "Rejected"
  • Critical discrepancies exist in $STEP_8_OUTPUT
  • consistencyScore < 70

Agent tool invocation (per Design Doc):

subagent_type: dev-workflows:technical-designer (or dev-workflows-frontend:technical-designer-frontend for frontend Design Docs)
description: "Revise Design Doc"
prompt: |
  Update Design Doc based on review feedback and code verification results.

  Operation Mode: update
  Existing Design Doc: $STEP_7_OUTPUT (or $STEP_7a_OUTPUT / $STEP_7b_OUTPUT)

  ## Review Feedback
  $STEP_9_OUTPUT

  ## Code Verification Results
  $STEP_8_OUTPUT

  Address discrepancies by severity. Critical and major items require correction.
  Minor items: correct if straightforward, otherwise leave as-is with rationale.

Loop Control: Maximum 2 revision cycles. After 2 cycles, flag for human review regardless of status.

Unit Completion

  • Review status is "Approved" or "Approved with Conditions"
  • Human review passed (if enabled in Step 0)

Next: Proceed to next unit. After all units → Final Report.

Final Report

Output summary including:

  • Generated documents table (Type, Name, Consistency Score, Review Status)
  • Action items (critical discrepancies, undocumented features, flagged items)
  • Next steps checklist

Error Handling

Error Action
Discovery finds nothing Ask user for project structure hints
Generation fails Log failure, continue with other units, report in summary
consistencyScore < 50 Flag for mandatory human review — require explicit human approval
Review rejects after 2 revisions Stop loop, flag for human intervention
该技能用于对代码实现与设计文档的一致性进行合规性及安全性验证。通过编排子代理执行审查,根据结果自动推荐修复路径(代码修复或设计更新),并在发现严重安全问题时阻断流程并上报。
需要检查代码是否符合设计文档规范 需要进行代码安全审计 设计文档与代码不一致需决定修复方向
skills/recipe-review/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-review -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-review",
    "description": "Design Doc compliance and security validation with optional auto-fixes",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Post-implementation quality assurance

Orchestrator Definition

Core Identity: "I am an orchestrator."

First Action: Register Steps 1-11 using TaskCreate before any execution.

Execution Method

  • Compliance validation → performed by code-reviewer
  • Security validation → performed by security-reviewer
  • Code-side fix path: Fix implementation → task-executor; Quality checks → quality-fixer; Re-validation → code-reviewer / security-reviewer
  • Design-side update path: DD revision → technical-designer (update mode); DD review → document-reviewer; cross-DD consistency → design-sync (when multiple DDs exist); Re-validation → code-reviewer

Orchestrator invokes sub-agents and passes structured JSON between them. The design-side path applies when the discrepancy reflects code that was correct but the Design Doc became stale, rather than code that violated the Design Doc.

Design Doc (uses most recent if omitted): $ARGUMENTS

Execution Flow

Step 1: Prerequisite Check

# Identify Design Doc
ls docs/design/*.md | grep -v template | tail -1

# Check implementation files
git diff --name-only main...HEAD

Step 2: Execute code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows:code-reviewer"
  • description: "Code compliance review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review mode: full. Validate Design Doc compliance and return structured JSON report."

Store output as: $STEP_2_OUTPUT

Step 3: Execute security-reviewer

Invoke security-reviewer using Agent tool:

  • subagent_type: "dev-workflows:security-reviewer"
  • description: "Security review"
  • prompt: "Design Doc: [path]. Implementation files: [git diff file list]. Review security compliance."

Store output as: $STEP_3_OUTPUT

Step 4: Verdict and Response

If security-reviewer returned blocked: Stop immediately. Report the blocked finding and escalate to user. Do not proceed to fix steps.

Code compliance criteria (considering project stage):

  • Prototype: Pass at 70%+
  • Production: 90%+ recommended

Security criteria:

  • approved or approved_with_notes → Pass
  • needs_revision → Fail

Report both results independently using subagent output fields only:

Before presenting to the user, the orchestrator computes a recommended route per finding using the rule below (this rule is internal — do not include it in the user-facing prompt):

Finding pattern Recommended route
dd_violation where the code intent matches the original requirement but the Design Doc captured a different design d (Design-side update)
dd_violation where the code drifted from a still-correct Design Doc c (Code-side fix)
reliability / security / maintainability findings c (Code-side fix)

Then present to the user (label each finding with its recommended route, grouped by route):

Code Compliance: [complianceRate from code-reviewer]
  Verdict: [verdict from code-reviewer]
  Identifier Match Rate: [identifierMatchRate from code-reviewer]
  Acceptance Criteria:
  - [fulfilled] [item] (confidence: [high/medium/low])
  - [partially_fulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  - [unfulfilled] [item]: [gap] — [suggestion] [recommended: c | d]
  Identifier Mismatches:
  - [identifier]: DD=[designDocValue] Code=[codeValue] at [location] [recommended: c | d]
  Quality Findings:
  - [category] [location]: [description] — [rationale] [recommended: c]

Security Review: [status from security-reviewer]
  Findings by category:
  - [confirmed_risk] [location]: [description] — [rationale] [recommended: c]
  - [defense_gap] [location]: [description] — [rationale] [recommended: c]
  - [hardening] [location]: [description] — [rationale] [recommended: c]
  - [policy] [location]: [description] — [rationale] [recommended: c]
  Notes: [notes from security-reviewer, if present]

Resolve discrepancies — confirm or override the recommended route per finding:
  c) Code-side fix       — code violates Design Doc; modify code to match
  d) Design-side update  — code is correct; Design Doc is stale, revise it
  s) Skip                — accept current state without changes

Use AskUserQuestion. The default offer is "accept all recommended routes" — a single confirmation for the typical case where the orchestrator's recommendations are correct. When the user wants to override, collect per-finding c/d/s decisions instead. If the user selects s for everything: skip Steps 5-10, proceed to Step 11.

Step 5: Execute Skill

Execute Skill: documentation-criteria (for task file template)

Step 5d: Design-Side Update

Run this step only when the user routed at least one finding to d. When all routes are c or s, skip directly to Step 6.

  1. Invoke technical-designer in update mode using Agent tool:

    • subagent_type: "dev-workflows:technical-designer"
    • description: "Design Doc update from review findings"
    • prompt: "Update Design Doc at [path] in update mode. The implementation has diverged in the following ways that the team has decided to ratify in the design rather than in the code: [list of d-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
  2. Invoke document-reviewer to verify the updated Design Doc:

    • subagent_type: "dev-workflows:document-reviewer"
    • description: "Document review of updated Design Doc"
    • prompt: "Review updated Design Doc at [path] for consistency and completeness."
  3. When multiple Design Docs exist (ls docs/design/*.md | grep -v template | wc -l > 1), invoke design-sync:

    • subagent_type: "dev-workflows:design-sync"
    • description: "Cross-DD consistency check"
    • prompt: "source_design: [updated DD path]. Detect conflicts across all Design Docs after the update."
    • When sync_status: conflicts_found: present conflicts to the user; resolution requires re-invoking technical-designer for affected DDs.
  4. After Step 5d completes:

    • If the user selected d for all findings (no c routes) → skip Steps 6-8, proceed to Step 9 for re-validation
    • If the user selected both d and c → re-evaluate the c-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remaining c findings

Step 6: Create Task File

Create task file at docs/plans/tasks/review-fixes-YYYYMMDD.md Include both code compliance issues and security requiredFixes.

Step 7: Execute Fixes

Invoke task-executor using Agent tool:

  • subagent_type: "dev-workflows:task-executor"
  • description: "Execute review fixes"
  • prompt: "Task file: docs/plans/tasks/review-fixes-YYYYMMDD.md. Apply staged fixes (stops at 5 files)."

Step 8: Quality Check

Invoke quality-fixer using Agent tool:

  • subagent_type: "dev-workflows:quality-fixer"
  • description: "Quality gate check"
  • prompt: "Confirm quality gate passage for fixed files."

Step 9: Re-validate code-reviewer

Invoke code-reviewer using Agent tool:

  • subagent_type: "dev-workflows:code-reviewer"
  • description: "Re-validate compliance"
  • prompt: "Re-validate Design Doc compliance after fixes. Prior compliance issues: $STEP_2_OUTPUT. Verify each prior issue is resolved (whether resolved code-side or design-side)."

Step 10: Re-validate security-reviewer

Invoke security-reviewer using Agent tool (only if security fixes were applied):

  • subagent_type: "dev-workflows:security-reviewer"
  • description: "Re-validate security"
  • prompt: "Re-validate security after fixes. Prior findings: $STEP_3_OUTPUT. Design Doc: [path]. Implementation files: [file list]."

Step 11: Final Cleanup and Report

Delete the review-fix task file this recipe created (if any). Its work is committed; docs/plans/ is ephemeral working state and is not retained between recipe runs:

  • Delete docs/plans/tasks/review-fixes-YYYYMMDD.md if it exists

If the file cannot be deleted (filesystem error), report the failure but do not block the final report.

Then present the final report:

Code Compliance:
  Initial: [X]%
  Final: [Y]% (if fixes executed)

Security Review:
  Initial: [status]
  Final: [status] (if fixes executed)
  Notes: [notes from approved_with_notes, if any]

Remaining issues:
- [items requiring manual intervention]

Cleanup: review-fixes task file removed

Auto-fixable Items (code-side path)

  • Simple unimplemented acceptance criteria
  • Error handling additions
  • Contract definition fixes
  • Function splitting (length/complexity improvements)
  • Security confirmed_risk and defense_gap fixes (input validation, auth checks, output encoding)

Non-fixable Items

  • Fundamental business logic changes
  • Architecture-level modifications
  • Committed secrets (blocked → human intervention)

Design-Side Update Triggers

Discrepancies suitable for the design-side path (code is correct, DD became stale):

  • Identifier renames where the new identifier reflects the team's current naming
  • Behavioral changes that match the original requirement intent better than what the DD captured
  • Component splits or merges where the new structure is sound and the DD documented the prior structure
  • New ACs that the implementation already satisfies but the DD never enumerated

Scope: Design Doc compliance validation, security review, code-side auto-fixes, and design-side update routing.

Scope Boundary for Subagents

Append the following block to every subagent prompt invoked from this recipe:

Scope boundary for subagents:
Operate within the review scope and referenced files in the prompt.
Use loaded skills to execute that scope.
Escalate when the required fix or investigation falls outside that scope.
该技能用于指导智能体执行任务,通过调用rule-advisor进行元认知分析和规则选择,生成结构化任务列表并遵循特定规范实施,确保高质量交付。
需要执行复杂任务时 编写Agent提示词或工件前
skills/recipe-task/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-task -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-task",
    "description": "Execute tasks following appropriate rules with rule-advisor metacognition",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Task Execution with Metacognitive Analysis

Task: $ARGUMENTS

Mandatory Execution Process

Step 1: Rule Selection via rule-advisor (REQUIRED)

Invoke rule-advisor using Agent tool:

  • subagent_type: "dev-workflows:rule-advisor"
  • description: "Rule selection"
  • prompt: "Task: $ARGUMENTS. Select appropriate rules and perform metacognitive analysis."

Step 2: Utilize rule-advisor Output

After receiving rule-advisor's JSON response, proceed with:

  1. Understand Task Essence (from taskAnalysis.essence)

    • Focus on fundamental purpose, not surface-level work
    • Distinguish between "quick fix" vs "proper solution"
  2. Follow Selected Rules (from selectedRules)

    • Review each selected rule section
    • Apply concrete procedures and guidelines
  3. Recognize Past Failures (from metaCognitiveGuidance.pastFailures)

    • Apply countermeasures for known failure patterns
    • Use suggested alternative approaches
  4. Execute First Action (from metaCognitiveGuidance.firstStep)

    • Start with recommended action
    • Use suggested tools first

Step 3: Create Task List with TaskCreate

Register work steps using TaskCreate. Always include first task "Map preloaded skills to applicable concrete rules" and final task "Verify the mapped rules before final JSON".

Break down the task based on rule-advisor's guidance:

  • Reflect taskAnalysis.essence in task descriptions
  • Apply metaCognitiveGuidance.firstStep to first task
  • Restructure tasks considering warningPatterns
  • Set priorities based on dependency order and warningPatterns severity

Step 4: Execute Implementation

Proceed with task execution following:

  • Start with metaCognitiveGuidance.firstStep action from rule-advisor
  • Update task structure with TaskUpdate to reflect rule-advisor insights
  • Selected rules from rule-advisor
  • Task structure (managed via TaskCreate/TaskUpdate)
  • Quality standards defined in the selectedRules output from rule-advisor
  • Monitor warningPatterns flags throughout execution and adjust approach when triggered
用于更新现有设计文档(Design Doc/PRD/ADR)。通过识别目标文档、明确变更内容,调用对应子代理执行更新,并经过代码验证、文档审查及一致性检查等多重质量门禁,最终在获得用户批准后完成更新流程。
需要修改现有的设计文档、产品需求文档或架构决策记录 对已存在的文档进行基于评审意见的迭代更新
skills/recipe-update-doc/SKILL.md
npx skills add shinpr/claude-code-workflows --skill recipe-update-doc -g -y
SKILL.md
Frontmatter
{
    "name": "recipe-update-doc",
    "description": "Update existing design documents (Design Doc \/ PRD \/ ADR) with review",
    "disable-model-invocation": true
}

Execute Skill: llm-friendly-context before writing Agent prompts, handoffs, or generated artifacts.

Context: Dedicated to updating existing design documents.

Orchestrator Definition

Core Identity: "I am an orchestrator." (see subagents-orchestration-guide skill)

First Action: Register Steps 1-6 using TaskCreate before any execution.

Execution Protocol:

  1. Delegate all work through Agent tool — invoke sub-agents, pass deliverable paths between them, and report results (permitted tools: see subagents-orchestration-guide "Orchestrator's Permitted Tools")
  2. Execute update flow:
    • Identify target → Clarify changes → Update document → Review → Consistency check
    • Stop at every [Stop: ...] marker → Wait for user approval before proceeding
  3. Scope: Complete when updated document receives approval

CRITICAL: Execute document-reviewer and all stopping points — each serves as a quality gate for document accuracy.

Workflow Overview

Target document → [Stop: Confirm changes]
                        ↓
              technical-designer / technical-designer-frontend / prd-creator (update mode)
                        ↓ (Design Doc only)
              code-verifier → document-reviewer → [Stop: Review approval]
                        ↓ (Design Doc only)
              design-sync → [Stop: Final approval]

Scope Boundaries

Included in this skill:

  • Existing document identification and selection
  • Change content clarification with user
  • Document update with appropriate agent (update mode)
  • Document review with document-reviewer
  • Consistency verification with design-sync (Design Doc only)

Out of scope (redirect to appropriate skills):

  • New requirement analysis
  • Work planning or implementation

Responsibility Boundary: This skill completes with updated document approval.

Target document: $ARGUMENTS

Execution Flow

Step 1: Target Document Identification

# Check existing documents
ls docs/design/*.md docs/prd/*.md docs/adr/*.md 2>/dev/null | grep -v template

Decision flow:

Situation Action
$ARGUMENTS specifies a path Use specified document
$ARGUMENTS describes a topic Search documents matching the topic
Multiple candidates found Present options with AskUserQuestion
No documents found Report and end (document creation is out of scope)

Step 2: Document Type and Layer Determination

Determine type from document path, then determine the layer to select the correct update agent:

Path Pattern Type Update Agent Notes
docs/design/*.md Design Doc technical-designer or technical-designer-frontend See layer detection below
docs/prd/*.md PRD prd-creator -
docs/adr/*.md ADR technical-designer or technical-designer-frontend See layer detection below

Layer detection (for Design Doc and ADR): Read the document and determine its layer from content signals:

  • Frontend (→ technical-designer-frontend): Document title/scope mentions React, components, UI, frontend; or file contains component hierarchy, state management, UI interactions
  • Backend (→ technical-designer): All other cases (API, data layer, business logic, infrastructure)

ADR Update Guidance:

  • Minor changes (clarification, typo fix, small scope adjustment): Update the existing ADR file
  • Major changes (decision reversal, significant scope change): Create a new ADR that supersedes the original

Step 3: Change Content Clarification [Stop]

Use AskUserQuestion to clarify what changes are needed:

  • What sections need updating
  • Reason for the change (bug fix findings, spec change, review feedback, etc.)
  • Expected outcome after the update

Confirm understanding of changes with user before proceeding.

Step 4: Document Update

Invoke the update agent determined in Step 2:

subagent_type: [Update Agent from Step 2]
description: "Update [Type from Step 2]"
prompt: |
  Operation Mode: update
  Existing Document: [path from Step 1]

  ## Changes Required
  [Changes clarified in Step 3]

  Update the document to reflect the specified changes.
  Add change history entry.

Step 5: Document Review [Stop]

For Design Doc updates only: Before document-reviewer, invoke code-verifier:

subagent_type: code-verifier
description: "Verify updated Design Doc"
prompt: |
  doc_type: design-doc
  document_path: [path from Step 1]
  Verify the updated Design Doc against current codebase.

  Verification focus: Pay special attention to literal identifier referential
  integrity in the updated sections (paths, endpoints, type names, config keys).

Store output as: $CODE_VERIFICATION_OUTPUT

Invoke document-reviewer:

subagent_type: document-reviewer
description: "Review updated document"
prompt: |
  Review the following updated document.

  doc_type: [Design Doc / PRD / ADR]
  target: [path from Step 1]
  mode: standard
  code_verification: $CODE_VERIFICATION_OUTPUT (Design Doc only, omit for PRD/ADR)

  Focus on:
  - Consistency of updated sections with rest of document
  - No contradictions introduced by changes
  - Completeness of change history

Store output as: $STEP_5_OUTPUT

On review result:

  • Approved → Proceed to Step 6
  • Needs revision → Return to Step 4 with the following prompt (max 2 iterations):
    subagent_type: [Update Agent from Step 2]
    description: "Revise [Type from Step 2]"
    prompt: |
      Operation Mode: update
      Existing Document: [path from Step 1]
    
      ## Review Feedback to Address
      $STEP_5_OUTPUT
    
      Address each issue raised in the review feedback.
    
  • After 2 rejections → Flag for human review, present accumulated feedback to user and end

Present review result to user for approval.

Step 6: Consistency Verification (Design Doc only) [Stop]

Skip condition: Document type is PRD or ADR → Proceed to completion.

For Design Doc, invoke design-sync:

subagent_type: design-sync
description: "Verify consistency"
prompt: |
  Verify consistency of the updated Design Doc with other design documents.

  Updated document: [path from Step 1]

On consistency result:

  • No conflicts → Present result to user for final approval
  • Conflicts detected → Present conflicts to user with AskUserQuestion:
    • A: Return to Step 4 to resolve conflicts in this document
    • B: End and address conflicts separately

Error Handling

Error Action
Target document not found Report and end (document creation is out of scope)
Sub-agent update fails Log failure, present error to user, retry once
Review rejects after 2 revisions Stop loop, flag for human intervention
design-sync detects conflicts Present to user for resolution decision

Completion Criteria

  • Identified target document
  • Clarified change content with user
  • Updated document with appropriate agent (update mode)
  • Executed code-verifier before document-reviewer (Design Doc only)
  • Executed document-reviewer and addressed feedback
  • Executed design-sync for consistency verification (Design Doc only)
  • Obtained user approval for updated document

Output Example

Document update completed.

  • Updated document: docs/design/[document-name].md
  • Approval status: User approved
指导多智能体协作与工作流程编排。通过需求分析器评估规模,分配任务给专业子代理(如代码、UI、测试等),并监控范围变更以重启流程,实现自动化执行与质量控制。
需要协调多个子代理完成任务时 管理复杂的工作流阶段 确定自主执行模式
skills/subagents-orchestration-guide/SKILL.md
npx skills add shinpr/claude-code-workflows --skill subagents-orchestration-guide -g -y
SKILL.md
Frontmatter
{
    "name": "subagents-orchestration-guide",
    "description": "Guides subagent coordination through implementation workflows. Use when orchestrating multiple agents, managing workflow phases, or determining autonomous execution mode."
}

Subagents Orchestration Guide

Role: The Orchestrator

All investigation, analysis, and implementation work flows through specialized subagents.

First Action Rule

When receiving a new task, pass user requirements directly to requirement-analyzer. Determine the workflow based on its scale assessment result.

Requirement Change Detection During Flow

During flow execution, monitor user responses for scope-expanding signals:

  • Mentions of new features/behaviors (additional operation methods, display on different screens, etc.)
  • Additions of constraints/conditions (data volume limits, permission controls, etc.)
  • Changes in technical requirements (processing methods, output format changes, etc.)

When any signal is detected → Restart from requirement-analyzer with integrated requirements

Available Subagents

Implementation support:

  1. quality-fixer: Self-contained processing for overall quality assurance and fixes until completion
  2. task-decomposer: Appropriate task decomposition of work plans
  3. task-executor: Individual task execution and structured response
  4. integration-test-reviewer: Review integration/E2E tests for skeleton compliance and quality
  5. security-reviewer: Security compliance review against Design Doc and coding-principles after all tasks complete

Document creation: 6. requirement-analyzer: Requirement analysis and work scale determination 7. codebase-analyzer: Analyze existing codebase to produce focused guidance for technical design (data, contracts, dependencies, quality assurance mechanisms) 8. ui-analyzer: Read the project's external-resources file, fetch external UI sources (design origin, design system, guidelines) via MCP/URL/file, and analyze existing UI code. Frontend/fullstack features; runs in parallel with codebase-analyzer. Uses disallowedTools to inherit MCP access 9. prd-creator: Product Requirements Document creation 10. ui-spec-designer: UI Specification creation from PRD and optional prototype code (frontend/fullstack features) 11. technical-designer: ADR/Design Doc creation 12. work-planner: Work plan creation from Design Doc and test skeletons 13. document-reviewer: Single document quality and rule compliance check 14. code-verifier: Verify document-code consistency. Pre-implementation: Design Doc claims against existing codebase. Post-implementation: implementation against Design Doc 15. design-sync: Design Doc consistency verification across multiple documents 16. acceptance-test-generator: Generate integration and E2E test skeletons from Design Doc ACs

Orchestration Principles

Delegation Boundary: What vs How

The orchestrator passes what to accomplish and where to work. Each specialist determines how to execute autonomously.

Pass to specialists (what/where/constraints):

  • Target directory, package, or file paths
  • Task file path or scope description
  • Acceptance criteria and hard constraints from the user or design artifacts

Let specialists determine (how):

  • Specific commands to run (specialists discover these from project configuration and repo conventions)
  • Execution order and tool flags
  • Which files to inspect or modify within the given scope
Bad (orchestrator prescribes how) Good (orchestrator passes what)
quality-fixer "Run these checks: 1. lint 2. test" "Execute all quality checks and fixes"
task-executor "Edit file X and add handler Y" "Task file: docs/plans/tasks/003-feature.md"

Decision precedence when outputs conflict:

  1. User instructions (explicit requests or constraints)
  2. Task files and design artifacts (Design Doc, PRD, work plan)
  3. Objective repo state (git status, file system, project configuration)
  4. Specialist judgment

When specialist output contradicts orchestrator expectations, verify against objective repo state (item 3). If repo state confirms the specialist, follow the specialist. Override specialist output only when it conflicts with items 1 or 2.

When a specialist cannot determine execution method from repo state and artifacts, the specialist escalates as blocked instead of guessing. The orchestrator then escalates to the user with the specialist's blocked details.

Task Assignment with Responsibility Separation

Assign work based on each subagent's responsibilities:

What to delegate to task-executor:

  • Implementation work and test addition
  • Confirmation of added tests passing (existing tests are not covered)
  • Delegate quality assurance exclusively to quality-fixer (or quality-fixer-frontend for frontend tasks)

What to delegate to quality-fixer:

  • Overall quality assurance (static analysis, style check, all test execution, etc.)
  • Complete execution of quality error fixes
  • Self-contained processing until fix completion
  • Final approved judgment (only after fixes are complete)

Constraints Between Subagents

Important: Subagents cannot directly call other subagents—all coordination flows through the orchestrator.

Explicit Stop Points

Autonomous execution MUST stop and wait for user input at these points. Use AskUserQuestion to present confirmations and questions.

Phase Stop Point User Action Required
Requirements After requirement-analyzer completes Confirm requirements / Answer questions
PRD After document-reviewer completes PRD review Approve PRD
UI Spec After document-reviewer completes UI Spec review (frontend/fullstack) Approve UI Spec
ADR After document-reviewer completes ADR review (if ADR created) Approve ADR
Design After design-sync completes consistency verification Approve Design Doc
Work Plan After work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) or work-planner (Small) completes Batch approval for implementation phase

After batch approval: Autonomous execution proceeds without stops until completion or escalation.

Scale Determination and Document Requirements

Scale File Count PRD ADR Design Doc Work Plan
Small 1-2 Update※1 Not needed Not needed Simplified
Medium 3-5 Update※1 Conditional※2 Required Required
Large 6+ Required※3 Conditional※2 Required Required

※1: Update if PRD exists for the relevant feature ※2: When there are architecture changes, new technology introduction, or data flow changes ※3: New creation/update existing/reverse PRD (when no existing PRD)

How to Call Subagents

Execution Method

Each subagent invocation is a fresh Agent tool call, isolating each phase's context; a SendMessage resume reuses the prior agent's context and breaks that isolation. Each call uses:

  • subagent_type: Agent name (e.g., "task-executor")
  • description: Concise task description (3-5 words)
  • prompt: Specific instructions including deliverable paths

Orchestrator's Permitted Tools

The orchestrator coordinates work using only the following tools:

Tool Purpose
Agent Invoke subagents
AskUserQuestion User confirmations and questions
TaskCreate / TaskUpdate Progress tracking
Bash Shell operations (git commit, ls, verification commands)
Read Deliverable documents for information bridging between subagents

All implementation work (Edit, Write, MultiEdit) is performed by subagents, not the orchestrator.

Prompt Construction Rule

Every subagent prompt must include:

  1. Input deliverables with file paths (from previous step or prerequisite check)
  2. Expected action (what the agent should do)

Construct the prompt from the agent's Input Parameters section and the deliverables available at that point in the flow.

Two additional rules:

  • Subagents see only the Agent prompt and files they read. Include required paths, prior JSON, parameters, and scope constraints explicitly.
  • Replace every [placeholder] in examples below with concrete values before invoking the Agent tool.

Call Example (requirement-analyzer)

  • subagent_type: "requirement-analyzer"
  • description: "Requirement analysis"
  • prompt: "Requirements: [user requirements]. Context: [any relevant context]. Perform requirement analysis and scale determination."

Call Example (codebase-analyzer)

  • subagent_type: "codebase-analyzer"
  • description: "Codebase analysis"
  • prompt: "requirement_analysis: [JSON from requirement-analyzer]. prd_path: [path if exists]. requirements: [original user requirements]. Analyze the existing codebase and produce design guidance."

Call Example (ui-analyzer)

  • subagent_type: "ui-analyzer"
  • description: "UI fact gathering"
  • prompt: "requirement_analysis: [JSON from requirement-analyzer]. requirements: [original user requirements]. ui_spec_path: [path if exists]. target_components: [list if focused]. Read docs/project-context/external-resources.md, fetch external UI sources via the declared access methods (MCP / URL / file), and analyze the existing UI codebase. Output the consolidated UI fact JSON."

When invoked alongside codebase-analyzer for frontend or fullstack-frontend work, run both agents in parallel and pass both JSON outputs to consumers (ui-spec-designer for the design phase; technical-designer-frontend for the Design Doc phase).

Call Example (task-executor)

  • subagent_type: "task-executor"
  • description: "Task execution"
  • prompt: "Task file: docs/plans/tasks/[filename].md Please complete the implementation"

Structured Response Specification

Subagents respond in JSON format. Key fields for orchestrator decisions:

  • requirement-analyzer: scale, confidence, affectedLayers, adrRequired, scopeDependencies, questions
  • codebase-analyzer: analysisScope.categoriesDetected, dataModel.detected, qualityAssurance (mechanisms[], domainConstraints[]), focusAreas[], existingElements count, limitations
  • ui-analyzer: analysisScope.uiConventions, externalResources (designOrigin/designSystem/guidelines/visualVerification with fetch_status), componentStructure[], propsPatterns[], cssLayout[], stateDisplay[], displayConditions[], i18n, accessibility[], generatedArtifacts[], focusAreas[] (raw fact_id; consumers apply ui: prefix when merging with codebase analysis facts), candidateWriteSet[] (with confidence labels), limitations
  • code-verifier: status (consistent/mostly_consistent/needs_review/inconsistent), consistencyScore, discrepancies[], reverseCoverage (including dataOperationsInCode, testBoundariesSectionPresent). Pre-implementation: verifies Design Doc claims against existing codebase. Post-implementation: verifies implementation consistency against Design Doc (pass code_paths scoped to changed files)
  • task-executor: status (escalation_needed/completed), escalation_type (design_compliance_violation/similar_function_found/investigation_target_not_found/out_of_scope_file/dependency_version_uncertain/binding_decision_violation/test_environment_not_ready), testsAdded, requiresTestReview
  • quality-fixer: Input: task_file (path to current task file — always pass this in orchestrated flows). Status: approved/stub_detected/blocked. stub_detected → route back to task-executor with incompleteImplementations[] details for completion, then re-run quality-fixer. blocked → discriminate by reason field: "Cannot determine due to unclear specification" → read blockingIssues[] for specification details; "Execution prerequisites not met" → read missingPrerequisites[] with resolutionSteps — present these to the user as actionable next steps
  • document-reviewer: verdict.decision (approved/approved_with_conditions/needs_revision/rejected)
  • design-sync: sync_status (synced/conflicts_found)
  • integration-test-reviewer: status (approved/needs_revision/blocked), requiredFixes
  • security-reviewer: status (approved/approved_with_notes/needs_revision/blocked), findings, notes, requiredFixes
  • acceptance-test-generator: status, generatedFiles.{integration,fixtureE2e,serviceE2e} (path|null per lane), budgetUsage per lane, e2eAbsenceReason per E2E lane (null when emitted; reason enum is owned by acceptance-test-generator and integration-e2e-testing skill)

Handling Requirement Changes

Handling Requirement Changes in requirement-analyzer

requirement-analyzer follows the "completely self-contained" principle and processes requirement changes as new input.

How to Integrate Requirements

Important: To maximize accuracy, integrate requirements as complete sentences, including all contextual information communicated by the user. Result format: raw concatenation of all requirements, followed by a labeled summary (Initial requirement: … / Additional requirement: …).

Update Mode for Document Generation Agents

Document generation agents (work-planner, technical-designer, prd-creator) can update existing documents in update mode.

  • Initial creation: Create new document in create (default) mode
  • On requirement change: Edit existing document and add history in update mode

Criteria for timing when to call each agent:

  • work-planner: Request updates only before execution
  • technical-designer: Request updates according to design changes → Execute document-reviewer for consistency check
  • prd-creator: Request updates according to requirement changes → Execute document-reviewer for consistency check
  • document-reviewer: Always execute before user approval after PRD/ADR/Design Doc creation/update, and after Work Plan creation/update at Medium/Large scale (Small uses a simplified plan with no semantic review — no Design Doc to trace against)

Basic Flow: Planning and Implementation

Always start with requirement-analyzer, then select the minimum planning flow required by scale and affected layers.

Planning flow (per scale)

Scale Planning flow (ends at task-decomposer for Medium/Large; ends at work-planner for Small)
Large requirement-analyzer → PRD → PRD review → external resource hearing → optional ADR → codebase-analyzer (+ ui-analyzer in parallel for frontend/fullstack) → optional UI Spec → Design Doc → code-verifier → document-reviewer → design-sync → acceptance-test-generator → work-planner → work plan review (document-reviewer, doc_type WorkPlan) → task-decomposer
Medium requirement-analyzer → external resource hearing → codebase-analyzer (+ ui-analyzer in parallel for frontend/fullstack) → optional UI Spec → optional ADR → Design Doc → code-verifier → document-reviewer → design-sync → acceptance-test-generator → work-planner → work plan review (document-reviewer, doc_type WorkPlan) → task-decomposer
Small requirement-analyzer → work-planner

External resource hearing runs in the orchestrator (it requires AskUserQuestion). ui-analyzer joins codebase-analyzer in parallel only when the work has a frontend surface; for backend-only work the planning flow uses codebase-analyzer alone.

After the planning flow completes and the user grants batch approval, implementation proceeds. Verifying the plan is implementable end-to-end (verification lanes, fixtures, E2E environment) is an optional preflight the user runs at their discretion via the recipe-prepare-implementation recipe; this guide does not invoke any orchestrator above the agent layer.

Then execute the task execution cycle: task-executor → quality-fixer → commit for each task. See "Autonomous Execution Mode" below for full per-task details. At Small scale this cycle still applies — implementation runs through task-executor, not orchestrator-direct edits.

Each agent name in the chain is invoked via the Agent tool (per "Orchestrator's Permitted Tools" above).

Rules:

  • Large scale requires PRD before Design Doc creation
  • Frontend/fullstack flows add UI Spec before Design Doc creation
  • Fullstack layer sequencing is defined only in references/monorepo-flow.md
  • design-sync is required whenever multiple Design Docs exist
  • task-decomposer begins only after work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) and batch approval
  • Work plan review self-heals: on verdict.decision needs_revision, route back to work-planner (update) and re-review until approved/approved_with_conditions; rejected escalates to the user. The work plan is a derivation of the Design Doc, so plan-fidelity findings need no user adjudication

Autonomous Execution Mode

Pre-Execution Environment Check

Principle: Verify subagents can complete their responsibilities

Required environments:

  • Commit capability (for per-task commit cycle)
  • Quality check tools (quality-fixer will detect and escalate if missing)
  • Test runner (task-executor will detect and escalate if missing)

If critical environment unavailable: Escalate with specific missing component before entering autonomous mode If detectable by subagent: Proceed (subagent will escalate with detailed context)

Authority Delegation

After environment check passes:

  • Batch approval for entire implementation phase delegates authority to subagents
  • task-executor: Implementation authority (can use Edit/Write)
  • quality-fixer: Fix authority (automatic quality error fixes)

Definition of Autonomous Execution Mode

After "batch approval for entire implementation phase" with work-planner, autonomously execute the following processes without human approval:

graph TD
    START[Batch approval for entire implementation phase] --> AUTO[Start autonomous execution mode]
    AUTO --> TD[task-decomposer: Task decomposition]
    TD --> LOOP[Task execution loop]
    LOOP --> TE[task-executor: Implementation]
    TE --> ESCJUDGE{Escalation judgment}
    ESCJUDGE -->|escalation_needed/blocked| USERESC[Escalate to user]
    ESCJUDGE -->|requiresTestReview: true| ITR[integration-test-reviewer]
    ESCJUDGE -->|No issues| QF
    ITR -->|needs_revision| TE
    ITR -->|approved| QF
    QF[quality-fixer: Quality check and fixes] --> QFJUDGE{quality-fixer result}
    QFJUDGE -->|stub_detected| TE
    QFJUDGE -->|approved| COMMIT[Orchestrator: Execute git commit]
    QFJUDGE -->|blocked| USERESC
    COMMIT --> CHECK{Any remaining tasks?}
    CHECK -->|Yes| LOOP
    CHECK -->|No| VERIFY[Post-implementation verification]
    VERIFY --> CV[code-verifier: DD consistency check]
    VERIFY --> SEC[security-reviewer: Security review]
    CV --> VRESULT{Verification results}
    SEC --> VRESULT
    VRESULT -->|All passed| REPORT[Completion report]
    VRESULT -->|Any failed| VFIX[task-executor: Verification fixes]
    VFIX --> QF2[quality-fixer: Quality check]
    QF2 --> REVERIFY[Re-run failed verifiers only]
    REVERIFY --> VRESULT
    VRESULT -->|blocked| USERESC

    LOOP --> INTERRUPT{User input?}
    INTERRUPT -->|None| TE
    INTERRUPT -->|Yes| REQCHECK{Requirement change check}
    REQCHECK -->|No change| TE
    REQCHECK -->|Change| STOP[Stop autonomous execution]
    STOP --> RA[Re-analyze with requirement-analyzer]

Post-Implementation Verification Pass/Fail Criteria

Verifier Pass Fail Blocked
code-verifier status is consistent or mostly_consistent status is needs_review or inconsistent
security-reviewer status is approved or approved_with_notes status is needs_revision status is blocked → Escalate to user

Re-run rule: After fix cycle, re-run only verifiers that returned fail. Verifiers that passed on the previous run are not re-run.

Conditions for Stopping Autonomous Execution

Stop autonomous execution and escalate to user in the following cases:

  1. Escalation from subagent

    • When receiving response with status: "escalation_needed"
    • When receiving response with status: "blocked"
  2. When requirement change detected

    • Any match in requirement change detection checklist
    • Stop autonomous execution and re-analyze with integrated requirements in requirement-analyzer
  3. When work-planner update restriction is violated

    • Requirement changes after task-decomposer starts require overall redesign
    • Restart entire flow from requirement-analyzer
  4. When user explicitly stops

    • Direct stop instruction or interruption

Task Management: 4-Step Cycle

Per-task cycle:

  1. Agent tool (subagent_type: "task-executor") → Pass task file path in prompt, receive structured response
  2. Check task-executor response:
    • status: escalation_needed or blocked → Escalate to user
    • requiresTestReview is true → Execute integration-test-reviewer
      • needs_revision → Return to step 1 with requiredFixes
      • approved → Proceed to step 3
    • Otherwise → Proceed to step 3
  3. quality-fixer → Quality check and fixes. Always pass the current task file path as task_file
    • stub_detected → Return to step 1 with incompleteImplementations[] details
    • blocked → Escalate to user
    • approved → Proceed to step 4
  4. git commit → Execute with Bash (on approved)

Progress Tracking

Register overall phases using TaskCreate. Update each phase with TaskUpdate as it completes.

Main Orchestrator Roles

  1. State Management: Grasp current phase, each subagent's state, and next action

  2. Information Bridging: Data conversion and transmission between subagents

    • Convert each subagent's output to next subagent's input format
    • Always pass deliverables from previous process to next agent
    • Extract necessary information from structured responses
    • Compose commit messages from changeSummary
    • Explicitly integrate initial and additional requirements when requirements change

    Handoff Contracts

    HC-01: requirement-analyzer → codebase-analyzer

    • Pass: requirement_analysis, prd_path (if exists), original user requirements

    HC-02: codebase-analyzer → technical-designer

    • Pass: full codebase-analyzer JSON as additional context
    • Required downstream uses:
      • focusAreas → canonical disposition-target list for the Fact Disposition Table
      • dataModel, dataTransformationPipelines, qualityAssurance → Existing Codebase Analysis / Verification Strategy / Quality Assurance sections

    HC-03: technical-designer → code-verifier

    • Pass: Design Doc path (doc_type: design-doc)
    • Do not pass code_paths; code-verifier discovers scope from the document

    HC-04: code-verifier + codebase-analyzer → document-reviewer

    • Pass: code_verification JSON and the same codebase_analysis JSON previously given to the designer
    • Purpose: reviewer validates both discrepancy integration and Fact Disposition coverage against focusAreas

    HC-05: code-verifier → next-layer technical-designer (fullstack only)

    • Defined only for multi-layer fullstack flow in references/monorepo-flow.md
    • Pass: prior-layer Design Doc path plus prior_layer_verification
    • Use only discrepancies[] as known issues to address or escalate. Do not infer verified claims that are not explicitly present in the verifier output.

    technical-designer → work-planner

    Pass to work-planner: Design Doc path. Work-planner reads the DD template from documentation-criteria skill, scans all DD sections, and extracts technical requirements in these categories:

    • Verification Strategy: Extracted to work plan header (Correctness Proof Method + Early Verification Point)
    • Implementation targets: Components, functions, or data structures to create or modify
    • Connection/switching/registration: Integration points, dependency wiring, switching methods
    • Contract changes and propagation: Interface changes, data contracts, field propagation across boundaries
    • Verification requirements: Verification methods, test boundaries, integration verification points
    • Prerequisite work: Migration steps, security measures, environment setup

    Work-planner produces a Design-to-Plan Traceability table mapping each extracted item to covering task(s). Items without a covering task must be marked as gap with justification. Unjustified gaps are errors. Justified gaps require user confirmation before plan approval.

    HC-06: acceptance-test-generator → work-planner

    Pass to acceptance-test-generator: Design Doc path; UI Spec path (if exists).

    Orchestrator verification: Every non-null generatedFiles.<lane> path exists on disk. For each null lane, e2eAbsenceReason.<lane> is present (intentional absence, not an error).

    Pass to work-planner: integration / fixture-e2e / service-integration-e2e file paths (or null per lane), per-lane absence reasons, plus timing guidance — integration tests are created alongside each phase implementation, fixture-e2e tests are created alongside the UI feature phase, service-integration-e2e tests are executed only in the final phase.

    On error: Escalate to user when status != completed and integration file generation failed unexpectedly. A null E2E lane with a valid absence reason is not an error.

  3. ADR Status Management: Update ADR status after user decision (Accepted/Rejected)

Important Constraints

Recap (defined above): quality-fixer approval before commit; inter-agent communication is JSON; document-reviewer + user approval before proceeding; check next step against work planning flow after approval; resolve conflicts via Decision precedence.

References

  • references/monorepo-flow.md: Fullstack (monorepo) orchestration flow
执行元认知任务分析与技能选择,通过识别任务本质、估算规模及类型,结合标签匹配与隐式依赖关系,从技能索引中筛选并排序最佳技能组合。
判断任务复杂度 选择合适技能 估算工作量规模
skills/task-analyzer/SKILL.md
npx skills add shinpr/claude-code-workflows --skill task-analyzer -g -y
SKILL.md
Frontmatter
{
    "name": "task-analyzer",
    "description": "Performs metacognitive task analysis and skill selection. Use when determining task complexity, selecting appropriate skills, or estimating work scale."
}

Task Analyzer

Provides metacognitive task analysis and skill selection guidance.

Skills Index

See skills-index.yaml for available skills metadata.

Task Analysis Process

1. Understand Task Essence

Identify the fundamental purpose beyond surface-level work:

Surface Work Fundamental Purpose
"Fix this bug" Problem solving, root cause analysis
"Implement this feature" Feature addition, value delivery
"Refactor this code" Quality improvement, maintainability
"Update this file" Change management, consistency

Action: Map the user request to one row in the Surface Work → Fundamental Purpose table above. If no row matches, state the fundamental purpose explicitly before proceeding.

2. Estimate Task Scale

Scale File Count Indicators
Small 1-2 Single function/component change
Medium 3-5 Multiple related components
Large 6+ Cross-cutting concerns, architecture impact

Scale affects skill priority:

  • Scale >= Large → include documentation-criteria and implementation-approach in selectedSkills with priority high
  • Scale = Small → limit selectedSkills to task-type essential skills only (max 3)

3. Identify Task Type

Type Characteristics Key Skills
Implementation New code, features coding-principles, testing-principles
Fix Bug resolution ai-development-guide, testing-principles
Refactoring Structure improvement coding-principles, ai-development-guide
Design Architecture decisions documentation-criteria, implementation-approach
Quality Testing, review testing-principles, integration-e2e-testing

4. Tag-Based Skill Matching

Extract relevant tags from task description and match against skills-index.yaml:

Task: "Implement user authentication with tests"
Extracted tags: [implementation, testing, security]
Matched skills:
  - coding-principles (implementation, security)
  - testing-principles (testing)
  - ai-development-guide (implementation)

5. Implicit Relationships

Consider hidden dependencies:

Task Involves Also Include
Error handling debugging, testing
New features design, implementation, documentation
Performance profiling, optimization, testing
Frontend typescript-rules, test-implement
API/Integration integration-e2e-testing

Output Format

Return structured analysis with skill metadata from skills-index.yaml:

taskAnalysis:
  essence: <string>  # Fundamental purpose identified
  type: <implementation|fix|refactoring|design|quality>
  scale: <small|medium|large>
  estimatedFiles: <number>
  tags: [<string>, ...]  # Extracted from task description

selectedSkills:
  - skill: <skill-name>  # From skills-index.yaml
    priority: <high|medium|low>
    reason: <string>  # Why this skill was selected
    # Pass through metadata from skills-index.yaml
    tags: [...]
    typical-use: <string>
    size: <small|medium|large>
    sections: [...]  # All sections from yaml, unfiltered

Note: Section selection (choosing which sections are relevant) is done after reading the actual SKILL.md files.

Skill Selection Priority

  1. Essential - Directly related to task type
  2. Quality - Testing and quality assurance
  3. Process - Workflow and documentation
  4. Supplementary - Reference and best practices

Metacognitive Question Design

Generate 3-5 questions according to task nature:

Task Type Question Focus
Implementation Design validity, edge cases, performance
Fix Root cause (5 Whys), impact scope, regression testing
Refactoring Current problems, target state, phased plan
Design Requirement clarity, future extensibility, trade-offs

Warning Patterns

Detect and flag these patterns:

Pattern Warning Mitigation
Large change detected Pair with implementation-approach Split into phases per strategy
Implementation task detected Pair with testing-principles Apply TDD from start
Error fix requested Pair with ai-development-guide Apply 5 Whys before fixing
Multi-file task without plan Pair with documentation-criteria Create work plan first
指导如何编写单元测试、集成测试及E2E测试。涵盖React组件测试(RTL+Vitest+MSW)和Playwright E2E测试,遵循AAA结构、独立性及规范命名原则。
需要实现单元测试时 需要实现集成测试时 需要实现E2E测试时 进行React组件测试时 使用Playwright进行浏览器级测试时
skills/test-implement/SKILL.md
npx skills add shinpr/claude-code-workflows --skill test-implement -g -y
SKILL.md
Frontmatter
{
    "name": "test-implement",
    "description": "Test implementation patterns and conventions. Use when implementing unit tests, integration tests, or E2E tests, including RTL+Vitest+MSW component testing and Playwright E2E testing."
}

Test Implementation Patterns

Reference Selection

Test Type Reference When to Use
Unit / Integration references/frontend.md Implementing React component tests with RTL + Vitest + MSW
E2E references/e2e.md Implementing browser-level E2E tests with Playwright

Common Principles

AAA Structure

All tests follow Arrange-Act-Assert:

  • Arrange: Set up preconditions and inputs
  • Act: Execute the behavior under test
  • Assert: Verify the expected outcome

Test Independence

  • Each test runs independently without depending on other tests
  • No shared mutable state between tests
  • Deterministic execution — no random or time dependencies without mocking

Naming

  • Test names describe expected behavior from user perspective
  • One test verifies one behavior
提供语言无关的测试原则,涵盖TDD红绿重构循环、覆盖率策略及测试质量要求。指导编写单元测试、集成与E2E测试,遵循AAA模式与单一断言概念,适用于测试编写、策略设计及代码审查场景。
编写测试用例 设计测试策略 审查测试质量
skills/testing-principles/SKILL.md
npx skills add shinpr/claude-code-workflows --skill testing-principles -g -y
SKILL.md
Frontmatter
{
    "name": "testing-principles",
    "description": "Language-agnostic testing principles including TDD, test quality, coverage standards, and test design patterns. Use when writing tests, designing test strategies, or reviewing test quality."
}

Language-Agnostic Testing Principles

Test-Driven Development (TDD)

The RED-GREEN-REFACTOR Cycle

Always follow this cycle:

  1. RED: Write a failing test first

    • Write the test before implementation
    • Ensure the test fails for the right reason
    • Verify test can actually fail
  2. GREEN: Write minimal code to pass

    • Implement just enough to make the test pass
    • Focus on making it work
  3. REFACTOR: Improve code structure

    • Clean up implementation
    • Eliminate duplication
    • Improve naming and clarity
    • Keep all tests passing
  4. VERIFY: Ensure all tests still pass

    • Run full test suite
    • Check for regressions
    • Validate refactoring didn't break anything

Quality Requirements

Coverage

  • Treat coverage as a diagnostic signal for finding untested areas, not a target — a target gets gamed into trivial tests (Goodhart's Law)
  • Concentrate tests on critical paths, business logic, and behavior whose regression would matter
  • Prioritize meaningful assertions over the coverage number; any CI threshold is the project's config, not a quality goal in itself

Test Characteristics

All tests must be:

  • Independent: No dependencies between tests (see Test Independence Verification for detailed criteria)
  • Reproducible: Same input always produces same output
  • Fast: Unit tests < 100ms each, integration tests < 1s each, full suite < 10 minutes
  • Self-checking: Clear pass/fail without manual verification
  • Timely: Written close to the code they test

Test Types

Unit Tests

Purpose: Test individual components in isolation

Characteristics:

  • Test single function, method, or class
  • Fast execution (milliseconds)
  • No external dependencies
  • Mock external services
  • Majority of your test suite

Integration Tests

Purpose: Test interactions between components

Characteristics:

  • Test multiple components together
  • May include database, file system, or APIs
  • Slower than unit tests
  • Verify contracts between modules
  • Smaller portion of test suite

End-to-End (E2E) Tests

Purpose: Test complete workflows from user perspective

Characteristics:

  • Test entire application stack
  • Simulate real user interactions
  • Slowest test type
  • Fewest in number
  • Highest confidence level

Test Design Principles

AAA Pattern (Arrange-Act-Assert)

Structure every test in three clear phases:

// Arrange: Setup test data and conditions
user = createTestUser()
validator = createValidator()

// Act: Execute the code under test
result = validator.validate(user)

// Assert: Verify expected outcome
assert(result.isValid == true)

Adaptation: Apply this structure using your language's idioms (methods, functions, procedures)

One Assertion Per Concept

  • Test one behavior per test case
  • Multiple assertions OK if testing single concept
  • Split unrelated assertions into separate tests

Example: prefer returns error when email is invalid over validates user.

Descriptive Test Names

Test names should clearly describe:

  • What is being tested
  • Under what conditions
  • What the expected outcome is

Recommended format: "should [expected behavior] when [condition]"

Examples:

test("should return error when email is invalid")
test("should calculate discount when user is premium")
test("should throw exception when file not found")

Adaptation: Follow your project's naming convention (camelCase, snake_case, describe/it blocks)

Test Independence

Setup and Teardown

  • Use setup hooks to prepare test environment
  • Use teardown hooks to clean up resources
  • Keep setup minimal and focused
  • Ensure teardown runs even if test fails

Mocking and Test Doubles

When to Use Mocks

  • Mock external dependencies: APIs, databases, file systems
  • Mock slow operations: Network calls, heavy computations
  • Mock unpredictable behavior: Random values, current time
  • Mock unavailable services: Third-party services

Mocking Principles

  • Mock at boundaries, not internally
  • Keep mocks simple and focused
  • Verify mock expectations when relevant
  • Wrap external libraries/frameworks behind adapters and mock the adapter

Data Layer Testing

Mock Limitations for Data Layer

Mocks validate call patterns but cannot verify data layer correctness. The following pass through undetected with mock-only testing:

  • Schema mismatches (table names, column names, data types)
  • Query correctness (joins, filters, aggregations, grouping)
  • Database constraints (NOT NULL, UNIQUE, foreign keys)
  • Migration drift (schema changes that make code out of sync)

When Mocks Are Appropriate for Data Access

  • Testing business logic that receives data from the data layer (mock the repository, test the service)
  • Testing error handling paths (simulating connection failures, timeouts)
  • Unit tests where data access is a dependency, not the subject under test

When Mocks Are Insufficient for Data Access

  • Testing repository or data access implementations themselves
  • Verifying query correctness (joins, filters, aggregations, grouping)
  • Testing data integrity constraints
  • Testing migration compatibility

Real Database Testing (Environment-Dependent)

Options for verifying data layer correctness against a real database engine:

  • Containerized databases for CI environments
  • In-memory databases for fast feedback (note: dialect differences may mask issues)
  • Dedicated test databases with seed data

The appropriate approach depends on project environment and CI/CD capabilities.

AI-Generated Code and Schema Awareness

  • AI-generated data access code has heightened schema hallucination risk
  • Generated queries may use correct syntax but reference nonexistent schema elements
  • Mock-based tests pass regardless of schema accuracy
  • Mitigation: Design Docs should include explicit schema references so that documented schemas can be cross-checked against data access code during review

Test Quality Practices

Keep Tests Active

  • Fix or delete failing tests: Resolve failures immediately
  • Remove commented-out tests: Fix them or delete entirely
  • Keep tests running: Broken tests lose value quickly
  • Maintain test suite: Refactor tests as needed

Test Helpers and Utilities

  • Create reusable test data builders
  • Extract common setup into helper functions
  • Build test utilities for complex scenarios
  • Share helpers across test files appropriately

What to Test

Focus on Behavior

Test observable behavior, not implementation:

Good: Test that function returns expected output ✓ Good: Test that correct API endpoint is called ✗ Bad: Test that internal variable was set ✗ Bad: Test order of private method calls

Test Public APIs

  • Test through public interfaces
  • Avoid testing private methods directly
  • Test return values, outputs, exceptions
  • Test side effects (database, files, logs)

Test Edge Cases

Always test:

  • Boundary conditions: Min/max values, empty collections
  • Error cases: Invalid input, null values, missing data
  • Edge cases: Special characters, extreme values
  • Happy path: Normal, expected usage

Test Quality Criteria

These criteria ensure reliable, maintainable tests.

Literal Expected Values

  • Use hardcoded literal values in assertions
  • Calculate expected values independently from the implementation
  • If the implementation has a bug, the test catches it through independent verification
  • If expected value equals mock return value unchanged, the test verifies nothing (no transformation occurred)

Result-Based Verification

  • Verify final results and observable outcomes
  • Assert on return values, output data, or system state changes
  • For mock verification, check that correct arguments were passed

Meaningful Assertions

  • Every test must include at least one assertion
  • Assertions must validate observable behavior
  • A test without assertions always passes and provides no value

Appropriate Mock Scope

  • Mock direct external I/O dependencies: databases, HTTP clients, file systems
  • Use real implementations for internal utilities and business logic
  • Over-mocking reduces test value by verifying wiring instead of behavior

Boundary Value Testing

Test at boundaries of valid input ranges:

  • Minimum valid value
  • Maximum valid value
  • Just below minimum (invalid)
  • Just above maximum (invalid)
  • Empty input (where applicable)

Test Independence Verification

Each test must:

  • Create its own test data
  • Not depend on execution order
  • Clean up its own state
  • Pass when run in isolation

Verification Requirements

Before Commit

  • ✓ All tests pass — fix failing tests immediately
  • ✓ No tests skipped or commented — delete or fix
  • ✓ No debug code left in tests
  • ✓ Test coverage meets standards
  • ✓ No flaky tests — make deterministic
  • ✓ Tests run within performance thresholds

Test Organization

File Structure

  • Mirror production structure: Tests follow code organization
  • Clear naming conventions: Follow project's test file patterns
    • Examples: UserService.test.*, user_service_test.*, test_user_service.*, UserServiceTests.*
  • Logical grouping: Group related tests together
  • Separate test types: Unit, integration, e2e in separate directories

Performance Considerations

Test Speed

  • Unit tests: < 100ms each
  • Integration tests: < 1s each
  • Full suite: Should run frequently (< 10 minutes)

Optimization Strategies

  • Run tests in parallel when possible
  • Use in-memory databases for tests
  • Mock expensive operations
  • Split slow test suites
  • Profile and optimize slow tests

Continuous Integration

CI/CD Requirements

  • Run full test suite on every commit
  • Block merges if tests fail
  • Run tests in isolated environments
  • Test on target platforms/versions

Test Reports

  • Generate coverage reports
  • Track test execution time
  • Identify flaky tests
  • Monitor test trends

Test Design Guardrails

Every Test Must

  • Include at least one meaningful assertion
  • Create its own test data and clean up its own state
  • Pass when run in any order and in isolation
  • Test observable behavior through public interfaces
  • Keep test logic simple (no branching, no loops)
  • Mock only external I/O boundaries, use real implementations for internal logic

Flaky Test Resolution

  • Use deterministic time mocking instead of real clocks
  • Use fixed seed values instead of random data
  • Ensure proper resource cleanup in teardown
  • Resolve race conditions with synchronization primitives

Regression Testing

Prevent Regressions

  • Add test for every bug fix
  • Maintain comprehensive test suite
  • Run full suite regularly
  • Keep all tests unless the tested functionality is removed

Legacy Code

  • Add characterization tests before refactoring
  • Test existing behavior first
  • Gradually improve coverage
  • Refactor with confidence

Testing Best Practices by Language Paradigm

Type System Utilization

For languages with static type systems:

  • Leverage compile-time verification for correctness
  • Focus tests on business logic and runtime behavior
  • Use language's type system to prevent invalid states

For languages with dynamic typing:

  • Add comprehensive runtime validation tests
  • Explicitly test data contract validation
  • Consider property-based testing for broader coverage

Programming Paradigm Considerations

Functional approach:

  • Test pure functions thoroughly (deterministic, no side effects)
  • Test side effects at system boundaries
  • Leverage property-based testing for invariants

Object-oriented approach:

  • Test behavior through public interfaces
  • Mock dependencies via abstraction layers
  • Test polymorphic behavior carefully

Common principle: Adapt testing strategy to leverage language strengths while ensuring comprehensive coverage

Documentation and Communication

Tests as Documentation

  • Tests document expected behavior
  • Use clear, descriptive test names
  • Include examples of usage
  • Show edge cases and error handling

Test Failure Messages

  • Provide clear, actionable error messages
  • Include actual vs expected values
  • Add context about what was being tested
  • Make debugging easier
提供React与TypeScript前端开发规范,涵盖类型安全、组件设计、状态管理及代码重构原则。强调消除any类型、使用类型守卫及现代TS特性,指导实现高质量前端代码。
需要制定或遵循React和TypeScript编码规范时 进行前端组件设计与类型安全检查时 处理外部数据输入的类型验证逻辑时
skills/typescript-rules/SKILL.md
npx skills add shinpr/claude-code-workflows --skill typescript-rules -g -y
SKILL.md
Frontmatter
{
    "name": "typescript-rules",
    "description": "React\/TypeScript frontend development rules including type safety, component design, state management, and error handling. Use when implementing React components, TypeScript code, or frontend features."
}

TypeScript Development Rules (Frontend)

Basic Principles

  • Aggressive Refactoring - Prevent technical debt and maintain health
  • Delete code when no current caller exists - YAGNI principle (Kent Beck)

Comment Writing Rules

Code first: names and types carry meaning; a comment must add what code cannot, and one comment per decision is enough. Frontend specifics:

  • Comment intent, not markup: explain why a component memoizes, guards, or re-renders — not what the JSX renders
  • Timeless content only: Record decisions and rationale; leave chronological history to version control

Type Safety

Absolute Rule: Replace every any with unknown, generics, or union types. any disables type checking and causes runtime errors.

any Type Alternatives (Priority Order)

  1. unknown Type + Type Guards: Use for validating external input (API responses, localStorage, URL parameters)
  2. Generics: When type flexibility is needed
  3. Union Types・Intersection Types: Combinations of multiple types
  4. Type Assertions (Last Resort): Only when type is certain

Type Guard Implementation Pattern

function isUser(value: unknown): value is User {
  return typeof value === 'object' && value !== null && 'id' in value && 'name' in value
}

Modern Type Features

  • satisfies Operator: const config = { apiUrl: '/api' } satisfies Config - Preserves inference
  • const Assertion: const ROUTES = { HOME: '/' } as const satisfies Routes - Immutable and type-safe
  • Branded Types: type UserId = string & { __brand: 'UserId' } - Distinguish meaning
  • Template Literal Types: type EventName = \on${Capitalize}`` - Express string patterns with types

Type Safety in Frontend Implementation

  • React Props/State: TypeScript manages types, unknown unnecessary
  • External API Responses: Always receive as unknown, validate with type guards
  • localStorage/sessionStorage: Treat as unknown, validate
  • URL Parameters: Treat as unknown, validate
  • Form Input (Controlled Components): Type-safe with React synthetic events

Type Safety in Data Flow

  • Frontend → Backend: Props/State (Type Guaranteed) → API Request (Serialization)
  • Backend → Frontend: API Response (unknown) → Type Guard → State (Type Guaranteed)

Type Complexity Management

  • Props Design:
    • Props count: 3-7 props ideal (consider component splitting if exceeds 10)
    • Optional Props: 50% or less (consider default values or Context if excessive)
    • Nesting: Up to 2 levels (flatten deeper structures)
  • Type Assertions: Review design if used 3+ times
  • External API Types: Relax constraints and define according to reality (convert appropriately internally)

Coding Conventions

Component Design Criteria

  • Function components only: Official React recommendation, optimizable by modern tooling (Exception: Error Boundary requires class component)
  • Custom Hooks: Standard pattern for logic reuse and dependency injection
  • Component Hierarchy: Use the project's adopted component architecture. When the project uses Atomic Design: Atoms → Molecules → Organisms → Templates → Pages. When the project uses Feature-based, Container-Presenter, or another structure: follow that structure consistently and document the chosen layering in the project README or design doc
  • Co-location: Place tests, styles, and related files alongside components

Server/Client Boundary (RSC frameworks only — e.g., Next.js App Router)

  • Default to server components for data fetching and rendering; isolate interactivity behind a "use client" boundary at the smallest scope that needs it
  • Keep browser-only APIs (window, localStorage, event handlers) inside client components; calling them in a server component breaks the render
  • N/A for client-only SPAs (e.g., Vite) — skip when the project has no server-component runtime

State Management Patterns

  • Local State: useState for component-specific state
  • Context API: For sharing state across component tree (theme, auth, etc.)
  • Custom Hooks: Encapsulate state logic and side effects
  • Server State: React Query or SWR for API data caching

Data Flow Principles

  • Single Source of Truth: Each piece of state has one authoritative source
  • Unidirectional Flow: Data flows top-down via props
  • Immutable Updates: Use immutable patterns for state updates
// Immutable state update — always create new arrays/objects
setUsers(prev => [...prev, newUser])

Function Design

  • 0-2 parameters maximum: Use object for 3+ parameters
    function createUser({ name, email, role }: CreateUserParams) {}
    

Props Design (Props-driven Approach)

  • Props are the interface: Define all necessary information as props
  • Pass all data dependencies as props; use Context only for cross-cutting concerns (theme, auth, locale)
  • Type-safe: Always define Props type explicitly

Environment Variables

  • Use the build tool's env accessor: read client-side env through the bundler's exposed accessor — Vite via import.meta.env, Next.js/CRA via prefixed process.env. Raw, unprefixed access is undefined in the browser bundle
  • Only prefixed vars reach the client: build tools expose only vars carrying their public prefix; an unprefixed var is undefined in the browser. The prefix differs per tool — match the project's bundler (Vite VITE_, Next.js public NEXT_PUBLIC_, CRA REACT_APP_)
  • Centrally manage env through a typed config object with a default for every variable
// Client-exposed env must carry the bundler's public prefix, or it is undefined in the browser.
// Vite:    import.meta.env.VITE_API_URL
// Next.js: process.env.NEXT_PUBLIC_API_URL
const config = {
  apiUrl: import.meta.env.VITE_API_URL || 'http://localhost:3000', // adjust accessor + prefix to the project's bundler
  appName: import.meta.env.VITE_APP_NAME || 'My App'
}

Security (Client-side Constraints)

  • CRITICAL: All frontend code is public and visible in browser
  • All secrets stay server-side: Store API keys, tokens, and secrets on the backend only
  • Exclude .env files via .gitignore
  • Limit error messages to non-sensitive context
// Backend manages secrets, frontend accesses via proxy
const response = await fetch('/api/data') // Backend handles API key authentication

Dependency Injection

  • Custom Hooks for dependency injection: Ensure testability and modularity

Asynchronous Processing

  • Promise Handling: Always use async/await
  • Error Handling: Always handle with try-catch or Error Boundary
  • Type Definition: Explicitly define return value types (e.g., Promise<Result>)
  • Effect race/cleanup: guard useEffect data fetches against out-of-order responses and post-unmount state updates — abort or ignore stale results (AbortController or a mounted flag), or use a server-state library (React Query/SWR) that cancels and dedupes. try-catch alone does not cover this

Format Rules

  • Semicolon omission (follow Biome settings)
  • Types in PascalCase, variables/functions in camelCase
  • Imports use absolute paths (src/)

Clean Code Principles

  • Delete unused code immediately
  • Delete debug console.log()
  • Delete commented-out code (retrieve from version control when needed)
  • Comments explain "why" (not "what")

Error Handling

Absolute Rule: Every caught error must be logged with context and either re-thrown to Error Boundary, returned as a Result error variant, or displayed as user-facing error state.

Fail-Fast Principle: Fail quickly on errors to prevent continued processing in invalid states

catch (error) {
  logger.error('Processing failed', error)
  throw error // Handle with Error Boundary or higher layer
}

Result Type Pattern: Express errors with types for explicit handling

type Result<T, E> = { ok: true; value: T } | { ok: false; error: E }

// Example: Express error possibility with types
function parseUser(data: unknown): Result<User, ValidationError> {
  if (!isValid(data)) return { ok: false, error: new ValidationError() }
  return { ok: true, value: data as User }
}

Custom Error Classes

export class AppError extends Error {
  constructor(message: string, public readonly code: string, public readonly statusCode = 500) {
    super(message)
    this.name = this.constructor.name
  }
}
// Purpose-specific: ValidationError(400), ApiError(502), NotFoundError(404)

Layer-Specific Error Handling (React)

  • Error Boundary: Catch React component errors, display fallback UI
  • Custom Hook: Detect business rule violations, propagate AppError as-is
  • API Layer: Convert fetch errors to domain errors

Structured Logging and Sensitive Information Protection Redact sensitive fields (password, token, apiKey, secret, creditCard) before logging

Asynchronous Error Handling in React

  • Error Boundary setup mandatory: Catch rendering errors
  • Use try-catch with all async/await in event handlers
  • Always log and re-throw errors or display error state

Refactoring Techniques

Basic Policy

  • Small Steps: Maintain always-working state through gradual improvements
  • Safe Changes: Minimize the scope of changes at once
  • Behavior Guarantee: Ensure existing behavior remains unchanged while proceeding

Implementation Procedure: Understand Current State → Gradual Changes → Behavior Verification → Final Validation

Priority: Duplicate Code Removal > Large Function Division > Complex Conditional Branch Simplification > Type Safety Improvement

Performance Optimization

  • Automatic memoization: when React Compiler is enabled, rely on it; reach for manual React.memo/useMemo/useCallback only as a profiler- or identity-justified escape hatch (a measured bottleneck, or stable reference identity for third-party APIs / effect dependencies)
  • State Optimization: Minimize re-renders with proper state structure
  • Lazy Loading: Use React.lazy and Suspense for code splitting
  • Bundle Size: Monitor via the build script against the project's budget

Non-functional Requirements

  • Browser Compatibility: Chrome/Firefox/Safari/Edge (latest 2 versions)
  • Rendering Time: Within 5 seconds for major pages

Accueil - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-07-09 01:41
浙ICP备14020137号-1 $Carte des visiteurs$