shinpr/claude-code-workflows
GitHub提供AI开发技术决策准则、反模式检测及调试技巧。用于识别代码与设计反模式,执行严格的质量检查,并指导基于Fail-Fast原则的错误处理与回退设计,确保系统可靠性。
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)
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
- Writing similar code 3 or more times - Violates Rule of Three
- Multiple responsibilities mixed in a single file - Violates Single Responsibility Principle (SRP)
- Defining same content in multiple files - Violates DRY principle
- Making changes without checking dependencies - Potential for unexpected impacts
- Disabling code with comments - Should use version control
- Error suppression - Hiding problems creates technical debt
- 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:
- Verify Design Doc explicitly defines this fallback
- Document the business justification
- Ensure error is logged with full context
- 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
- Read error message (first line) accurately
- Focus on first and last of stack trace
- 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
- Code Style Checking: Verify adherence to style guidelines
- Code Formatting: Ensure consistent formatting
- Unused Code Detection: Identify dead code and unused imports/variables
- Static Type Checking: Verify type correctness (for statically typed languages)
- Static Analysis: Detect potential bugs, security issues, code smells
Phase 2: Build Verification
- Compilation/Build: Verify code builds successfully (for compiled languages)
- Dependency Resolution: Ensure all dependencies are available and compatible
- Resource Validation: Check configuration files, assets are valid
Phase 3: Testing
- Unit Tests: Run all unit tests
- Integration Tests: Run integration tests
- Test Coverage: Measure and verify coverage meets standards
- 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
- Maintainability over Speed: Prioritize long-term code health over initial development velocity
- Simplicity First: Choose the simplest solution that meets requirements (YAGNI principle)
- 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.
- Explicit over Implicit: Make intentions clear through code structure and naming
- 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
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
- prd-template.md - Product Requirements Document template
- adr-template.md - Architecture Decision Record template
- ui-spec-template.md - UI Specification template (frontend/fullstack features)
- design-template.md - Technical Design Document template
- plan-template.md - Work Plan template
- task-template.md - Task file template for implementation tasks
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:
- Phase 1: Foundation Implementation - Contract definitions, interfaces/signatures, test preparation
- Phase 2: Core Feature Implementation - Business logic, unit tests
- 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:
- Implementation Complete: Code is functional
- Quality Complete: Tests, static checks, linting pass
- Integration Complete: Verified connection with other components
Creation Process
- Problem Analysis: Change scale assessment, ADR condition check
- Identify explicit and implicit project standards before investigation
- ADR Option Consideration (ADR only): Compare 3+ options, specify trade-offs
- Creation: Use templates, include measurable conditions
- 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
Proposed → Accepted → Deprecated/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
- At creation: Identify common technical areas (logging, error handling, async processing, etc.), reference existing common ADRs
- When missing: Consider creating necessary common ADRs
- Design Doc: Specify common ADRs in "Prerequisite ADRs" section
- Compliance check: Verify design aligns with common ADR decisions
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
-
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).
-
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:
- Build the project-tier content from the answers. Use references/template.md as the structure.
- Write to
docs/project-context/external-resources.md. Create the directory if absent. - When the calling workflow has a target UI Spec or Design Doc, also append or update the document's
## External Resources Usedsection with the feature-tier subset (label references + feature-specific identifiers only). - Report the file paths back to the calling workflow.
Reference Protocol (For Downstream Consumers)
Agents that load this skill consult resources in this order:
- Read
docs/project-context/external-resources.mdfirst (if present) to learn what is available and how to access it. - Read the target UI Spec or Design Doc's
## External Resources Usedsection for feature-specific identifiers. - 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
- references/frontend.md — Frontend domain axes
- references/backend.md — Backend domain axes
- references/api.md — API contract domain axes
- references/infra.md — Infrastructure domain axes
- references/template.md — Project-tier and feature-tier structure templates
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
- Writing similar code 3 or more times - Violates Rule of Three
- Multiple responsibilities mixed in a single component - Violates Single Responsibility Principle (SRP)
- Defining same content in multiple components - Violates DRY principle
- Making changes without checking dependencies - Potential for unexpected impacts
- Disabling code with comments - Should use version control
- Error suppression - Hiding problems creates technical debt
- Excessive use of type assertions (as) - Abandoning type safety
- Prop drilling through 3+ levels - Should use Context API or state management
- 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
- Read error message (first line) accurately
- Focus on first and last of stack trace
- Identify first line where your code appears
- 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)
- Lint/format — the project's formatter + linter (e.g., Biome, or ESLint + Prettier)
- Type check — type check without emit
- Build — production build
- Test — unit/integration tests
- 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:
- Selected strategy name and characteristics
- Alternatives considered and reason for rejection
- Risk mitigation plan (from Phase 3)
- Constraint compliance summary (from Phase 4)
- 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
- Verify at least one strategy combination beyond listed patterns was considered
- Confirm Phase 1 analysis framework is complete before selecting strategy
- Confirm Phase 3 risk analysis matrix is populated before implementation starts
- Confirm Phase 4 constraint checklist is reviewed before strategy decision
- Confirm Phase 6 documentation template is filled with selection rationale
Guidelines for Meta-cognitive Execution
- Leverage Known Patterns: Use as starting point, explore creative combinations
- Active WebSearch Use: Research implementation examples from similar tech stacks
- Apply 5 Whys: Pursue root causes to grasp essence
- Multi-perspective Evaluation: Comprehensively evaluate from each Phase 1-4 perspective
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:
- 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)
- State carries across steps — data produced or actions taken in one step affect what the next step accepts or displays
- 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 stateservice-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 undertests/e2e/fixture/) - service-integration-e2e tests:
*.service.e2e.test.*(or organize undertests/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
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
-
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."
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
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
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:
-
RED: Write a failing test first
- Write the test before implementation
- Ensure the test fails for the right reason
- Verify test can actually fail
-
GREEN: Write minimal code to pass
- Implement just enough to make the test pass
- Focus on making it work
-
REFACTOR: Improve code structure
- Clean up implementation
- Eliminate duplication
- Improve naming and clarity
- Keep all tests passing
-
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.*
- Examples:
- 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
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)
- unknown Type + Type Guards: Use for validating external input (API responses, localStorage, URL parameters)
- Generics: When type flexibility is needed
- Union Types・Intersection Types: Combinations of multiple types
- 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:
useStatefor 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 prefixedprocess.env. Raw, unprefixed access isundefinedin the browser bundle - Only prefixed vars reach the client: build tools expose only vars carrying their public prefix; an unprefixed var is
undefinedin the browser. The prefix differs per tool — match the project's bundler (ViteVITE_, Next.js publicNEXT_PUBLIC_, CRAREACT_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
.envfiles 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-catchor Error Boundary - Type Definition: Explicitly define return value types (e.g.,
Promise<Result>) - Effect race/cleanup: guard
useEffectdata fetches against out-of-order responses and post-unmount state updates — abort or ignore stale results (AbortControlleror a mounted flag), or use a server-state library (React Query/SWR) that cancels and dedupes.try-catchalone does not cover this
Format Rules
- Semicolon omission (follow Biome settings)
- Types in
PascalCase, variables/functions incamelCase - 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/useCallbackonly 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.lazyandSuspensefor 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-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
- Writing similar code 3 or more times - Violates Rule of Three
- Multiple responsibilities mixed in a single file - Violates Single Responsibility Principle (SRP)
- Defining same content in multiple files - Violates DRY principle
- Making changes without checking dependencies - Potential for unexpected impacts
- Disabling code with comments - Should use version control
- Error suppression - Hiding problems creates technical debt
- 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:
- Verify Design Doc explicitly defines this fallback
- Document the business justification
- Ensure error is logged with full context
- 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
- Read error message (first line) accurately
- Focus on first and last of stack trace
- 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
- Code Style Checking: Verify adherence to style guidelines
- Code Formatting: Ensure consistent formatting
- Unused Code Detection: Identify dead code and unused imports/variables
- Static Type Checking: Verify type correctness (for statically typed languages)
- Static Analysis: Detect potential bugs, security issues, code smells
Phase 2: Build Verification
- Compilation/Build: Verify code builds successfully (for compiled languages)
- Dependency Resolution: Ensure all dependencies are available and compatible
- Resource Validation: Check configuration files, assets are valid
Phase 3: Testing
- Unit Tests: Run all unit tests
- Integration Tests: Run integration tests
- Test Coverage: Measure and verify coverage meets standards
- 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
- Maintainability over Speed: Prioritize long-term code health over initial development velocity
- Simplicity First: Choose the simplest solution that meets requirements (YAGNI principle)
- 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.
- Explicit over Implicit: Make intentions clear through code structure and naming
- 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
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
- prd-template.md - Product Requirements Document template
- adr-template.md - Architecture Decision Record template
- ui-spec-template.md - UI Specification template (frontend/fullstack features)
- design-template.md - Technical Design Document template
- plan-template.md - Work Plan template
- task-template.md - Task file template for implementation tasks
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:
- Phase 1: Foundation Implementation - Contract definitions, interfaces/signatures, test preparation
- Phase 2: Core Feature Implementation - Business logic, unit tests
- 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:
- Implementation Complete: Code is functional
- Quality Complete: Tests, static checks, linting pass
- Integration Complete: Verified connection with other components
Creation Process
- Problem Analysis: Change scale assessment, ADR condition check
- Identify explicit and implicit project standards before investigation
- ADR Option Consideration (ADR only): Compare 3+ options, specify trade-offs
- Creation: Use templates, include measurable conditions
- 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
Proposed → Accepted → Deprecated/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
- At creation: Identify common technical areas (logging, error handling, async processing, etc.), reference existing common ADRs
- When missing: Consider creating necessary common ADRs
- Design Doc: Specify common ADRs in "Prerequisite ADRs" section
- Compliance check: Verify design aligns with common ADR decisions
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
-
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).
-
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:
- Build the project-tier content from the answers. Use references/template.md as the structure.
- Write to
docs/project-context/external-resources.md. Create the directory if absent. - When the calling workflow has a target UI Spec or Design Doc, also append or update the document's
## External Resources Usedsection with the feature-tier subset (label references + feature-specific identifiers only). - Report the file paths back to the calling workflow.
Reference Protocol (For Downstream Consumers)
Agents that load this skill consult resources in this order:
- Read
docs/project-context/external-resources.mdfirst (if present) to learn what is available and how to access it. - Read the target UI Spec or Design Doc's
## External Resources Usedsection for feature-specific identifiers. - 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
- references/frontend.md — Frontend domain axes
- references/backend.md — Backend domain axes
- references/api.md — API contract domain axes
- references/infra.md — Infrastructure domain axes
- references/template.md — Project-tier and feature-tier structure templates
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
- Writing similar code 3 or more times - Violates Rule of Three
- Multiple responsibilities mixed in a single component - Violates Single Responsibility Principle (SRP)
- Defining same content in multiple components - Violates DRY principle
- Making changes without checking dependencies - Potential for unexpected impacts
- Disabling code with comments - Should use version control
- Error suppression - Hiding problems creates technical debt
- Excessive use of type assertions (as) - Abandoning type safety
- Prop drilling through 3+ levels - Should use Context API or state management
- 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
- Read error message (first line) accurately
- Focus on first and last of stack trace
- Identify first line where your code appears
- 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)
- Lint/format — the project's formatter + linter (e.g., Biome, or ESLint + Prettier)
- Type check — type check without emit
- Build — production build
- Test — unit/integration tests
- 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:
- Selected strategy name and characteristics
- Alternatives considered and reason for rejection
- Risk mitigation plan (from Phase 3)
- Constraint compliance summary (from Phase 4)
- 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
- Verify at least one strategy combination beyond listed patterns was considered
- Confirm Phase 1 analysis framework is complete before selecting strategy
- Confirm Phase 3 risk analysis matrix is populated before implementation starts
- Confirm Phase 4 constraint checklist is reviewed before strategy decision
- Confirm Phase 6 documentation template is filled with selection rationale
Guidelines for Meta-cognitive Execution
- Leverage Known Patterns: Use as starting point, explore creative combinations
- Active WebSearch Use: Research implementation examples from similar tech stacks
- Apply 5 Whys: Pursue root causes to grasp essence
- Multi-perspective Evaluation: Comprehensively evaluate from each Phase 1-4 perspective
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:
- 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)
- State carries across steps — data produced or actions taken in one step affect what the next step accepts or displays
- 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 stateservice-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 undertests/e2e/fixture/) - service-integration-e2e tests:
*.service.e2e.test.*(or organize undertests/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
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
-
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."
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
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 problemmandatoryChecks.taskEssence: Root problem beyond surface symptomsselectedRules: Applicable rule sectionswarningPatterns: Patterns to avoid
0.4 Reflecting in investigator Prompt
Include the following in investigator prompt:
- Problem essence (taskEssence)
- Key applicable rules summary (from selectedRules)
- Investigation focus (investigationFocus): Convert warningPatterns to "points prone to confusion or oversight in this investigation"
- 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):
-
pathMapexists 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,evidencewith asourceciting a specific file or location - Each failure point has
comparisonAnalysis(normalImplementation found or explicitly null) -
causeCategoryfor each failure point is one of: typo / logic_error / missing_constraint / design_gap / external_factor -
investigationSourcescovers at least 3 distinct source types (code, history, dependency, config, document, external) - Investigation covers
investigationFocusitems (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:
- Insert user confirmation before verifier execution
- Use AskUserQuestion:
"A design-level issue was detected. How should we proceed?"
- A: Attempt fix within current design
- B: Include design reconsideration
- If user selects B, pass
includeRedesign: trueto 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:
- Return to Step 1 with unchecked areas identified by verifier as investigation targets
- Maximum 2 additional investigation iterations
- 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
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:
- Delegate to subagents (one-shot calls): ui-analyzer, work-planner, quality-fixer-frontend.
- 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.
- 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).
- Read
candidateWriteSet[]from ui-analyzer output. - 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. - 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):
- Plan the edit based on ui-analyzer focusAreas and the relevant external resource (e.g., design origin's fetched_summary).
- Apply the edit using Edit / Write / MultiEdit on the affected files.
- Verify against external sources using whichever access method
docs/project-context/external-resources.mddeclares 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)
- Refine and re-verify until the adjustment matches the design source, or matches the user-confirmed adjustment target when no separate design source exists.
- 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. PassfilesModified: [list of files edited in this adjustment unit]. - Branch B (3-5 files): pass
task_file: <work plan path>(supplementary hint) ANDfilesModified: [list of files edited in this adjustment unit](primary scope).
- Branch A (1-2 files): omit
- 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 7stub_detected→ return to Step 5 to complete the implementation for this unit, then re-invoke quality-fixer-frontendblocked→ readreason. When"Cannot determine due to unclear specification", surfaceblockingIssues[]to the user and stop. When"Execution prerequisites not met", surfacemissingPrerequisites[]withresolutionStepsto 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
filesModifiedscoping - 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
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:
- 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")
- Follow the 4-step task cycle exactly: task-executor-frontend → escalation check → quality-fixer-frontend → commit
- Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
- 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:
- 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 - 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) - For each remaining file, extract the
{plan-name}prefix as the segment that appears before-task- - When at least one task file matches, the work plan is
docs/plans/{plan-name}.mdfor the prefix that has the most recent task-file mtime; ties broken by the lexicographically last{plan-name} - When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template
.mdindocs/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:
- List task files in
docs/plans/tasks/matching the single-layer pattern{plan-name}-task-*.mdfor the{plan-name}resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded - 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:
- 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"
- Agent tool (subagent_type: "dev-workflows-frontend:task-executor-frontend") → Pass task file path in prompt, receive structured response
- CHECK task-executor-frontend response:
status: "escalation_needed"or"blocked"→ STOP and escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 2 withrequiredFixesapproved→ Proceed to step 4
readyForQualityCheck: true→ Proceed to step 4
- INVOKE quality-fixer-frontend: Execute all quality checks and fixes. Always pass the current task file path as
task_file - CHECK quality-fixer-frontend response:
stub_detected→ Return to step 2 withincompleteImplementations[]detailsblocked→ STOP and escalate to userapproved→ Proceed to step 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:
-
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
- code-verifier (subagent_type: "dev-workflows-frontend:code-verifier") →
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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}.mdif 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
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:
- 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.
- 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
- 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:
- Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
- Search the repository with Bash (
rg, orgrepwhenrgis unavailable) for files matching those keywords. - Collect the matched file paths as the seed
affectedFiles. - When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as
affectedFilesbefore 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. - 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
affectedFilesbefore 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: includerequirements: the user requirements verbatimrequirement_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.filesAnalyzedand the modules they belong to - Affected layers: layers touched, derived from
analysisScope.categoriesDetectedandfocusAreas - Unknowns/assumptions:
limitationsplus 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: includerequirements: the user requirementsrequirement_analysis: a JSON object with all four fields —affectedFiles(analysisScope.filesAnalyzedfrom 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
- Source: an existing PRD in
- 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."
- For ADR:
- (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:
- Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
- Follow subagents-orchestration-guide skill planning flow:
- Execute steps defined below
- Stop and obtain approval for plan content before completion
- 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]."
- Invoke acceptance-test-generator using Agent tool:
- 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.])"
- When
- 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: onneeds_revision, re-invoke work-planner in update mode with the findings and re-review, repeating untilapprovedorapproved_with_conditions. Onrejected, 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.
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:
approvedorapproved_with_notes→ Passneeds_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.
-
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 ofd-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
-
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."
-
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.
-
After Step 5d completes:
- If the user selected
dfor all findings (nocroutes) → skip Steps 6-8, proceed to Step 9 for re-validation - If the user selected both
dandc→ re-evaluate thec-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remainingcfindings
- If the user selected
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.mdif 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-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:
-
Understand Task Essence (from
taskAnalysis.essence)- Focus on fundamental purpose, not surface-level work
- Distinguish between "quick fix" vs "proper solution"
-
Follow Selected Rules (from
selectedRules)- Review each selected rule section
- Apply concrete procedures and guidelines
-
Recognize Past Failures (from
metaCognitiveGuidance.pastFailures)- Apply countermeasures for known failure patterns
- Use suggested alternative approaches
-
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.essencein task descriptions - Apply
metaCognitiveGuidance.firstStepto 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.firstStepaction 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
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:
- 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")
- Execute update flow:
- Identify target → Clarify changes → Update document → Review → Consistency check
- Stop at every
[Stop: ...]marker → Wait for user approval before proceeding
- 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:
- quality-fixer: Self-contained processing for overall quality assurance and fixes until completion
- task-decomposer: Appropriate task decomposition of work plans
- task-executor: Individual task execution and structured response
- integration-test-reviewer: Review integration/E2E tests for skeleton compliance and quality
- 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:
- User instructions (explicit requests or constraints)
- Task files and design artifacts (Design Doc, PRD, work plan)
- Objective repo state (git status, file system, project configuration)
- 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:
- Input deliverables with file paths (from previous step or prerequisite check)
- 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_pathsscoped 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 withincompleteImplementations[]details for completion, then re-run quality-fixer.blocked→ discriminate byreasonfield:"Cannot determine due to unclear specification"→ readblockingIssues[]for specification details;"Execution prerequisites not met"→ readmissingPrerequisites[]withresolutionSteps— 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-syncis required whenever multiple Design Docs existtask-decomposerbegins only after work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) and batch approval- Work plan review self-heals: on
verdict.decisionneeds_revision, route back to work-planner (update) and re-review untilapproved/approved_with_conditions;rejectedescalates 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:
-
Escalation from subagent
- When receiving response with
status: "escalation_needed" - When receiving response with
status: "blocked"
- When receiving response with
-
When requirement change detected
- Any match in requirement change detection checklist
- Stop autonomous execution and re-analyze with integrated requirements in requirement-analyzer
-
When work-planner update restriction is violated
- Requirement changes after task-decomposer starts require overall redesign
- Restart entire flow from requirement-analyzer
-
When user explicitly stops
- Direct stop instruction or interruption
Task Management: 4-Step Cycle
Per-task cycle:
- Agent tool (subagent_type: "task-executor") → Pass task file path in prompt, receive structured response
- Check task-executor response:
status: escalation_neededorblocked→ Escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 1 withrequiredFixesapproved→ Proceed to step 3
- Otherwise → Proceed to step 3
- quality-fixer → Quality check and fixes. Always pass the current task file path as
task_filestub_detected→ Return to step 1 withincompleteImplementations[]detailsblocked→ Escalate to userapproved→ Proceed to step 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
-
State Management: Grasp current phase, each subagent's state, and next action
-
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 TabledataModel,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_verificationJSON and the samecodebase_analysisJSON 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
gapwith 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.
-
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
- Essential - Directly related to task type
- Quality - Testing and quality assurance
- Process - Workflow and documentation
- 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 |
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
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:
-
RED: Write a failing test first
- Write the test before implementation
- Ensure the test fails for the right reason
- Verify test can actually fail
-
GREEN: Write minimal code to pass
- Implement just enough to make the test pass
- Focus on making it work
-
REFACTOR: Improve code structure
- Clean up implementation
- Eliminate duplication
- Improve naming and clarity
- Keep all tests passing
-
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.*
- Examples:
- 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
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)
- unknown Type + Type Guards: Use for validating external input (API responses, localStorage, URL parameters)
- Generics: When type flexibility is needed
- Union Types・Intersection Types: Combinations of multiple types
- 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:
useStatefor 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 prefixedprocess.env. Raw, unprefixed access isundefinedin the browser bundle - Only prefixed vars reach the client: build tools expose only vars carrying their public prefix; an unprefixed var is
undefinedin the browser. The prefix differs per tool — match the project's bundler (ViteVITE_, Next.js publicNEXT_PUBLIC_, CRAREACT_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
.envfiles 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-catchor Error Boundary - Type Definition: Explicitly define return value types (e.g.,
Promise<Result>) - Effect race/cleanup: guard
useEffectdata fetches against out-of-order responses and post-unmount state updates — abort or ignore stale results (AbortControlleror a mounted flag), or use a server-state library (React Query/SWR) that cancels and dedupes.try-catchalone does not cover this
Format Rules
- Semicolon omission (follow Biome settings)
- Types in
PascalCase, variables/functions incamelCase - 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/useCallbackonly 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.lazyandSuspensefor 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
- Writing similar code 3 or more times - Violates Rule of Three
- Multiple responsibilities mixed in a single file - Violates Single Responsibility Principle (SRP)
- Defining same content in multiple files - Violates DRY principle
- Making changes without checking dependencies - Potential for unexpected impacts
- Disabling code with comments - Should use version control
- Error suppression - Hiding problems creates technical debt
- 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:
- Verify Design Doc explicitly defines this fallback
- Document the business justification
- Ensure error is logged with full context
- 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
- Read error message (first line) accurately
- Focus on first and last of stack trace
- 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
- Code Style Checking: Verify adherence to style guidelines
- Code Formatting: Ensure consistent formatting
- Unused Code Detection: Identify dead code and unused imports/variables
- Static Type Checking: Verify type correctness (for statically typed languages)
- Static Analysis: Detect potential bugs, security issues, code smells
Phase 2: Build Verification
- Compilation/Build: Verify code builds successfully (for compiled languages)
- Dependency Resolution: Ensure all dependencies are available and compatible
- Resource Validation: Check configuration files, assets are valid
Phase 3: Testing
- Unit Tests: Run all unit tests
- Integration Tests: Run integration tests
- Test Coverage: Measure and verify coverage meets standards
- 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
- Maintainability over Speed: Prioritize long-term code health over initial development velocity
- Simplicity First: Choose the simplest solution that meets requirements (YAGNI principle)
- 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.
- Explicit over Implicit: Make intentions clear through code structure and naming
- 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
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
- prd-template.md - Product Requirements Document template
- adr-template.md - Architecture Decision Record template
- ui-spec-template.md - UI Specification template (frontend/fullstack features)
- design-template.md - Technical Design Document template
- plan-template.md - Work Plan template
- task-template.md - Task file template for implementation tasks
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:
- Phase 1: Foundation Implementation - Contract definitions, interfaces/signatures, test preparation
- Phase 2: Core Feature Implementation - Business logic, unit tests
- 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:
- Implementation Complete: Code is functional
- Quality Complete: Tests, static checks, linting pass
- Integration Complete: Verified connection with other components
Creation Process
- Problem Analysis: Change scale assessment, ADR condition check
- Identify explicit and implicit project standards before investigation
- ADR Option Consideration (ADR only): Compare 3+ options, specify trade-offs
- Creation: Use templates, include measurable conditions
- 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
Proposed → Accepted → Deprecated/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
- At creation: Identify common technical areas (logging, error handling, async processing, etc.), reference existing common ADRs
- When missing: Consider creating necessary common ADRs
- Design Doc: Specify common ADRs in "Prerequisite ADRs" section
- Compliance check: Verify design aligns with common ADR decisions
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
-
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).
-
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:
- Build the project-tier content from the answers. Use references/template.md as the structure.
- Write to
docs/project-context/external-resources.md. Create the directory if absent. - When the calling workflow has a target UI Spec or Design Doc, also append or update the document's
## External Resources Usedsection with the feature-tier subset (label references + feature-specific identifiers only). - Report the file paths back to the calling workflow.
Reference Protocol (For Downstream Consumers)
Agents that load this skill consult resources in this order:
- Read
docs/project-context/external-resources.mdfirst (if present) to learn what is available and how to access it. - Read the target UI Spec or Design Doc's
## External Resources Usedsection for feature-specific identifiers. - 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
- references/frontend.md — Frontend domain axes
- references/backend.md — Backend domain axes
- references/api.md — API contract domain axes
- references/infra.md — Infrastructure domain axes
- references/template.md — Project-tier and feature-tier structure templates
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
- Writing similar code 3 or more times - Violates Rule of Three
- Multiple responsibilities mixed in a single component - Violates Single Responsibility Principle (SRP)
- Defining same content in multiple components - Violates DRY principle
- Making changes without checking dependencies - Potential for unexpected impacts
- Disabling code with comments - Should use version control
- Error suppression - Hiding problems creates technical debt
- Excessive use of type assertions (as) - Abandoning type safety
- Prop drilling through 3+ levels - Should use Context API or state management
- 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
- Read error message (first line) accurately
- Focus on first and last of stack trace
- Identify first line where your code appears
- 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)
- Lint/format — the project's formatter + linter (e.g., Biome, or ESLint + Prettier)
- Type check — type check without emit
- Build — production build
- Test — unit/integration tests
- 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:
- Selected strategy name and characteristics
- Alternatives considered and reason for rejection
- Risk mitigation plan (from Phase 3)
- Constraint compliance summary (from Phase 4)
- 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
- Verify at least one strategy combination beyond listed patterns was considered
- Confirm Phase 1 analysis framework is complete before selecting strategy
- Confirm Phase 3 risk analysis matrix is populated before implementation starts
- Confirm Phase 4 constraint checklist is reviewed before strategy decision
- Confirm Phase 6 documentation template is filled with selection rationale
Guidelines for Meta-cognitive Execution
- Leverage Known Patterns: Use as starting point, explore creative combinations
- Active WebSearch Use: Research implementation examples from similar tech stacks
- Apply 5 Whys: Pursue root causes to grasp essence
- Multi-perspective Evaluation: Comprehensively evaluate from each Phase 1-4 perspective
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:
- 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)
- State carries across steps — data produced or actions taken in one step affect what the next step accepts or displays
- 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 stateservice-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 undertests/e2e/fixture/) - service-integration-e2e tests:
*.service.e2e.test.*(or organize undertests/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
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
-
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."
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
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
backend→ Design Doc (backend) - Filename contains
frontend→ Design 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 7status: 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 withincompleteImplementations[]details, then re-execute Steps 4→5→6→7blocked→ Escalate to userapproved→ 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-*.mdanddocs/plans/tasks/integration-tests-frontend-task-*.mdcreated 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:
- 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")
- Follow the 4-step task cycle exactly: task-executor → escalation check → quality-fixer → commit
- Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
- 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:
- 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 - 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) - For each remaining file, extract the
{plan-name}prefix as the segment that appears before-task- - When at least one task file matches, the work plan is
docs/plans/{plan-name}.mdfor the prefix that has the most recent task-file mtime; ties broken by the lexicographically last{plan-name} - When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template
.mdindocs/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:
- List task files in
docs/plans/tasks/matching the single-layer pattern{plan-name}-task-*.mdfor the{plan-name}resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded - 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:
- 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"
- Agent tool (subagent_type: "dev-workflows-fullstack:task-executor") → Pass task file path in prompt, receive structured response
- CHECK task-executor response:
status: "escalation_needed"or"blocked"→ STOP and escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 2 withrequiredFixesapproved→ Proceed to step 4
readyForQualityCheck: true→ Proceed to step 4
- INVOKE quality-fixer: Execute all quality checks and fixes. Always pass the current task file path as
task_file - CHECK quality-fixer response:
stub_detected→ Return to step 2 withincompleteImplementations[]detailsblocked→ STOP and escalate to userapproved→ Proceed to step 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:
-
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
- code-verifier (subagent_type: "dev-workflows-fullstack:code-verifier") →
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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}.mdif 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
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:
- 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.
- 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
- 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:
- Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
- Search the repository with Bash (
rg, orgrepwhenrgis unavailable) for files matching those keywords. - Collect the matched file paths as the seed
affectedFiles. - When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as
affectedFilesbefore 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. - 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
affectedFilesbefore 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: includerequirements: the user requirements verbatimrequirement_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.filesAnalyzedand the modules they belong to - Affected layers: layers touched, derived from
analysisScope.categoriesDetectedandfocusAreas - Unknowns/assumptions:
limitationsplus 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."
- For Design Doc:
- (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 problemmandatoryChecks.taskEssence: Root problem beyond surface symptomsselectedRules: Applicable rule sectionswarningPatterns: Patterns to avoid
0.4 Reflecting in investigator Prompt
Include the following in investigator prompt:
- Problem essence (taskEssence)
- Key applicable rules summary (from selectedRules)
- Investigation focus (investigationFocus): Convert warningPatterns to "points prone to confusion or oversight in this investigation"
- 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):
-
pathMapexists 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,evidencewith asourceciting a specific file or location - Each failure point has
comparisonAnalysis(normalImplementation found or explicitly null) -
causeCategoryfor each failure point is one of: typo / logic_error / missing_constraint / design_gap / external_factor -
investigationSourcescovers at least 3 distinct source types (code, history, dependency, config, document, external) - Investigation covers
investigationFocusitems (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:
- Insert user confirmation before verifier execution
- Use AskUserQuestion:
"A design-level issue was detected. How should we proceed?"
- A: Attempt fix within current design
- B: Include design reconsideration
- If user selects B, pass
includeRedesign: trueto 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:
- Return to Step 1 with unchecked areas identified by verifier as investigation targets
- Maximum 2 additional investigation iterations
- 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
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:
- Delegate to subagents (one-shot calls): ui-analyzer, work-planner, quality-fixer-frontend.
- 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.
- 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).
- Read
candidateWriteSet[]from ui-analyzer output. - 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. - 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):
- Plan the edit based on ui-analyzer focusAreas and the relevant external resource (e.g., design origin's fetched_summary).
- Apply the edit using Edit / Write / MultiEdit on the affected files.
- Verify against external sources using whichever access method
docs/project-context/external-resources.mddeclares 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)
- Refine and re-verify until the adjustment matches the design source, or matches the user-confirmed adjustment target when no separate design source exists.
- 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. PassfilesModified: [list of files edited in this adjustment unit]. - Branch B (3-5 files): pass
task_file: <work plan path>(supplementary hint) ANDfilesModified: [list of files edited in this adjustment unit](primary scope).
- Branch A (1-2 files): omit
- 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 7stub_detected→ return to Step 5 to complete the implementation for this unit, then re-invoke quality-fixer-frontendblocked→ readreason. When"Cannot determine due to unclear specification", surfaceblockingIssues[]to the user and stop. When"Execution prerequisites not met", surfacemissingPrerequisites[]withresolutionStepsto 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
filesModifiedscoping - 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
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:
- 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")
- Follow the 4-step task cycle exactly: task-executor-frontend → escalation check → quality-fixer-frontend → commit
- Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
- 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:
- 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 - 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) - For each remaining file, extract the
{plan-name}prefix as the segment that appears before-task- - When at least one task file matches, the work plan is
docs/plans/{plan-name}.mdfor the prefix that has the most recent task-file mtime; ties broken by the lexicographically last{plan-name} - When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template
.mdindocs/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:
- List task files in
docs/plans/tasks/matching the single-layer pattern{plan-name}-task-*.mdfor the{plan-name}resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded - 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:
- 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"
- Agent tool (subagent_type: "dev-workflows-fullstack:task-executor-frontend") → Pass task file path in prompt, receive structured response
- CHECK task-executor-frontend response:
status: "escalation_needed"or"blocked"→ STOP and escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 2 withrequiredFixesapproved→ Proceed to step 4
readyForQualityCheck: true→ Proceed to step 4
- INVOKE quality-fixer-frontend: Execute all quality checks and fixes. Always pass the current task file path as
task_file - CHECK quality-fixer-frontend response:
stub_detected→ Return to step 2 withincompleteImplementations[]detailsblocked→ STOP and escalate to userapproved→ Proceed to step 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:
-
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
- code-verifier (subagent_type: "dev-workflows-fullstack:code-verifier") →
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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}.mdif 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
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:
- 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.
- 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
- 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:
- Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
- Search the repository with Bash (
rg, orgrepwhenrgis unavailable) for files matching those keywords. - Collect the matched file paths as the seed
affectedFiles. - When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as
affectedFilesbefore 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. - 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
affectedFilesbefore 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: includerequirements: the user requirements verbatimrequirement_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.filesAnalyzedand the modules they belong to - Affected layers: layers touched, derived from
analysisScope.categoriesDetectedandfocusAreas - Unknowns/assumptions:
limitationsplus 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: includerequirements: the user requirementsrequirement_analysis: a JSON object with all four fields —affectedFiles(analysisScope.filesAnalyzedfrom 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
- Source: an existing PRD in
- 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."
- For ADR:
- (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:
- Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
- Follow subagents-orchestration-guide skill planning flow:
- Execute steps defined below
- Stop and obtain approval for plan content before completion
- 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]."
- Invoke acceptance-test-generator using Agent tool:
- 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.])"
- When
- 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: onneeds_revision, re-invoke work-planner in update mode with the findings and re-review, repeating untilapprovedorapproved_with_conditions. Onrejected, 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.
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:
approvedorapproved_with_notes→ Passneeds_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.
-
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 ofd-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
-
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."
-
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.
-
After Step 5d completes:
- If the user selected
dfor all findings (nocroutes) → skip Steps 6-8, proceed to Step 9 for re-validation - If the user selected both
dandc→ re-evaluate thec-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remainingcfindings
- If the user selected
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.mdif 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
- 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")
- 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
- Follow the 4-step task cycle exactly: executor → escalation check → quality-fixer → commit
- Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
- 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:
- List task files in
docs/plans/tasks/matching the layer-aware patterns{plan-name}-backend-task-*.mdand{plan-name}-frontend-task-*.mdonly. 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 - 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) - For each remaining file, extract the
{plan-name}prefix as the segment that appears before-backend-task-or-frontend-task- - When at least one task file matches, the work plan is
docs/plans/{plan-name}.mdfor the prefix that has the most recent task-file mtime; ties broken by the lexicographically last{plan-name} - When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template
.mdindocs/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:
- List task files in
docs/plans/tasks/matching the layer-aware patterns{plan-name}-backend-task-*.mdand{plan-name}-frontend-task-*.mdfor the{plan-name}resolved by Work Plan Resolution. Single-layer tasks are excluded - 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:
- 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"
- Agent tool (subagent_type per routing table) → Pass task file path in prompt, receive structured response
- CHECK executor response:
status: "escalation_needed"or"blocked"→ STOP and escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 2 withrequiredFixesapproved→ Proceed to step 4
readyForQualityCheck: true→ Proceed to step 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 - CHECK quality-fixer response:
stub_detected→ Return to step 2 withincompleteImplementations[]detailsblocked→ STOP and escalate to userapproved→ Proceed to step 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:
-
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, singledocument_path,code_paths: implementation file list fromgit diff --name-only main...HEAD) - security-reviewer (subagent_type: "dev-workflows-fullstack:security-reviewer") → Design Doc path(s), implementation file list
- code-verifier (subagent_type: "dev-workflows-fullstack:code-verifier") → invoke once per Design Doc (
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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}.mdif 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
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
- 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")
- Follow monorepo-flow.md for the design phase (multiple Design Docs, design-sync, vertical slicing)
- Follow subagents-orchestration-guide skill for all other orchestration rules (stop points, structured responses, escalation)
- 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_progressusing TaskUpdate - Complete task registration before invoking subagents
After requirement-analyzer [Stop]
When user responds to questions:
- If response matches any
scopeDependencies.question→ Checkimpactfor 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:
- 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)
- Check executor status before quality-fixer (escalation check)
- Quality-fixer MUST run after each executor before proceeding to commit. Always pass the current task file path as
task_file - Check quality-fixer response:
stub_detected→ Return to executor withincompleteImplementations[]detailsblocked→ Escalate to userapproved→ Proceed to commit
Post-Implementation Verification (After All Tasks Complete)
After all task cycles finish, run verification agents in parallel before the completion report:
-
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, singledocument_path,code_paths: implementation file list fromgit diff --name-only main...HEAD) - security-reviewer (subagent_type: "dev-workflows-fullstack:security-reviewer") → Design Doc path(s), implementation file list
- code-verifier (subagent_type: "dev-workflows-fullstack:code-verifier") → invoke once per Design Doc (
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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-*.mdanddocs/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}.mdif 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.fixtureE2eande2eAbsenceReason.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:
- 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")
- 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
- 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→ Checkimpactfor 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_progressusing 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):
- Agent tool (subagent_type: "dev-workflows-fullstack:task-executor") → Pass task file path in prompt, receive structured response
- Check task-executor response:
status: escalation_neededorblocked→ Escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 1 withrequiredFixesapproved→ Proceed to step 3
- Otherwise → Proceed to step 3
- quality-fixer → Quality check and fixes. Always pass the current task file path as
task_filestub_detected→ Return to step 1 withincompleteImplementations[]detailsblocked→ Escalate to userapproved→ Proceed to step 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:
-
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
- code-verifier (subagent_type: "dev-workflows-fullstack:code-verifier") →
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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}.mdif 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.fixtureE2eande2eAbsenceReason.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:
- Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
- Follow subagents-orchestration-guide skill planning flow exactly:
- Execute steps defined below
- Stop and obtain approval for plan content before completion
- 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.])"
- When
- 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: onneeds_revision, re-invoke work-planner in update mode with the findings and re-review, repeating untilapprovedorapproved_with_conditions. Onrejected, 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).
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:
- 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")
- 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.
- 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:
- Execute the scan defined in Readiness Criteria using Read / Glob / Grep
- Record the result:
pass/fail/not_applicable - Cite evidence: file:line for
pass, the unresolved reference forfail, the missing trigger signal fornot_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:
-
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")
-
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.
- backend when every target file path matches one of:
-
Create a Phase 0 task file at
docs/plans/tasks/{plan-name}-backend-task-prep-{NN}.md(backend) ordocs/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 -
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"):
- 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)
- Check escalation per orchestration-guide
- 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"
- 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
-
Re-scan: Re-run the Step 2 readiness scan after all resolution tasks are committed.
-
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.
-
Final Cleanup: Delete every prep task file this recipe created for the current
{plan-name}(docs/plans/tasks/{plan-name}-backend-task-prep-*.mdanddocs/plans/tasks/{plan-name}-frontend-task-prep-*.md) AND the phase-completion file generated for prep phases (docs/plans/tasks/{plan-name}-phase0-completion.mdwhen 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. -
Exit:
Re-scan result Action All applicable criteria passExit with outcome: ready, gaps_resolved: Nand final Readiness ReportOne or more failremainExit 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
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:
- 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")
- 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
- Pass
$STEP_N_OUTPUTas-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:
- Target path: Which directory/module to document
- Depth: PRD only, or PRD + Design Docs
- Reference Architecture: layered / mvc / clean / hexagonal / none
- Human review: Yes (recommended) / No (fully autonomous)
- 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.prdUnitsexists- All
sourceUnitsacrossprdUnits(flattened, deduplicated) match the set ofdiscoveredUnitsIDs — no unit missing, no unit duplicated - Each discovered unit's
unitInventoryhas 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 FilestechnicalProfile.publicInterfaces→ Public Interfacesdependencies→ DependenciesrelatedFiles→ Scope boundaryunitInventory→ 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:
approvedorapproved_with_notes→ Passneeds_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.
-
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 ofd-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
-
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."
-
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.
-
After Step 5d completes:
- If the user selected
dfor all findings (nocroutes) → skip Steps 6-8, proceed to Step 9 for re-validation - If the user selected both
dandc→ re-evaluate thec-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remainingcfindings
- If the user selected
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.mdif 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-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:
-
Understand Task Essence (from
taskAnalysis.essence)- Focus on fundamental purpose, not surface-level work
- Distinguish between "quick fix" vs "proper solution"
-
Follow Selected Rules (from
selectedRules)- Review each selected rule section
- Apply concrete procedures and guidelines
-
Recognize Past Failures (from
metaCognitiveGuidance.pastFailures)- Apply countermeasures for known failure patterns
- Use suggested alternative approaches
-
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.essencein task descriptions - Apply
metaCognitiveGuidance.firstStepto 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.firstStepaction 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
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:
- 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")
- Execute update flow:
- Identify target → Clarify changes → Update document → Review → Consistency check
- Stop at every
[Stop: ...]marker → Wait for user approval before proceeding
- 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:
- quality-fixer: Self-contained processing for overall quality assurance and fixes until completion
- task-decomposer: Appropriate task decomposition of work plans
- task-executor: Individual task execution and structured response
- integration-test-reviewer: Review integration/E2E tests for skeleton compliance and quality
- 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:
- User instructions (explicit requests or constraints)
- Task files and design artifacts (Design Doc, PRD, work plan)
- Objective repo state (git status, file system, project configuration)
- 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:
- Input deliverables with file paths (from previous step or prerequisite check)
- 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_pathsscoped 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 withincompleteImplementations[]details for completion, then re-run quality-fixer.blocked→ discriminate byreasonfield:"Cannot determine due to unclear specification"→ readblockingIssues[]for specification details;"Execution prerequisites not met"→ readmissingPrerequisites[]withresolutionSteps— 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-syncis required whenever multiple Design Docs existtask-decomposerbegins only after work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) and batch approval- Work plan review self-heals: on
verdict.decisionneeds_revision, route back to work-planner (update) and re-review untilapproved/approved_with_conditions;rejectedescalates 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:
-
Escalation from subagent
- When receiving response with
status: "escalation_needed" - When receiving response with
status: "blocked"
- When receiving response with
-
When requirement change detected
- Any match in requirement change detection checklist
- Stop autonomous execution and re-analyze with integrated requirements in requirement-analyzer
-
When work-planner update restriction is violated
- Requirement changes after task-decomposer starts require overall redesign
- Restart entire flow from requirement-analyzer
-
When user explicitly stops
- Direct stop instruction or interruption
Task Management: 4-Step Cycle
Per-task cycle:
- Agent tool (subagent_type: "task-executor") → Pass task file path in prompt, receive structured response
- Check task-executor response:
status: escalation_neededorblocked→ Escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 1 withrequiredFixesapproved→ Proceed to step 3
- Otherwise → Proceed to step 3
- quality-fixer → Quality check and fixes. Always pass the current task file path as
task_filestub_detected→ Return to step 1 withincompleteImplementations[]detailsblocked→ Escalate to userapproved→ Proceed to step 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
-
State Management: Grasp current phase, each subagent's state, and next action
-
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 TabledataModel,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_verificationJSON and the samecodebase_analysisJSON 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
gapwith 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.
-
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
- Essential - Directly related to task type
- Quality - Testing and quality assurance
- Process - Workflow and documentation
- 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 |
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
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:
-
RED: Write a failing test first
- Write the test before implementation
- Ensure the test fails for the right reason
- Verify test can actually fail
-
GREEN: Write minimal code to pass
- Implement just enough to make the test pass
- Focus on making it work
-
REFACTOR: Improve code structure
- Clean up implementation
- Eliminate duplication
- Improve naming and clarity
- Keep all tests passing
-
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.*
- Examples:
- 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
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)
- unknown Type + Type Guards: Use for validating external input (API responses, localStorage, URL parameters)
- Generics: When type flexibility is needed
- Union Types・Intersection Types: Combinations of multiple types
- 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:
useStatefor 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 prefixedprocess.env. Raw, unprefixed access isundefinedin the browser bundle - Only prefixed vars reach the client: build tools expose only vars carrying their public prefix; an unprefixed var is
undefinedin the browser. The prefix differs per tool — match the project's bundler (ViteVITE_, Next.js publicNEXT_PUBLIC_, CRAREACT_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
.envfiles 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-catchor Error Boundary - Type Definition: Explicitly define return value types (e.g.,
Promise<Result>) - Effect race/cleanup: guard
useEffectdata fetches against out-of-order responses and post-unmount state updates — abort or ignore stale results (AbortControlleror a mounted flag), or use a server-state library (React Query/SWR) that cancels and dedupes.try-catchalone does not cover this
Format Rules
- Semicolon omission (follow Biome settings)
- Types in
PascalCase, variables/functions incamelCase - 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/useCallbackonly 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.lazyandSuspensefor 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/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
- Writing similar code 3 or more times - Violates Rule of Three
- Multiple responsibilities mixed in a single file - Violates Single Responsibility Principle (SRP)
- Defining same content in multiple files - Violates DRY principle
- Making changes without checking dependencies - Potential for unexpected impacts
- Disabling code with comments - Should use version control
- Error suppression - Hiding problems creates technical debt
- 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:
- Verify Design Doc explicitly defines this fallback
- Document the business justification
- Ensure error is logged with full context
- 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
- Read error message (first line) accurately
- Focus on first and last of stack trace
- 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
- Code Style Checking: Verify adherence to style guidelines
- Code Formatting: Ensure consistent formatting
- Unused Code Detection: Identify dead code and unused imports/variables
- Static Type Checking: Verify type correctness (for statically typed languages)
- Static Analysis: Detect potential bugs, security issues, code smells
Phase 2: Build Verification
- Compilation/Build: Verify code builds successfully (for compiled languages)
- Dependency Resolution: Ensure all dependencies are available and compatible
- Resource Validation: Check configuration files, assets are valid
Phase 3: Testing
- Unit Tests: Run all unit tests
- Integration Tests: Run integration tests
- Test Coverage: Measure and verify coverage meets standards
- 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
- Maintainability over Speed: Prioritize long-term code health over initial development velocity
- Simplicity First: Choose the simplest solution that meets requirements (YAGNI principle)
- 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.
- Explicit over Implicit: Make intentions clear through code structure and naming
- 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
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
- prd-template.md - Product Requirements Document template
- adr-template.md - Architecture Decision Record template
- ui-spec-template.md - UI Specification template (frontend/fullstack features)
- design-template.md - Technical Design Document template
- plan-template.md - Work Plan template
- task-template.md - Task file template for implementation tasks
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:
- Phase 1: Foundation Implementation - Contract definitions, interfaces/signatures, test preparation
- Phase 2: Core Feature Implementation - Business logic, unit tests
- 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:
- Implementation Complete: Code is functional
- Quality Complete: Tests, static checks, linting pass
- Integration Complete: Verified connection with other components
Creation Process
- Problem Analysis: Change scale assessment, ADR condition check
- Identify explicit and implicit project standards before investigation
- ADR Option Consideration (ADR only): Compare 3+ options, specify trade-offs
- Creation: Use templates, include measurable conditions
- 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
Proposed → Accepted → Deprecated/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
- At creation: Identify common technical areas (logging, error handling, async processing, etc.), reference existing common ADRs
- When missing: Consider creating necessary common ADRs
- Design Doc: Specify common ADRs in "Prerequisite ADRs" section
- Compliance check: Verify design aligns with common ADR decisions
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
-
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).
-
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:
- Build the project-tier content from the answers. Use references/template.md as the structure.
- Write to
docs/project-context/external-resources.md. Create the directory if absent. - When the calling workflow has a target UI Spec or Design Doc, also append or update the document's
## External Resources Usedsection with the feature-tier subset (label references + feature-specific identifiers only). - Report the file paths back to the calling workflow.
Reference Protocol (For Downstream Consumers)
Agents that load this skill consult resources in this order:
- Read
docs/project-context/external-resources.mdfirst (if present) to learn what is available and how to access it. - Read the target UI Spec or Design Doc's
## External Resources Usedsection for feature-specific identifiers. - 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
- references/frontend.md — Frontend domain axes
- references/backend.md — Backend domain axes
- references/api.md — API contract domain axes
- references/infra.md — Infrastructure domain axes
- references/template.md — Project-tier and feature-tier structure templates
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:
- Selected strategy name and characteristics
- Alternatives considered and reason for rejection
- Risk mitigation plan (from Phase 3)
- Constraint compliance summary (from Phase 4)
- 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
- Verify at least one strategy combination beyond listed patterns was considered
- Confirm Phase 1 analysis framework is complete before selecting strategy
- Confirm Phase 3 risk analysis matrix is populated before implementation starts
- Confirm Phase 4 constraint checklist is reviewed before strategy decision
- Confirm Phase 6 documentation template is filled with selection rationale
Guidelines for Meta-cognitive Execution
- Leverage Known Patterns: Use as starting point, explore creative combinations
- Active WebSearch Use: Research implementation examples from similar tech stacks
- Apply 5 Whys: Pursue root causes to grasp essence
- Multi-perspective Evaluation: Comprehensively evaluate from each Phase 1-4 perspective
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:
- 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)
- State carries across steps — data produced or actions taken in one step affect what the next step accepts or displays
- 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 stateservice-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 undertests/e2e/fixture/) - service-integration-e2e tests:
*.service.e2e.test.*(or organize undertests/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
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
-
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."
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
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
backend→ Design Doc (backend) - Filename contains
frontend→ Design 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 7status: 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 withincompleteImplementations[]details, then re-execute Steps 4→5→6→7blocked→ Escalate to userapproved→ 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-*.mdanddocs/plans/tasks/integration-tests-frontend-task-*.mdcreated 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:
- 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")
- Follow the 4-step task cycle exactly: task-executor → escalation check → quality-fixer → commit
- Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
- 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:
- 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 - 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) - For each remaining file, extract the
{plan-name}prefix as the segment that appears before-task- - When at least one task file matches, the work plan is
docs/plans/{plan-name}.mdfor the prefix that has the most recent task-file mtime; ties broken by the lexicographically last{plan-name} - When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template
.mdindocs/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:
- List task files in
docs/plans/tasks/matching the single-layer pattern{plan-name}-task-*.mdfor the{plan-name}resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded - 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:
- 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"
- Agent tool (subagent_type: "dev-workflows:task-executor") → Pass task file path in prompt, receive structured response
- CHECK task-executor response:
status: "escalation_needed"or"blocked"→ STOP and escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 2 withrequiredFixesapproved→ Proceed to step 4
readyForQualityCheck: true→ Proceed to step 4
- INVOKE quality-fixer: Execute all quality checks and fixes. Always pass the current task file path as
task_file - CHECK quality-fixer response:
stub_detected→ Return to step 2 withincompleteImplementations[]detailsblocked→ STOP and escalate to userapproved→ Proceed to step 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:
-
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
- code-verifier (subagent_type: "dev-workflows:code-verifier") →
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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}.mdif 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
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:
- 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.
- 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
- 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:
- Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
- Search the repository with Bash (
rg, orgrepwhenrgis unavailable) for files matching those keywords. - Collect the matched file paths as the seed
affectedFiles. - When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as
affectedFilesbefore 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. - 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
affectedFilesbefore 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: includerequirements: the user requirements verbatimrequirement_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.filesAnalyzedand the modules they belong to - Affected layers: layers touched, derived from
analysisScope.categoriesDetectedandfocusAreas - Unknowns/assumptions:
limitationsplus 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."
- For Design Doc:
- (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 problemmandatoryChecks.taskEssence: Root problem beyond surface symptomsselectedRules: Applicable rule sectionswarningPatterns: Patterns to avoid
0.4 Reflecting in investigator Prompt
Include the following in investigator prompt:
- Problem essence (taskEssence)
- Key applicable rules summary (from selectedRules)
- Investigation focus (investigationFocus): Convert warningPatterns to "points prone to confusion or oversight in this investigation"
- 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):
-
pathMapexists 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,evidencewith asourceciting a specific file or location - Each failure point has
comparisonAnalysis(normalImplementation found or explicitly null) -
causeCategoryfor each failure point is one of: typo / logic_error / missing_constraint / design_gap / external_factor -
investigationSourcescovers at least 3 distinct source types (code, history, dependency, config, document, external) - Investigation covers
investigationFocusitems (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:
- Insert user confirmation before verifier execution
- Use AskUserQuestion:
"A design-level issue was detected. How should we proceed?"
- A: Attempt fix within current design
- B: Include design reconsideration
- If user selects B, pass
includeRedesign: trueto 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:
- Return to Step 1 with unchecked areas identified by verifier as investigation targets
- Maximum 2 additional investigation iterations
- 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
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:
- 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")
- 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
- 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→ Checkimpactfor 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_progressusing 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):
- Agent tool (subagent_type: "dev-workflows:task-executor") → Pass task file path in prompt, receive structured response
- Check task-executor response:
status: escalation_neededorblocked→ Escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 1 withrequiredFixesapproved→ Proceed to step 3
- Otherwise → Proceed to step 3
- quality-fixer → Quality check and fixes. Always pass the current task file path as
task_filestub_detected→ Return to step 1 withincompleteImplementations[]detailsblocked→ Escalate to userapproved→ Proceed to step 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:
-
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
- code-verifier (subagent_type: "dev-workflows:code-verifier") →
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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}.mdif 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.fixtureE2eande2eAbsenceReason.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:
- Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
- Follow subagents-orchestration-guide skill planning flow exactly:
- Execute steps defined below
- Stop and obtain approval for plan content before completion
- 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.])"
- When
- 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: onneeds_revision, re-invoke work-planner in update mode with the findings and re-review, repeating untilapprovedorapproved_with_conditions. Onrejected, 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).
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:
- 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")
- 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.
- 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:
- Execute the scan defined in Readiness Criteria using Read / Glob / Grep
- Record the result:
pass/fail/not_applicable - Cite evidence: file:line for
pass, the unresolved reference forfail, the missing trigger signal fornot_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:
-
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")
-
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.
- backend when every target file path matches one of:
-
Create a Phase 0 task file at
docs/plans/tasks/{plan-name}-backend-task-prep-{NN}.md(backend) ordocs/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 -
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"):
- 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)
- Check escalation per orchestration-guide
- 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"
- 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
-
Re-scan: Re-run the Step 2 readiness scan after all resolution tasks are committed.
-
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.
-
Final Cleanup: Delete every prep task file this recipe created for the current
{plan-name}(docs/plans/tasks/{plan-name}-backend-task-prep-*.mdanddocs/plans/tasks/{plan-name}-frontend-task-prep-*.md) AND the phase-completion file generated for prep phases (docs/plans/tasks/{plan-name}-phase0-completion.mdwhen 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. -
Exit:
Re-scan result Action All applicable criteria passExit with outcome: ready, gaps_resolved: Nand final Readiness ReportOne or more failremainExit 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
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:
- 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")
- 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
- Pass
$STEP_N_OUTPUTas-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:
- Target path: Which directory/module to document
- Depth: PRD only, or PRD + Design Docs
- Reference Architecture: layered / mvc / clean / hexagonal / none
- Human review: Yes (recommended) / No (fully autonomous)
- 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.prdUnitsexists- All
sourceUnitsacrossprdUnits(flattened, deduplicated) match the set ofdiscoveredUnitsIDs — no unit missing, no unit duplicated - Each discovered unit's
unitInventoryhas 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 FilestechnicalProfile.publicInterfaces→ Public Interfacesdependencies→ DependenciesrelatedFiles→ Scope boundaryunitInventory→ 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:
approvedorapproved_with_notes→ Passneeds_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.
-
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 ofd-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
-
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."
-
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.
-
After Step 5d completes:
- If the user selected
dfor all findings (nocroutes) → skip Steps 6-8, proceed to Step 9 for re-validation - If the user selected both
dandc→ re-evaluate thec-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remainingcfindings
- If the user selected
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.mdif 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/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:
-
Understand Task Essence (from
taskAnalysis.essence)- Focus on fundamental purpose, not surface-level work
- Distinguish between "quick fix" vs "proper solution"
-
Follow Selected Rules (from
selectedRules)- Review each selected rule section
- Apply concrete procedures and guidelines
-
Recognize Past Failures (from
metaCognitiveGuidance.pastFailures)- Apply countermeasures for known failure patterns
- Use suggested alternative approaches
-
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.essencein task descriptions - Apply
metaCognitiveGuidance.firstStepto 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.firstStepaction 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
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:
- 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")
- Execute update flow:
- Identify target → Clarify changes → Update document → Review → Consistency check
- Stop at every
[Stop: ...]marker → Wait for user approval before proceeding
- 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:
- quality-fixer: Self-contained processing for overall quality assurance and fixes until completion
- task-decomposer: Appropriate task decomposition of work plans
- task-executor: Individual task execution and structured response
- integration-test-reviewer: Review integration/E2E tests for skeleton compliance and quality
- 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:
- User instructions (explicit requests or constraints)
- Task files and design artifacts (Design Doc, PRD, work plan)
- Objective repo state (git status, file system, project configuration)
- 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:
- Input deliverables with file paths (from previous step or prerequisite check)
- 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_pathsscoped 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 withincompleteImplementations[]details for completion, then re-run quality-fixer.blocked→ discriminate byreasonfield:"Cannot determine due to unclear specification"→ readblockingIssues[]for specification details;"Execution prerequisites not met"→ readmissingPrerequisites[]withresolutionSteps— 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-syncis required whenever multiple Design Docs existtask-decomposerbegins only after work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) and batch approval- Work plan review self-heals: on
verdict.decisionneeds_revision, route back to work-planner (update) and re-review untilapproved/approved_with_conditions;rejectedescalates 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:
-
Escalation from subagent
- When receiving response with
status: "escalation_needed" - When receiving response with
status: "blocked"
- When receiving response with
-
When requirement change detected
- Any match in requirement change detection checklist
- Stop autonomous execution and re-analyze with integrated requirements in requirement-analyzer
-
When work-planner update restriction is violated
- Requirement changes after task-decomposer starts require overall redesign
- Restart entire flow from requirement-analyzer
-
When user explicitly stops
- Direct stop instruction or interruption
Task Management: 4-Step Cycle
Per-task cycle:
- Agent tool (subagent_type: "task-executor") → Pass task file path in prompt, receive structured response
- Check task-executor response:
status: escalation_neededorblocked→ Escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 1 withrequiredFixesapproved→ Proceed to step 3
- Otherwise → Proceed to step 3
- quality-fixer → Quality check and fixes. Always pass the current task file path as
task_filestub_detected→ Return to step 1 withincompleteImplementations[]detailsblocked→ Escalate to userapproved→ Proceed to step 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
-
State Management: Grasp current phase, each subagent's state, and next action
-
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 TabledataModel,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_verificationJSON and the samecodebase_analysisJSON 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
gapwith 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.
-
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
- Essential - Directly related to task type
- Quality - Testing and quality assurance
- Process - Workflow and documentation
- 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 |
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:
-
RED: Write a failing test first
- Write the test before implementation
- Ensure the test fails for the right reason
- Verify test can actually fail
-
GREEN: Write minimal code to pass
- Implement just enough to make the test pass
- Focus on making it work
-
REFACTOR: Improve code structure
- Clean up implementation
- Eliminate duplication
- Improve naming and clarity
- Keep all tests passing
-
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.*
- Examples:
- 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
- Writing similar code 3 or more times - Violates Rule of Three
- Multiple responsibilities mixed in a single file - Violates Single Responsibility Principle (SRP)
- Defining same content in multiple files - Violates DRY principle
- Making changes without checking dependencies - Potential for unexpected impacts
- Disabling code with comments - Should use version control
- Error suppression - Hiding problems creates technical debt
- 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:
- Verify Design Doc explicitly defines this fallback
- Document the business justification
- Ensure error is logged with full context
- 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
- Read error message (first line) accurately
- Focus on first and last of stack trace
- 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
- Code Style Checking: Verify adherence to style guidelines
- Code Formatting: Ensure consistent formatting
- Unused Code Detection: Identify dead code and unused imports/variables
- Static Type Checking: Verify type correctness (for statically typed languages)
- Static Analysis: Detect potential bugs, security issues, code smells
Phase 2: Build Verification
- Compilation/Build: Verify code builds successfully (for compiled languages)
- Dependency Resolution: Ensure all dependencies are available and compatible
- Resource Validation: Check configuration files, assets are valid
Phase 3: Testing
- Unit Tests: Run all unit tests
- Integration Tests: Run integration tests
- Test Coverage: Measure and verify coverage meets standards
- 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
- Maintainability over Speed: Prioritize long-term code health over initial development velocity
- Simplicity First: Choose the simplest solution that meets requirements (YAGNI principle)
- 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.
- Explicit over Implicit: Make intentions clear through code structure and naming
- 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
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
- prd-template.md - Product Requirements Document template
- adr-template.md - Architecture Decision Record template
- ui-spec-template.md - UI Specification template (frontend/fullstack features)
- design-template.md - Technical Design Document template
- plan-template.md - Work Plan template
- task-template.md - Task file template for implementation tasks
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:
- Phase 1: Foundation Implementation - Contract definitions, interfaces/signatures, test preparation
- Phase 2: Core Feature Implementation - Business logic, unit tests
- 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:
- Implementation Complete: Code is functional
- Quality Complete: Tests, static checks, linting pass
- Integration Complete: Verified connection with other components
Creation Process
- Problem Analysis: Change scale assessment, ADR condition check
- Identify explicit and implicit project standards before investigation
- ADR Option Consideration (ADR only): Compare 3+ options, specify trade-offs
- Creation: Use templates, include measurable conditions
- 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
Proposed → Accepted → Deprecated/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
- At creation: Identify common technical areas (logging, error handling, async processing, etc.), reference existing common ADRs
- When missing: Consider creating necessary common ADRs
- Design Doc: Specify common ADRs in "Prerequisite ADRs" section
- Compliance check: Verify design aligns with common ADR decisions
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
-
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).
-
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:
- Build the project-tier content from the answers. Use references/template.md as the structure.
- Write to
docs/project-context/external-resources.md. Create the directory if absent. - When the calling workflow has a target UI Spec or Design Doc, also append or update the document's
## External Resources Usedsection with the feature-tier subset (label references + feature-specific identifiers only). - Report the file paths back to the calling workflow.
Reference Protocol (For Downstream Consumers)
Agents that load this skill consult resources in this order:
- Read
docs/project-context/external-resources.mdfirst (if present) to learn what is available and how to access it. - Read the target UI Spec or Design Doc's
## External Resources Usedsection for feature-specific identifiers. - 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
- references/frontend.md — Frontend domain axes
- references/backend.md — Backend domain axes
- references/api.md — API contract domain axes
- references/infra.md — Infrastructure domain axes
- references/template.md — Project-tier and feature-tier structure templates
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
- Writing similar code 3 or more times - Violates Rule of Three
- Multiple responsibilities mixed in a single component - Violates Single Responsibility Principle (SRP)
- Defining same content in multiple components - Violates DRY principle
- Making changes without checking dependencies - Potential for unexpected impacts
- Disabling code with comments - Should use version control
- Error suppression - Hiding problems creates technical debt
- Excessive use of type assertions (as) - Abandoning type safety
- Prop drilling through 3+ levels - Should use Context API or state management
- 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
- Read error message (first line) accurately
- Focus on first and last of stack trace
- Identify first line where your code appears
- 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)
- Lint/format — the project's formatter + linter (e.g., Biome, or ESLint + Prettier)
- Type check — type check without emit
- Build — production build
- Test — unit/integration tests
- 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:
- Selected strategy name and characteristics
- Alternatives considered and reason for rejection
- Risk mitigation plan (from Phase 3)
- Constraint compliance summary (from Phase 4)
- 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
- Verify at least one strategy combination beyond listed patterns was considered
- Confirm Phase 1 analysis framework is complete before selecting strategy
- Confirm Phase 3 risk analysis matrix is populated before implementation starts
- Confirm Phase 4 constraint checklist is reviewed before strategy decision
- Confirm Phase 6 documentation template is filled with selection rationale
Guidelines for Meta-cognitive Execution
- Leverage Known Patterns: Use as starting point, explore creative combinations
- Active WebSearch Use: Research implementation examples from similar tech stacks
- Apply 5 Whys: Pursue root causes to grasp essence
- Multi-perspective Evaluation: Comprehensively evaluate from each Phase 1-4 perspective
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:
- 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)
- State carries across steps — data produced or actions taken in one step affect what the next step accepts or displays
- 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 stateservice-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 undertests/e2e/fixture/) - service-integration-e2e tests:
*.service.e2e.test.*(or organize undertests/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
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
-
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."
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
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
backend→ Design Doc (backend) - Filename contains
frontend→ Design 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 7status: 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 withincompleteImplementations[]details, then re-execute Steps 4→5→6→7blocked→ Escalate to userapproved→ 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-*.mdanddocs/plans/tasks/integration-tests-frontend-task-*.mdcreated 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:
- 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")
- Follow the 4-step task cycle exactly: task-executor → escalation check → quality-fixer → commit
- Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
- 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:
- 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 - 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) - For each remaining file, extract the
{plan-name}prefix as the segment that appears before-task- - When at least one task file matches, the work plan is
docs/plans/{plan-name}.mdfor the prefix that has the most recent task-file mtime; ties broken by the lexicographically last{plan-name} - When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template
.mdindocs/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:
- List task files in
docs/plans/tasks/matching the single-layer pattern{plan-name}-task-*.mdfor the{plan-name}resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded - 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:
- 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"
- Agent tool (subagent_type: "dev-workflows:task-executor") → Pass task file path in prompt, receive structured response
- CHECK task-executor response:
status: "escalation_needed"or"blocked"→ STOP and escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 2 withrequiredFixesapproved→ Proceed to step 4
readyForQualityCheck: true→ Proceed to step 4
- INVOKE quality-fixer: Execute all quality checks and fixes. Always pass the current task file path as
task_file - CHECK quality-fixer response:
stub_detected→ Return to step 2 withincompleteImplementations[]detailsblocked→ STOP and escalate to userapproved→ Proceed to step 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:
-
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
- code-verifier (subagent_type: "dev-workflows:code-verifier") →
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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}.mdif 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
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:
- 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.
- 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
- 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:
- Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
- Search the repository with Bash (
rg, orgrepwhenrgis unavailable) for files matching those keywords. - Collect the matched file paths as the seed
affectedFiles. - When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as
affectedFilesbefore 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. - 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
affectedFilesbefore 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: includerequirements: the user requirements verbatimrequirement_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.filesAnalyzedand the modules they belong to - Affected layers: layers touched, derived from
analysisScope.categoriesDetectedandfocusAreas - Unknowns/assumptions:
limitationsplus 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."
- For Design Doc:
- (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 problemmandatoryChecks.taskEssence: Root problem beyond surface symptomsselectedRules: Applicable rule sectionswarningPatterns: Patterns to avoid
0.4 Reflecting in investigator Prompt
Include the following in investigator prompt:
- Problem essence (taskEssence)
- Key applicable rules summary (from selectedRules)
- Investigation focus (investigationFocus): Convert warningPatterns to "points prone to confusion or oversight in this investigation"
- 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):
-
pathMapexists 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,evidencewith asourceciting a specific file or location - Each failure point has
comparisonAnalysis(normalImplementation found or explicitly null) -
causeCategoryfor each failure point is one of: typo / logic_error / missing_constraint / design_gap / external_factor -
investigationSourcescovers at least 3 distinct source types (code, history, dependency, config, document, external) - Investigation covers
investigationFocusitems (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:
- Insert user confirmation before verifier execution
- Use AskUserQuestion:
"A design-level issue was detected. How should we proceed?"
- A: Attempt fix within current design
- B: Include design reconsideration
- If user selects B, pass
includeRedesign: trueto 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:
- Return to Step 1 with unchecked areas identified by verifier as investigation targets
- Maximum 2 additional investigation iterations
- 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
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:
- Delegate to subagents (one-shot calls): ui-analyzer, work-planner, quality-fixer-frontend.
- 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.
- 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).
- Read
candidateWriteSet[]from ui-analyzer output. - 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. - 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):
- Plan the edit based on ui-analyzer focusAreas and the relevant external resource (e.g., design origin's fetched_summary).
- Apply the edit using Edit / Write / MultiEdit on the affected files.
- Verify against external sources using whichever access method
docs/project-context/external-resources.mddeclares 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)
- Refine and re-verify until the adjustment matches the design source, or matches the user-confirmed adjustment target when no separate design source exists.
- 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. PassfilesModified: [list of files edited in this adjustment unit]. - Branch B (3-5 files): pass
task_file: <work plan path>(supplementary hint) ANDfilesModified: [list of files edited in this adjustment unit](primary scope).
- Branch A (1-2 files): omit
- 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 7stub_detected→ return to Step 5 to complete the implementation for this unit, then re-invoke quality-fixer-frontendblocked→ readreason. When"Cannot determine due to unclear specification", surfaceblockingIssues[]to the user and stop. When"Execution prerequisites not met", surfacemissingPrerequisites[]withresolutionStepsto 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
filesModifiedscoping - 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
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:
- 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")
- Follow the 4-step task cycle exactly: task-executor-frontend → escalation check → quality-fixer-frontend → commit
- Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
- 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:
- 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 - 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) - For each remaining file, extract the
{plan-name}prefix as the segment that appears before-task- - When at least one task file matches, the work plan is
docs/plans/{plan-name}.mdfor the prefix that has the most recent task-file mtime; ties broken by the lexicographically last{plan-name} - When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template
.mdindocs/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:
- List task files in
docs/plans/tasks/matching the single-layer pattern{plan-name}-task-*.mdfor the{plan-name}resolved by Work Plan Resolution. Layer-aware fullstack tasks are excluded - 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:
- 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"
- Agent tool (subagent_type: "dev-workflows-frontend:task-executor-frontend") → Pass task file path in prompt, receive structured response
- CHECK task-executor-frontend response:
status: "escalation_needed"or"blocked"→ STOP and escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 2 withrequiredFixesapproved→ Proceed to step 4
readyForQualityCheck: true→ Proceed to step 4
- INVOKE quality-fixer-frontend: Execute all quality checks and fixes. Always pass the current task file path as
task_file - CHECK quality-fixer-frontend response:
stub_detected→ Return to step 2 withincompleteImplementations[]detailsblocked→ STOP and escalate to userapproved→ Proceed to step 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:
-
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
- code-verifier (subagent_type: "dev-workflows-frontend:code-verifier") →
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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}.mdif 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
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:
- 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.
- 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
- 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:
- Extract candidate keywords from the user requirements (feature names, domain nouns, identifiers).
- Search the repository with Bash (
rg, orgrepwhenrgis unavailable) for files matching those keywords. - Collect the matched file paths as the seed
affectedFiles. - When the search returns no files: ask the user which files or modules the design targets (AskUserQuestion), and use that answer as
affectedFilesbefore 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. - 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
affectedFilesbefore 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: includerequirements: the user requirements verbatimrequirement_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.filesAnalyzedand the modules they belong to - Affected layers: layers touched, derived from
analysisScope.categoriesDetectedandfocusAreas - Unknowns/assumptions:
limitationsplus 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: includerequirements: the user requirementsrequirement_analysis: a JSON object with all four fields —affectedFiles(analysisScope.filesAnalyzedfrom 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
- Source: an existing PRD in
- 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."
- For ADR:
- (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:
- Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
- Follow subagents-orchestration-guide skill planning flow:
- Execute steps defined below
- Stop and obtain approval for plan content before completion
- 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]."
- Invoke acceptance-test-generator using Agent tool:
- 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.])"
- When
- 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: onneeds_revision, re-invoke work-planner in update mode with the findings and re-review, repeating untilapprovedorapproved_with_conditions. Onrejected, 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.
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:
approvedorapproved_with_notes→ Passneeds_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.
-
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 ofd-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
-
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."
-
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.
-
After Step 5d completes:
- If the user selected
dfor all findings (nocroutes) → skip Steps 6-8, proceed to Step 9 for re-validation - If the user selected both
dandc→ re-evaluate thec-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remainingcfindings
- If the user selected
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.mdif 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.
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
- 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")
- 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
- Follow the 4-step task cycle exactly: executor → escalation check → quality-fixer → commit
- Enter autonomous mode when user provides execution instruction with existing task files — this IS the batch approval
- 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:
- List task files in
docs/plans/tasks/matching the layer-aware patterns{plan-name}-backend-task-*.mdand{plan-name}-frontend-task-*.mdonly. 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 - 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) - For each remaining file, extract the
{plan-name}prefix as the segment that appears before-backend-task-or-frontend-task- - When at least one task file matches, the work plan is
docs/plans/{plan-name}.mdfor the prefix that has the most recent task-file mtime; ties broken by the lexicographically last{plan-name} - When no task file matches the restricted pattern, the work plan is the most-recent-mtime non-template
.mdindocs/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:
- List task files in
docs/plans/tasks/matching the layer-aware patterns{plan-name}-backend-task-*.mdand{plan-name}-frontend-task-*.mdfor the{plan-name}resolved by Work Plan Resolution. Single-layer tasks are excluded - 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:
- 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"
- Agent tool (subagent_type per routing table) → Pass task file path in prompt, receive structured response
- CHECK executor response:
status: "escalation_needed"or"blocked"→ STOP and escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 2 withrequiredFixesapproved→ Proceed to step 4
readyForQualityCheck: true→ Proceed to step 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 - CHECK quality-fixer response:
stub_detected→ Return to step 2 withincompleteImplementations[]detailsblocked→ STOP and escalate to userapproved→ Proceed to step 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:
-
Invoke both in parallel using Agent tool:
- code-verifier (subagent_type: "dev-workflows:code-verifier") → invoke once per Design Doc (
doc_type: design-doc, singledocument_path,code_paths: implementation file list fromgit diff --name-only main...HEAD) - security-reviewer (subagent_type: "dev-workflows:security-reviewer") → Design Doc path(s), implementation file list
- code-verifier (subagent_type: "dev-workflows:code-verifier") → invoke once per Design Doc (
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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}.mdif 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
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
- 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")
- Follow monorepo-flow.md for the design phase (multiple Design Docs, design-sync, vertical slicing)
- Follow subagents-orchestration-guide skill for all other orchestration rules (stop points, structured responses, escalation)
- 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_progressusing TaskUpdate - Complete task registration before invoking subagents
After requirement-analyzer [Stop]
When user responds to questions:
- If response matches any
scopeDependencies.question→ Checkimpactfor 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:
- 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)
- Check executor status before quality-fixer (escalation check)
- Quality-fixer MUST run after each executor before proceeding to commit. Always pass the current task file path as
task_file - Check quality-fixer response:
stub_detected→ Return to executor withincompleteImplementations[]detailsblocked→ Escalate to userapproved→ Proceed to commit
Post-Implementation Verification (After All Tasks Complete)
After all task cycles finish, run verification agents in parallel before the completion report:
-
Invoke both in parallel using Agent tool:
- code-verifier (subagent_type: "dev-workflows:code-verifier") → invoke once per Design Doc (
doc_type: design-doc, singledocument_path,code_paths: implementation file list fromgit diff --name-only main...HEAD) - security-reviewer (subagent_type: "dev-workflows:security-reviewer") → Design Doc path(s), implementation file list
- code-verifier (subagent_type: "dev-workflows:code-verifier") → invoke once per Design Doc (
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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-*.mdanddocs/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}.mdif 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.fixtureE2eande2eAbsenceReason.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:
- 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")
- 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
- 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→ Checkimpactfor 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_progressusing 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):
- Agent tool (subagent_type: "dev-workflows:task-executor") → Pass task file path in prompt, receive structured response
- Check task-executor response:
status: escalation_neededorblocked→ Escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 1 withrequiredFixesapproved→ Proceed to step 3
- Otherwise → Proceed to step 3
- quality-fixer → Quality check and fixes. Always pass the current task file path as
task_filestub_detected→ Return to step 1 withincompleteImplementations[]detailsblocked→ Escalate to userapproved→ Proceed to step 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:
-
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
- code-verifier (subagent_type: "dev-workflows:code-verifier") →
-
Consolidate results — check pass/fail for each:
- code-verifier: pass when
statusisconsistentormostly_consistent. fail whenneeds_revieworinconsistent. Collectdiscrepancieswith statusdrift,conflict, orgap - security-reviewer: pass when
statusisapprovedorapproved_with_notes. fail whenneeds_revision. blocked → Escalate to user - Present unified verification report to user
- code-verifier: pass when
-
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
-
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}.mdif 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.fixtureE2eande2eAbsenceReason.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:
- Delegate all work to sub-agents — your role is to invoke sub-agents, pass data between them, and report results
- Follow subagents-orchestration-guide skill planning flow exactly:
- Execute steps defined below
- Stop and obtain approval for plan content before completion
- 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.])"
- When
- 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: onneeds_revision, re-invoke work-planner in update mode with the findings and re-review, repeating untilapprovedorapproved_with_conditions. Onrejected, 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).
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:
- 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")
- 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.
- 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:
- Execute the scan defined in Readiness Criteria using Read / Glob / Grep
- Record the result:
pass/fail/not_applicable - Cite evidence: file:line for
pass, the unresolved reference forfail, the missing trigger signal fornot_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:
-
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")
-
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.
- backend when every target file path matches one of:
-
Create a Phase 0 task file at
docs/plans/tasks/{plan-name}-backend-task-prep-{NN}.md(backend) ordocs/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 -
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"):
- 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)
- Check escalation per orchestration-guide
- 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"
- 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
-
Re-scan: Re-run the Step 2 readiness scan after all resolution tasks are committed.
-
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.
-
Final Cleanup: Delete every prep task file this recipe created for the current
{plan-name}(docs/plans/tasks/{plan-name}-backend-task-prep-*.mdanddocs/plans/tasks/{plan-name}-frontend-task-prep-*.md) AND the phase-completion file generated for prep phases (docs/plans/tasks/{plan-name}-phase0-completion.mdwhen 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. -
Exit:
Re-scan result Action All applicable criteria passExit with outcome: ready, gaps_resolved: Nand final Readiness ReportOne or more failremainExit 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
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:
- 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")
- 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
- Pass
$STEP_N_OUTPUTas-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:
- Target path: Which directory/module to document
- Depth: PRD only, or PRD + Design Docs
- Reference Architecture: layered / mvc / clean / hexagonal / none
- Human review: Yes (recommended) / No (fully autonomous)
- 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.prdUnitsexists- All
sourceUnitsacrossprdUnits(flattened, deduplicated) match the set ofdiscoveredUnitsIDs — no unit missing, no unit duplicated - Each discovered unit's
unitInventoryhas 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 FilestechnicalProfile.publicInterfaces→ Public Interfacesdependencies→ DependenciesrelatedFiles→ Scope boundaryunitInventory→ 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:
approvedorapproved_with_notes→ Passneeds_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.
-
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 ofd-routed findings with codeLocation and designDocValue from $STEP_2_OUTPUT]. Reflect the current code behavior in the relevant sections and add a history entry."
-
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."
-
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.
-
After Step 5d completes:
- If the user selected
dfor all findings (nocroutes) → skip Steps 6-8, proceed to Step 9 for re-validation - If the user selected both
dandc→ re-evaluate thec-routed findings against the updated DD and drop any that are now satisfied by the DD revision; then proceed to Step 6 with the remainingcfindings
- If the user selected
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.mdif 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.
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:
-
Understand Task Essence (from
taskAnalysis.essence)- Focus on fundamental purpose, not surface-level work
- Distinguish between "quick fix" vs "proper solution"
-
Follow Selected Rules (from
selectedRules)- Review each selected rule section
- Apply concrete procedures and guidelines
-
Recognize Past Failures (from
metaCognitiveGuidance.pastFailures)- Apply countermeasures for known failure patterns
- Use suggested alternative approaches
-
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.essencein task descriptions - Apply
metaCognitiveGuidance.firstStepto 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.firstStepaction 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
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:
- 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")
- Execute update flow:
- Identify target → Clarify changes → Update document → Review → Consistency check
- Stop at every
[Stop: ...]marker → Wait for user approval before proceeding
- 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
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:
- quality-fixer: Self-contained processing for overall quality assurance and fixes until completion
- task-decomposer: Appropriate task decomposition of work plans
- task-executor: Individual task execution and structured response
- integration-test-reviewer: Review integration/E2E tests for skeleton compliance and quality
- 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:
- User instructions (explicit requests or constraints)
- Task files and design artifacts (Design Doc, PRD, work plan)
- Objective repo state (git status, file system, project configuration)
- 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:
- Input deliverables with file paths (from previous step or prerequisite check)
- 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_pathsscoped 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 withincompleteImplementations[]details for completion, then re-run quality-fixer.blocked→ discriminate byreasonfield:"Cannot determine due to unclear specification"→ readblockingIssues[]for specification details;"Execution prerequisites not met"→ readmissingPrerequisites[]withresolutionSteps— 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-syncis required whenever multiple Design Docs existtask-decomposerbegins only after work plan review (document-reviewer, doc_type WorkPlan; Medium/Large) and batch approval- Work plan review self-heals: on
verdict.decisionneeds_revision, route back to work-planner (update) and re-review untilapproved/approved_with_conditions;rejectedescalates 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:
-
Escalation from subagent
- When receiving response with
status: "escalation_needed" - When receiving response with
status: "blocked"
- When receiving response with
-
When requirement change detected
- Any match in requirement change detection checklist
- Stop autonomous execution and re-analyze with integrated requirements in requirement-analyzer
-
When work-planner update restriction is violated
- Requirement changes after task-decomposer starts require overall redesign
- Restart entire flow from requirement-analyzer
-
When user explicitly stops
- Direct stop instruction or interruption
Task Management: 4-Step Cycle
Per-task cycle:
- Agent tool (subagent_type: "task-executor") → Pass task file path in prompt, receive structured response
- Check task-executor response:
status: escalation_neededorblocked→ Escalate to userrequiresTestReviewistrue→ Execute integration-test-reviewerneeds_revision→ Return to step 1 withrequiredFixesapproved→ Proceed to step 3
- Otherwise → Proceed to step 3
- quality-fixer → Quality check and fixes. Always pass the current task file path as
task_filestub_detected→ Return to step 1 withincompleteImplementations[]detailsblocked→ Escalate to userapproved→ Proceed to step 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
-
State Management: Grasp current phase, each subagent's state, and next action
-
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 TabledataModel,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_verificationJSON and the samecodebase_analysisJSON 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
gapwith 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.
-
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
- Essential - Directly related to task type
- Quality - Testing and quality assurance
- Process - Workflow and documentation
- 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 |
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
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:
-
RED: Write a failing test first
- Write the test before implementation
- Ensure the test fails for the right reason
- Verify test can actually fail
-
GREEN: Write minimal code to pass
- Implement just enough to make the test pass
- Focus on making it work
-
REFACTOR: Improve code structure
- Clean up implementation
- Eliminate duplication
- Improve naming and clarity
- Keep all tests passing
-
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.*
- Examples:
- 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/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)
- unknown Type + Type Guards: Use for validating external input (API responses, localStorage, URL parameters)
- Generics: When type flexibility is needed
- Union Types・Intersection Types: Combinations of multiple types
- 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:
useStatefor 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 prefixedprocess.env. Raw, unprefixed access isundefinedin the browser bundle - Only prefixed vars reach the client: build tools expose only vars carrying their public prefix; an unprefixed var is
undefinedin the browser. The prefix differs per tool — match the project's bundler (ViteVITE_, Next.js publicNEXT_PUBLIC_, CRAREACT_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
.envfiles 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-catchor Error Boundary - Type Definition: Explicitly define return value types (e.g.,
Promise<Result>) - Effect race/cleanup: guard
useEffectdata fetches against out-of-order responses and post-unmount state updates — abort or ignore stale results (AbortControlleror a mounted flag), or use a server-state library (React Query/SWR) that cancels and dedupes.try-catchalone does not cover this
Format Rules
- Semicolon omission (follow Biome settings)
- Types in
PascalCase, variables/functions incamelCase - 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/useCallbackonly 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.lazyandSuspensefor 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


