AI-driven development toolkit with commands and agents for testing, code review, and commit management
- GitHub stars
- 13
Install
/plugin install aitt@prompt-collectionRun it inside Claude Code after adding the marketplace with /plugin marketplace add ByborgAI/prompt-collection.
Contents
Discovered from sourceCommands 13
⚠️ Schema: This command follows
aitt/commands/cmd.md. Read schema before modifying.
Cmd
Create, rewrite, or modify slash commands following the embedded schema specification.
Purpose
This command serves as both the authoritative schema definition and an operational tool for command authorship. Use it to:
- Create new commands from scratch with proper structure
- Rewrite existing non-compliant commands to follow the schema
- Modify schema-compliant commands—extend or change their behavior
Use when:
- Starting a new slash command
- Migrating legacy commands to schema compliance
- Extending or altering existing commands while maintaining structure
Do not use when:
- Making minor content edits (use direct file editing)
- The target is not a slash command
Inputs
Expects: Mode and target specification Required: Yes
Mode A: Create (with input)
/cmd create <command-name>
Creates a new command with the specified name. The command will guide you through:
- Description and category selection
- Command type template selection
- Section-by-section content development
Example:
/cmd create deploy-staging
Mode B: Rewrite (with input)
/cmd rewrite <path-to-command>
Transforms an existing non-compliant command to follow the schema. Creates a .bak backup before modification.
Example:
/cmd rewrite .claude/commands/worktree.md
Mode C: Modify (with input)
/cmd modify <path-to-command>
Works on an existing schema-compliant command—either extending its functionality or modifying its current behavior. Can alter any section, add new sections, or change existing logic.
Example:
/cmd modify .claude/commands/deploy.md
Mode D: Interactive (no input)
/cmd
Prompts for mode selection when invoked without arguments.
Prerequisites
Gate 1: Valid Mode Detection
Check: Input matches one of: create <name>, rewrite <path>, modify <path>, or empty
Pass: Proceed to mode-specific gate
Fail: Exit with usage guidance
Fail Output:
Invalid input. Usage:
/cmd create <command-name>
/cmd rewrite <path-to-command>
/cmd modify <path-to-command>
/cmd (interactive mode)
Gate 2: Target Validation (rewrite/modify modes)
Check: Target file exists at specified path Pass: Proceed to Process Fail: Exit with file not found error
Fail Output:
Target not found: <path>
Verify the file path and try again.
Gate 3: Schema Compliance (modify mode only)
Check: Target command follows schema structure (has frontmatter, required sections) Pass: Proceed to Process Fail: Suggest rewrite mode instead
Fail Output:
Target command is not schema-compliant.
Use '/cmd rewrite <path>' to transform it first.
Process
Step 1: Parse Input and Determine Mode
Extract mode and target from $ARGUMENTS:
Input: "" → Mode: interactive
Input: "create foo" → Mode: create, Target: foo
Input: "rewrite path/cmd.md" → Mode: rewrite, Target: path/cmd.md
Input: "modify path/cmd.md" → Mode: modify, Target: path/cmd.md
Step 1.5: Gap Analysis and User Clarification
Throughout all modes, when encountering ambiguity or gaps that cannot be resolved through logical inference:
When to ask:
- Architectural decisions with multiple valid approaches
- Business logic that requires domain knowledge
- Naming conventions specific to the user's project
- Integration points with unknown external systems
- Priority conflicts between competing requirements
When NOT to ask:
- Formatting choices covered by this schema
- Standard patterns with clear best practices
- Technical implementation details derivable from context
- Syntax or structure questions answerable from existing code
Question Protocol:
- Ask one question at a time
- Provide alphabetically labeled options (A, B, C, etc.)
- Option A is always the recommended choice
- Include brief rationale for each option
- Always include a final option for "Other (specify)"
Question Format:
[Context: Brief explanation of why this decision matters]
<question>
A) Recommended option - [why this is preferred]
B) Alternative option - [tradeoff/benefit]
C) Alternative option - [tradeoff/benefit]
Z) Other (please specify)
</question>
Awaiting your selection before proceeding.
Example:
The command's error handling strategy affects recovery behavior.
<question>
A) Fail-fast (recommended) - Exit immediately on first error; simpler, predictable, easier to debug
B) Accumulate - Collect all errors, report at end; better for batch operations but delays feedback
C) Retry with backoff - Attempt recovery; handles transient failures but adds complexity
Z) Other (please specify)
</question>
Awaiting your selection before proceeding.
Step 2: Execute Mode-Specific Workflow
Mode: Create
Step 2.1: Gather Command Metadata
Prompt user for:
- Description - One-line description (< 80 chars)
- Category - One of: documentation, workflow, analysis, generation, orchestration
- Command Type - One of the 5 templates (see Schema Specification)
Step 2.2: Generate Skeleton
Based on selected type, generate command skeleton:
---
name: <command-name>
description: <user-provided>
category: <user-selected>
version: 1.0
schema: aitt/commands/cmd.md
input:
expects: "[To be defined]"
required: true
format: free-text
---
> **Schema:** This command follows `aitt/commands/cmd.md`. Read schema before modifying.
# <Command Name>
> <description>
## Purpose
[Define the command's goal and when to use it]
## Inputs
**Expects:** [What input the command needs]
**Required:** [Yes | No | Conditional]
[Document input format based on command needs]
## Prerequisites
[Define entry conditions if applicable, or remove section]
## Process
### Step 1: [First Action]
[Describe step with implementation details]
### Step 2: [Next Action]
[Continue with process steps]
## Outputs
[Define artifacts produced, or remove section]
## Examples
### Basic Usage
/command-name argument
## Error Handling
| Error | Cause | Resolution |
|-------|-------|------------|
| [Error type] | [Cause] | [Fix] |
## References
- Schema: `aitt/commands/cmd.md`
Step 2.3: Guide Content Development
For each section, provide:
- Section purpose (from Schema Specification)
- Prompts for content
- Validation of completeness
Step 2.4: Write Command File
Write completed command to .claude/commands/<name>.md
Mode: Rewrite
Step 2.1: Read Existing Command
Read target file and analyze current structure.
Step 2.2: Extract Intent and Content
Map existing content to schema sections:
| Existing Pattern | Maps To |
|---|---|
| Inline description | Purpose section |
| Arguments/Parameters | Inputs section |
| Workflow/Steps | Process section |
| Notes/Warnings | Error Handling |
| Commands/Code | Process step implementation |
Step 2.3: Create Backup
cp <target> <target>.bak
Step 2.4: Generate Schema-Compliant Version
Transform content into schema structure while preserving:
- Original functionality and intent
- All process steps and logic
- Error handling information
- Any code examples
Step 2.5: Present for Approval
Show diff between original and transformed version. Request user approval before writing.
Step 2.6: Write Updated File
Upon approval, write schema-compliant version to target path.
Mode: Modify
Step 2.1: Read Existing Command
Read schema-compliant target file.
Step 2.2: Gather Modification Requirements
Prompt user for:
- Which section(s) to modify or extend
- What changes to make (add, alter, or remove functionality)
- Any new sections needed
Step 2.3: Generate Modifications
Apply changes while:
- Preserving existing structure where not explicitly changed
- Maintaining schema compliance
- Following section-specific formatting
Step 2.4: Present for Approval
Show proposed changes. Request user approval.
Step 2.5: Update File
Upon approval, write modified version to target path.
Mode: Interactive
Step 2.1: Present Mode Selection
Schema Command - Select Mode:
1. create - Generate new command from scratch
2. rewrite - Transform existing command to schema
3. modify - Extend or change behavior of compliant command
Enter mode and target (e.g., 'create my-command'):
Step 2.2: Route to Appropriate Mode
Parse selection and execute corresponding workflow.
Step 3: Checkpoint — Output Validation
GATE: Do not proceed until satisfied.
- Output follows schema structure
- All required sections present (Purpose, Process)
- Frontmatter complete and valid
- No schema violations detected
If not satisfied: Return to Step 2 and correct issues.
Step 4: Report Completion
Output summary:
- Mode executed
- File path created/modified
- Backup path (if rewrite mode)
- Any warnings or notes
Outputs
Files Generated/Modified
Create mode:
.claude/commands/<name>.md # New command file
Rewrite mode:
<target>.bak # Backup of original
<target> # Transformed command
Modify mode:
<target> # Modified command
Success Output
Schema command completed successfully.
Mode: <create|rewrite|modify>
Target: <path>
Status: <created|rewritten|modified>
[Backup: <path>.bak] # Rewrite mode only
Validation
Check 1: Frontmatter Validity
Method: Parse YAML frontmatter, verify required fields present Required fields: name, description, category, version
On success: Proceed to next check
On failure:
- Identify missing fields
- Add missing fields with appropriate values
- Re-validate
Check 2: Section Completeness
Method: Verify required sections exist (Purpose, Process minimum)
On success: Proceed to next check
On failure:
- Identify missing sections
- Generate placeholder content
- Prompt user to complete
- Re-validate
Check 3: Schema Notice (for created/rewritten commands)
Method: Verify schema notice blockquote present after frontmatter
On success: Complete validation
On failure:
- Add schema notice:
> **Schema:** This command follows `aitt/commands/cmd.md`. Read schema before modifying. - Re-validate
Error Handling
ERR-001: Invalid Mode
Symptoms: Command fails at input parsing Cause: Unrecognized mode keyword
Resolution:
- Check spelling of mode (create, rewrite, modify)
- Ensure proper spacing between mode and target
- Retry with correct syntax
ERR-002: Target Not Found
Symptoms: Command fails at Gate 2 Cause: File path incorrect or file doesn't exist
Resolution:
- Verify file path is correct (relative to repo root)
- Check file extension (.md)
- Use glob to search:
**/*<partial-name>*.md - Retry with correct path
ERR-003: Non-Compliant Target (modify mode)
Symptoms: Command fails at Gate 3 Cause: Target doesn't follow schema structure
Resolution:
- Use rewrite mode first:
/cmd rewrite <target> - Then use modify mode on the rewritten command
ERR-004: Backup Failed
Symptoms: Rewrite mode fails before transformation Cause: Permission or disk space issue
Resolution:
- Check write permissions for target directory
- Verify sufficient disk space
- Manually backup file if needed
- Retry operation
ERR-005: User Rejected Changes
Symptoms: Transformation/modification abandoned Cause: User declined approval
Resolution:
- Review proposed changes
- Modify requirements if needed
- Re-run command with adjusted approach
Examples
Example 1: Create New Command
Input:
/cmd create deploy-staging
Interaction:
Creating new command: deploy-staging
Description (< 80 chars):
> Deploys application to staging environment
Category:
1. documentation
2. workflow
3. analysis
4. generation
5. orchestration
Select [1-5]: 2
Command Type:
1. Simple Action - Single focused action
2. Delegation - Wraps base command with context
3. Multi-Step Workflow - Orchestrates multiple steps
4. Analysis/Report - Analyzes and produces report
5. Documentation Generation - Creates artifacts from source
Select [1-5]: 3
Generating skeleton...
[Skeleton presented for review]
Proceed with guided content development? [Y/n]
Result:
.claude/commands/deploy-staging.md created
Example 2: Rewrite Legacy Command
Input:
/cmd rewrite .claude/commands/worktree.md
Interaction:
Rewriting: .claude/commands/worktree.md
Analyzing existing structure...
Detected content:
- Description (line 1)
- Arguments section
- Workflow section (5 steps)
- Implementation details
Mapping to schema sections...
[Diff presented]
--- Original
+++ Transformed
-Create a new worktree for a branch.
+---
+name: worktree
+description: Create a new worktree for a branch
+category: workflow
+version: 1.0
+schema: aitt/commands/cmd.md
...
Backup will be created at: .claude/commands/worktree.md.bak
Apply transformation? [Y/n]
Result:
Backup: .claude/commands/worktree.md.bak
Rewritten: .claude/commands/worktree.md
Example 3: Modify Existing Command
Input:
/cmd modify .claude/commands/deploy-staging.md
Interaction:
Modifying: .claude/commands/deploy-staging.md
Current sections:
1. Purpose
2. Inputs
3. Process (4 steps)
4. Outputs
5. Error Handling
What would you like to change?
> Add rollback capability to Process section
Generating modifications...
[Proposed changes presented]
### Step 5: Rollback (if deployment fails)
If health check fails:
1. Identify previous stable version
2. Execute rollback: `kubectl rollout undo deployment/app`
3. Verify rollback successful
4. Report failure with rollback status
Apply changes? [Y/n]
Result:
Modified: .claude/commands/deploy-staging.md
Example 4: Interactive Mode
Input:
/cmd
Interaction:
Schema Command - Select Mode:
1. create - Generate new command from scratch
2. rewrite - Transform existing command to schema
3. modify - Extend or change behavior of compliant command
Enter mode and target: create api-test
Result: Proceeds with create mode workflow.
References
Internal References
- Schema Specification: See below (embedded in this command)
- Command Types: See "Command Type Templates" section
External References
- Claude Code documentation: https://docs.anthropic.com/claude-code
Schema Specification
Version: 1.3 Purpose: Standardized structure for all slash commands in
.claude/commands/
This specification defines a consistent format for Claude Code slash commands, ensuring clarity, maintainability, and predictable behavior across all commands.
Schema Structure
# FRONTMATTER (Optional but recommended)
---
name: command-name
description: One-line description shown in command list
category: documentation | workflow | analysis | generation | orchestration # examples; custom values allowed
version: 1.0
schema: aitt/commands/cmd.md # Reference to schema - modifications must follow this
input:
expects: "Feature name and optional configuration"
required: true
format: free-text | json | named-params | none | conditional
---
# BODY (Markdown)
Section Reference
| # | Section | Required | Purpose |
|---|---|---|---|
| 1 | Frontmatter | Recommended | Machine-readable metadata |
| 2 | Purpose | Required | What the command does |
| 3 | Key Principles | If applicable | Core philosophy and approach |
| 4 | Inputs | If applicable | Variables, arguments, context |
| 5 | Prerequisites | If applicable | Entry conditions, early-exit gates |
| 6 | Process | Required | Step-by-step execution flow |
| 7 | Outputs | If applicable | Files, reports, artifacts produced |
| 8 | Examples | Recommended | Usage and output examples |
| 9 | Validation | If applicable | Post-execution checks with fix procedures |
| 10 | Cleanup | If applicable | Resource cleanup after execution |
| 11 | Error Handling | Recommended | Failure modes and recovery |
| 12 | Summary | Recommended | Post-execution summary and reflection |
| 13 | References | If applicable | Related commands, external docs |
Complete Template
---
name: example-command
description: Brief description for command listing
category: documentation
version: 1.0
schema: aitt/commands/cmd.md # Schema reference - modifications must follow this
model: sonnet # Optional: preferred model (sonnet|opus|haiku)
tools: [Read, Write, Glob] # Optional: allowed tools
mcp_servers: [chrome] # Optional: required MCP servers
input: # Optional: quick input summary
expects: "Target name"
required: true
format: free-text
---
> **Schema:** This command follows `aitt/commands/cmd.md`. Read schema before modifying. If not found, ask user.
# Command Name
> Brief one-sentence description of what this command accomplishes.
## Purpose
Expanded description of the command's goal and when to use it.
## Key Principles (Optional)
**[Principle Name]:**
Core concept or philosophy that guides this command's approach.
**Anti-Pattern to Avoid:**
- **Wrong:** Description of incorrect approach
- **Correct:** Description of correct approach
## Inputs
**Expects:** Target name and optional configuration
**Required:** Target required, options optional
| Parameter | Required | Type | Description |
|-----------|----------|------|-------------|
| Target | Yes | string | The target to process |
| Options | No | JSON | Additional configuration |
### Usage
/example-command MyTarget /example-command MyTarget {"verbose": true}
## Prerequisites
### Check 1: [Condition Name]
**Check:** What to verify
**Pass:** Proceed to next check
**Fail:** Exit with [output/message]
### Check 2: [Condition Name]
**Check:** What to verify
**Pass:** Proceed to Process
**Fail:** Exit with [output/message]
## Process
### Step 1: Initialization
Description of first step.
```bash
# Commands to execute
npm run setup --target=$TARGET
Step 2: Execution
Description of second step.
Case A: Condition Met
- Action when condition is true
Case B: Condition Not Met
- Action when condition is false
Output Schema
{
"result": "success | error",
"data": { }
}
Step 3: Checkpoint — Quality Gate
GATE: Do not proceed until satisfied.
- Condition 1 met
- Condition 2 met
If not satisfied: Return to Step 2
Step 4: Finalization
Description of final step.
Implementation
// Update status in registry
const data = JSON.parse(fs.readFileSync('registry.json'));
data.status = 'completed';
fs.writeFileSync('registry.json', JSON.stringify(data, null, 2));
Outputs
Files Generated
output-folder/
├── artifact-1.md
├── artifact-2.mmd
└── artifact-3.json
Output Format
Description or schema of output structure.
Examples
Basic Usage
/example-command MyTarget
With Options
/example-command MyTarget {"option": "value"}
Example Output
# Generated Report
...
Validation
Check 1: Schema Compliance
Method: Run validation-command
On success: Proceed to next check
On failure:
- Identify invalid fields from error output
- Fix each violation
- Re-run validation
- Repeat until passes
Check 2: Content Accuracy
Method: Cross-reference output against source On success: Proceed to Cleanup On failure:
- Identify discrepancy
- Correct output
- Re-validate
Cleanup
If [resource was used]:
- Cleanup action 1
- Cleanup action 2
If [resource was not used]:
- No cleanup required
Error Handling
| Error | Cause | Resolution |
|---|---|---|
Target not found | Invalid input | Verify target exists |
Missing dependency | Prerequisite not met | Run /prerequisite first |
Summary
Brief post-execution summary of what was accomplished, issues encountered (if any), and recommended next steps.
References
- Related:
/related-command - External: Documentation Link
- Depends on:
/dependency-command
---
## Section Specifications
### 1. Frontmatter
YAML metadata block for machine parsing.
```yaml
---
name: kebab-case-name # Command identifier
description: string # One-line description (< 80 chars)
category: enum # See categories below
version: semver # Schema version (e.g., 1.0)
author: string # Optional creator
requires: [string] # Optional dependencies
schema: aitt/commands/cmd.md # Schema this command follows (recommended)
# Execution Control (Optional)
model: sonnet | opus | haiku # Preferred Claude model
tools: [Tool1, Tool2] # Allowed tools whitelist
mcp_servers: [server1] # Required MCP servers
# Input Definition (Optional - choose format that fits)
input:
expects: string # Brief description of expected input
required: boolean # Is input required?
format: free-text | json | named-params | none | conditional
---
Note: The input property in frontmatter provides a quick summary. Detailed input documentation belongs in the Inputs section of the command body.
Schema Reference:
The schema property declares which schema this command follows. When present:
- Agents modifying the command MUST read and follow the referenced schema
- If the schema file is not found, agents MUST ask the user for the schema location before making modifications
- This ensures structural consistency across command updates
Required Schema Notice: Commands following this schema MUST include a visible notice immediately after the frontmatter:
> **Schema:** This command follows `aitt/commands/cmd.md`. Read schema before modifying. If not found, ask user.
This ensures future agents see the schema requirement even if they don't parse frontmatter.
Categories:
documentation- Generates docs, specs, diagramsworkflow- Orchestrates multi-step processesanalysis- Inspects code/data, produces reportsgeneration- Creates code, files, artifactsorchestration- Coordinates other commands/agents
Execution Control Properties:
model- Specify preferred Claude model for this commandtools- Whitelist of tools the command may usemcp_servers- MCP servers required for command execution
2. Purpose
Clear statement of what the command does.
## Purpose
This command [action verb] [target] to [outcome].
**Use when:**
- Scenario 1
- Scenario 2
**Do not use when:**
- Anti-pattern 1
3. Key Principles
Optional section describing the core philosophy, approach, and guiding concepts that inform how the command works. Useful for complex commands where understanding the "why" helps users apply the command correctly.
## Key Principles
**[Principle Name]:**
Description of the core concept or philosophy.
**[Another Principle]:**
Description of another guiding principle.
**Anti-Pattern to Avoid:**
- **Wrong:** Description of incorrect approach or common mistake
- **Correct:** Description of the right way to think about it
When to include Key Principles:
- Command has a specific methodology or approach that isn't obvious
- There are common misconceptions about how the command should be used
- The command embodies a particular philosophy (e.g., "transaction completeness" vs "module boundaries")
- Understanding the principles helps users make better decisions during execution
Example principles:
- Transaction Completeness: "Documentation captures the entire user transaction from action to idle state"
- Source Truth: "Source code is authoritative—documentation must match implementation"
- 1:1 Correspondence: "Every BDD scenario must have a corresponding flowchart path"
4. Inputs
Document what input the command expects. The format is flexible—choose the structure that best describes your command's input requirements.
Input Summary (Required)
Always start with a brief summary of input expectations:
## Inputs
**Expects:** [Description of what input the command needs]
**Required:** Yes | No | Conditional
Format A: Free Text
For commands accepting natural language or simple string input:
## Inputs
**Expects:** Free text describing the target
**Required:** Yes
The command accepts `$ARGUMENTS` as free-form text input.
**Examples:**
- `/command analyze the login flow`
- `/command Email/Password Login`
- `/command "feature name with spaces"`
Format B: Structured (JSON/YAML)
For commands expecting structured data:
## Inputs
**Expects:** JSON object with feature metadata
**Required:** Yes
### Schema
```json
{
"feature_name": "string (required)",
"category": "string (required)",
"evidence": ["array of file paths (optional)"]
}
Example
{
"feature_name": "User Login",
"category": "Authentication"
}
#### Format C: Named Parameters
For commands with multiple distinct inputs:
```markdown
## Inputs
**Expects:** Feature name and optional configuration
**Required:** Feature name required, options optional
| Parameter | Required | Type | Description |
|-----------|----------|------|-------------|
| Feature name | Yes | string | Name of feature to process |
| Options | No | JSON | Additional configuration |
### Usage Patterns
/command FeatureName /command FeatureName {"verbose": true}
Format D: No Input
For commands that operate without user input:
## Inputs
**Expects:** None
**Required:** No
This command auto-detects its target based on [context/state/configuration].
Format E: Conditional Input
For commands with mode-dependent inputs:
## Inputs
**Expects:** Optional target specification
**Required:** Conditional
### Mode A: Auto-Select (no input)
/command
Command automatically selects next item from queue.
### Mode B: Specific Target (with input)
/command TargetName
Command processes the specified target.
Context Files (Optional)
If the command auto-loads context files:
### Context Files
- `@path/to/config.md` - Loaded automatically for [purpose]
- `@path/to/data.json` - Required data source
5. Prerequisites
Entry conditions that must be satisfied before the main process begins. If any prerequisite fails, the command exits early with an appropriate message or error output.
## Prerequisites
### Gate 1: [Condition Name]
**Check:** Description of what to verify
**Pass:** Proceed to next gate
**Fail:** Exit with [specific output or message]
**Fail Output Template (if applicable):**
```yaml
status: "error"
error_type: "prerequisite_failed"
message: "Description of why prerequisite was not met"
Gate 2: [Condition Name]
Check: Description of what to verify Pass: Proceed to Process Fail: Exit with [specific output or message]
**Key characteristics:**
- Prerequisites run BEFORE the main process
- Each gate is evaluated in order
- Failure causes immediate exit (no partial execution)
- Fail outputs can include structured error artifacts
- All gates must pass to proceed to Process
**Common prerequisite patterns:**
- Check if output already exists (skip/overwrite decision)
- Validate target accessibility (URL reachable, file exists)
- Verify required dependencies are available
- Confirm required MCP servers are connected
---
### 6. Process
Step-by-step execution with clear decision points. Includes support for checkpoints, special case handling, and embedded implementation details.
#### Embedding Implementation Details
**Steps SHOULD include concrete implementation details** when they help clarify execution. This includes:
| Content Type | When to Include | Example |
|--------------|-----------------|---------|
| Bash commands | CLI operations, file manipulation, tool invocation | `npx mmdc -i file.mmd -o output.svg` |
| Code snippets | Programmatic logic, data transformations | JavaScript, Python, etc. |
| Schema definitions | Data structures the step produces or consumes | JSON Schema, TypeScript interfaces |
| File templates | Content structure for generated files | Markdown templates, config files |
| Search patterns | Grep/glob patterns for discovery | `grep -r "ClassName" --include="*.kt"` |
| API examples | Request/response structures | REST endpoints, GraphQL queries |
**Principle:** If an agent would need to guess HOW to implement a step, the step lacks sufficient detail. Include the implementation inline.
```markdown
## Process
### Step 1: [Action Verb] [Target]
Description of what happens.
```bash
# Concrete command to execute
npx some-tool --input file.json --output result.md
Substep 1.1: Condition Handling
If condition A:
- Action 1
- Action 2
Else if condition B:
- Alternative action
Else:
- Default action
Step 2: [Next Action]
Continue with next logical step...
Output Schema
When this step produces structured data, define the schema:
{
"status": "completed | failed",
"output_path": "string",
"metadata": {
"created_at": "ISO8601 timestamp",
"source_files": ["array of paths"]
}
}
Implementation
// Inline code when logic is non-trivial
const result = processInput(data);
if (result.valid) {
writeOutput(result.data);
}
Step 3: Checkpoint — [Gate Name]
GATE: Do not proceed until all conditions are satisfied.
- Condition 1 verified
- Condition 2 verified
- Minimum threshold met
If not satisfied: Return to Step 2 and continue work
Step 4: Process Items
General procedure for processing items.
Special Cases
[Item Type A]:
- Override behavior 1
- Special handling instructions
[Item Type B]:
- Different handling approach
- Specific requirements
Step N: Completion
Final step and what success looks like.
#### Checkpoint Steps
Checkpoints are mid-process gates that pause execution until conditions are met:
```markdown
### Step N: Checkpoint — [Descriptive Name]
> **GATE:** Do not proceed until satisfied.
- [ ] Condition 1
- [ ] Condition 2
**If not satisfied:** [Recovery action - typically return to earlier step]
Checkpoint characteristics:
- Explicitly marked with "Checkpoint —" prefix
- Include blockquote with GATE: indicator
- List conditions as checkboxes
- Specify recovery action if conditions not met
Special Cases Subsection
When process steps have item-specific overrides:
### Step N: Process Items
[General procedure description]
#### Special Cases
**[Item Type A]:**
- Override 1
- Override 2
**[Item Type B]:**
- Different handling
Common Step Subsection Patterns
Use these subsection headers within steps to organize implementation details:
| Subsection | Purpose | Example Content |
|---|---|---|
#### Implementation | Code that executes the step | JavaScript, Python, bash scripts |
#### Output Schema | Structure of data produced | JSON schema, TypeScript interface |
#### Input Schema | Structure of data consumed | JSON schema with validation rules |
#### Search Patterns | Patterns for file/content discovery | Glob patterns, grep regex |
#### File Template | Template for generated files | Markdown structure, config format |
#### API Request | External API call details | Endpoint, headers, body |
#### Validation Rules | Criteria the step must satisfy | Business rules, format requirements |
Example step with implementation details:
### Step 3: Update Feature Registry
Update the feature status in the registry file.
#### Input Schema
```json
{
"feature_name": "string (required)",
"status": "pending | completed | failed"
}
Implementation
node -e "
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('registry.json', 'utf8'));
const feature = data.find(f => f.name === '${FEATURE_NAME}');
feature.status = 'completed';
feature.updated_at = new Date().toISOString();
fs.writeFileSync('registry.json', JSON.stringify(data, null, 2));
"
Validation Rules
- Feature must exist in registry before update
- Status must be one of: pending, completed, failed
- updated_at must be valid ISO8601 timestamp
---
### 7. Outputs
Specify all artifacts produced.
```markdown
## Outputs
### Directory Structure
output-folder/ ├── file-1.ext # Description ├── file-2.ext # Description └── subfolder/ └── file-3.ext # Description
### File Schemas
#### file-1.ext
```json
{
"schema": "definition"
}
Console Output
Description of what gets printed/displayed.
---
### 8. Examples
Show concrete usage patterns.
```markdown
## Examples
### Example 1: Basic Usage
**Input:**
/command-name simple-argument
**Result:**
Description of outcome.
### Example 2: Complex Usage
**Input:**
/command-name {"complex": "json", "input": true}
**Result:**
```markdown
# Generated Output
Content here...
Good vs Bad Examples
Good
/command-name correct-usage
Why: Explanation
Bad
/command-name incorrect-usage
Why: Explanation
---
### 9. Validation
Post-execution validation with support for fix-and-retry procedures. Validation runs AFTER the main process completes and BEFORE cleanup.
#### Format A: Simple Checks
For straightforward pass/fail validation:
```markdown
## Validation
- [ ] Output file exists
- [ ] JSON is well-formed
- [ ] Required fields present
- [ ] Values within expected ranges
Format B: Validation with Fix Procedures
For validations that include remediation workflows:
## Validation
### Check 1: Schema Compliance
**Method:** Run `npx ajv-cli validate -s schema.json -d output.yaml`
**On success:** Proceed to next check
**On failure:**
1. Read error output to identify invalid fields
2. Use Edit tool to fix each violation
3. Re-run validation command
4. Repeat until validation passes
**Max retries:** Until success
---
### Check 2: Content Accuracy
**Method:** Cross-reference each output field against source data
**On success:** Proceed to Cleanup
**On failure:**
1. Identify discrepancy between output and source
2. Return to source, verify correct value
3. Update output with corrected value
4. Re-validate this check
**Max retries:** 3 (then flag for manual review)
---
### Check 3: Consistency
**Method:** Compare related outputs for contradictions
**On success:** Complete validation
**On failure:**
1. Identify contradicting statements
2. Determine authoritative source
3. Correct non-authoritative output
4. Re-validate
Validation check structure:
- Method — How to perform the check (command, manual review, comparison)
- On success — Next action (proceed to next check, proceed to cleanup, complete)
- On failure — Step-by-step fix procedure
- Max retries — How many fix attempts before escalation (optional)
Key principles:
- Validation is post-execution only (pre-execution checks belong in Prerequisites)
- Each check should have a clear fix procedure, not just pass/fail
- External tool validation (schema validators, linters) is supported
- Fix-and-retry loops continue until success or max retries reached
10. Cleanup
Resource cleanup after command execution. Runs after validation, regardless of success or failure.
## Cleanup
**If [resource/tool was used]:**
1. Cleanup action 1
2. Cleanup action 2
3. Verify cleanup complete
**If [resource/tool was not used]:**
- No cleanup required
Common cleanup patterns:
## Cleanup
**If Chrome MCP was used:**
1. Close all browser tabs opened during execution
2. Verify no tabs remain from this session
**If temporary files were created:**
1. Delete files in `/tmp/command-workspace/`
2. Remove empty directories
**If external connections were opened:**
1. Close database connections
2. Terminate API sessions
3. Release file locks
**If no resources require cleanup:**
- No cleanup required
Key characteristics:
- Cleanup runs AFTER validation completes
- Cleanup should execute regardless of command success/failure
- Conditional cleanup based on which execution paths were taken
- Verify cleanup actions completed successfully
11. Error Handling
Document failure modes and recovery. Use the appropriate format based on complexity.
## Error Handling
### ERR-001: Target Not Found
**Symptoms:**
- Command reports "Target X not found"
- No output files generated
**Possible Causes:**
1. File path is incorrect or relative
2. Target was renamed or moved
3. Target exists but in unexpected location
**Resolution Steps:**
1. Verify the target path is absolute
2. Search for the target using glob patterns:
```bash
find . -name "*target-name*"
- Check recent git history for renames:
git log --follow --name-only -- "*target*" - If found in new location, update input and retry
Prevention:
- Always use absolute paths
- Run
/verify-pathsbefore complex operations
ERR-002: Validation Failure
Symptoms:
- Output generated but marked invalid
- Consistency check fails
Diagnosis Checklist:
- Source files unchanged since analysis started?
- All dependencies resolved?
- Output schema matches expected format?
Resolution by Cause:
If source changed during execution:
- Discard output
- Re-run command with fresh source state
If dependency missing:
- Identify missing dependency from error log
- Run prerequisite command first
- Retry original command
If schema mismatch:
- Compare output against schema definition
- Identify malformed sections
- Manually correct or regenerate affected sections
ERR-003: Partial Completion
Symptoms:
- Some outputs generated, others missing
- Command terminated unexpectedly
Recovery Procedure:
- Check which outputs exist:
output/ ├── file-1.md ✓ (exists) ├── file-2.md ✗ (missing) └── file-3.md ✓ (exists) - Determine if partial outputs are usable
- Options:
- Resume: Re-run command (idempotent commands only)
- Complete manually: Generate missing files individually
- Rollback: Delete partial outputs, fix cause, restart
Do NOT:
- Assume partial outputs are complete
- Mix outputs from multiple runs without verification
---
### 12. Summary
Post-execution summary providing reflection on what was accomplished, issues encountered, and recommended next steps. This section helps users understand the outcome and determine follow-up actions.
**When to include:**
- Complex multi-step processes where outcomes may vary
- Analysis commands that produce findings requiring interpretation
- Workflows that may encounter recoverable issues
- Any command where user action may be needed post-execution
**When to omit:**
- Simple commands with obvious success/failure outcomes
- Commands where the output artifacts speak for themselves
```markdown
## Summary
Brief post-execution summary addressing:
- What was successfully accomplished
- Issues encountered (if any) with their impact
- Data quality or completeness assessment (if applicable)
- Recommended next steps or follow-up actions
- Any caveats or limitations users should be aware of
### Format A: Success with No Issues
If everything completed successfully with no gaps or concerns:
✓ [COMMAND NAME] COMPLETE
[1-2 sentence summary of what was accomplished] No issues detected. All objectives met.
### Format B: Success with Notes
If command completed but with recoverable issues, missing data, or important context:
✓ [COMMAND NAME] COMPLETE
[1-2 sentence summary of what was accomplished]
Issues Encountered:
- [Issue 1 description]
- [Issue 2 description]
Impact: [How issues affect the output or next steps]
Recommended Actions:
- [Specific action to address issue 1]
- [Specific action to address issue 2]
Quality Assessment: [Brief statement on output completeness/reliability]
### Format C: Partial Completion
If command completed but some objectives were not met:
⚠ [COMMAND NAME] PARTIALLY COMPLETE
Completed:
- [What succeeded]
Incomplete:
- [What failed or was skipped]
Reason: [Why partial completion occurred]
Next Steps:
- [How to complete remaining work]
- [Alternative approaches if applicable]
**Key principles:**
- Be concise—users want actionable information, not verbose recap
- Prioritize recommendations—what should the user do next?
- Differentiate severity—minor gaps vs. critical issues
- Provide specificity—concrete actions, not vague suggestions
- Omit the section entirely if no useful information to convey
13. References
Link related resources.
## References
### Related Commands
- `/related-1` - Relationship description
- `/related-2` - Relationship description
### Dependencies
- `/prerequisite` - Must run before this command
### External Documentation
- [Link Text](url) - Description
### Source Files
- `path/to/implementation` - Purpose
Command Type Templates
Type A: Simple Action Command
---
name: simple-action
description: Performs a single focused action
category: generation
input:
expects: "Target to process"
required: true
format: free-text
---
# Simple Action
> Performs [action] on [target].
## Purpose
[One paragraph description]
## Inputs
| Variable | Type | Description |
|----------|------|-------------|
| `$TARGET` | string | The target to process |
## Process
1. Read input
2. Execute action
3. Output result
## Outputs
- Single file or console output
## Examples
/simple-action my-target
Type B: Delegation Command
---
name: platform-specific
description: Delegates to base command with platform context
category: orchestration
requires: [base-command]
input:
expects: "Arguments to pass to base command"
required: true
format: json
---
# Platform-Specific Command
> Executes base command with platform-specific configuration.
## Purpose
Wrapper that applies platform context to the base command.
## Configuration
| Setting | Value |
|---------|-------|
| Output folder | `platform/` |
| Source location | `source-path/` |
## Process
Execute `@.claude/commands/base-command.md` with:
1. Platform-specific output paths
2. Platform-specific source paths
3. All other base command instructions
## Inputs
Pass through: `$ARGUMENTS`
## Outputs
Same as base command, in platform-specific directory.
Type C: Multi-Step Workflow
---
name: workflow-command
description: Orchestrates multiple steps or commands
category: workflow
input:
expects: "Optional workflow arguments"
required: false
format: free-text
---
# Workflow Command
> Orchestrates [workflow description].
## Purpose
Coordinates multiple steps/commands to achieve [goal].
## Process Overview
Step 1 ──► Step 2 ──► Step 3 ──► Complete
│
▼
[Parallel]
/
Step 2a Step 2b
\ /
──►──►──
## Process
### Step 1: Setup
[Description]
### Step 2: Parallel Execution
Launch simultaneously:
- **Task A:** Description
- **Task B:** Description
### Step 3: Aggregation
Combine results from parallel tasks.
### Step 4: Completion
Final actions and reporting.
## Error Handling
### Step Failures
- Step 1 fails: Abort workflow
- Step 2a fails: Continue with 2b, mark partial
- Step 3 fails: Retry once, then abort
## Status Tracking
| Status | Meaning |
|--------|---------|
| `pending` | Not started |
| `in_progress` | Currently executing |
| `completed` | Successfully finished |
| `failed` | Error occurred |
Type D: Analysis/Report Command
---
name: analysis-command
description: Analyzes target and produces report
category: analysis
input:
expects: "Target to analyze"
required: true
format: free-text
---
# Analysis Command
> Analyzes [target] and produces [report type].
## Purpose
Performs comprehensive analysis of [target] to identify [findings].
## Inputs
| Variable | Type | Description |
|----------|------|-------------|
| `$TARGET` | string | What to analyze |
## Analysis Scope
### Include
- Item type 1
- Item type 2
### Exclude
- Excluded item type 1
## Process
### Step 1: Discovery
Locate and enumerate targets.
### Step 2: Analysis
For each target:
- Check aspect 1
- Check aspect 2
- Record findings
### Step 3: Synthesis
Aggregate findings into report.
## Output Format
### Report Structure
```markdown
# Analysis Report: [Target]
## Summary
[Executive summary]
## Findings
### Category 1
| Finding | Severity | Location |
|---------|----------|----------|
| ... | ... | ... |
## Recommendations
[Prioritized recommendations]
Validation
- All targets analyzed
- No false positives
- Recommendations actionable
---
### Type E: Documentation Generation
```markdown
---
name: doc-generator
description: Generates documentation from source analysis
category: documentation
input:
expects: "Feature metadata object"
required: true
format: json
---
# Documentation Generator
> Generates comprehensive documentation for [target].
## Purpose
Analyzes source code and produces documentation artifacts.
## Inputs
### JSON Schema
```json
{
"feature_name": "string (required)",
"category": "string (required)",
"evidence": ["array of file paths"]
}
Process
Step 1: Parse Input
Extract metadata from JSON input.
Step 2: Resolve Evidence
Locate all referenced source files.
Step 3: Analyze
Deep analysis of source code behavior.
Step 4: Generate Artifacts
Create documentation files.
Step 5: Validate
Cross-check artifacts for consistency.
Outputs
File Structure
${feature-name}/
├── ${feature-name}.spec.md # Specification
├── ${feature-name}.diagram.mmd # Visual diagram
└── ${feature-name}.notes.md # Additional notes
Artifact Specifications
spec.md
- Metadata section
- Overview
- Detailed scenarios
- References
diagram.mmd
- Mermaid syntax
- Color-coded paths
- All decision points
Validation
Consistency Checks
- All scenarios in spec have diagram paths
- All diagram paths match spec scenarios
- Evidence files resolved
- Syntax validated
---
## Best Practices
### Writing Style
**Principles:**
1. Structure conveys importance—all steps are required by default
2. Concise over verbose—every word must earn its place
3. Complete over brief—include all details, but no filler
**Conciseness guidelines:**
| Verbose (avoid) | Concise (prefer) |
|-----------------|------------------|
| "In order to accomplish this task, you will need to..." | "Run:" |
| "It is important to note that the system will..." | "The system..." |
| "The next step involves performing the action of..." | "Next:" |
| "Please ensure that you have completed..." | "Verify:" |
| "This particular feature is responsible for..." | "This feature..." |
| "At this point in time, the process will..." | "The process..." |
**Write like a reference manual, not a tutorial.** Assume the reader is competent. State facts. Omit preamble.
```markdown
❌ "Before we begin, it's worth mentioning that you'll want to make sure
that all of your dependencies are properly installed and configured
before attempting to run this command."
✓ "Prerequisite: Dependencies installed."
Prohibited patterns:
❌ *** MANDATORY ***
❌ CRITICAL: You MUST do this
❌ IMPORTANT: Do not skip this step
❌ **NOTE:** This is essential
❌ WARNING: Required action
❌ !!! ATTENTION !!!
❌ [REQUIRED] Step description
❌ Step description (MUST DO)
Correct approach:
✓ Step description # All steps are required by default
✓ (Optional) Step description # Explicitly mark optional items
✓ > **GATE:** Do not proceed... # Use schema-defined checkpoints for critical gates
✓ **If not satisfied:** Return to... # Use structured conditions, not shouty warnings
Rationale:
- When everything is marked "CRITICAL," nothing stands out
- The schema's structure (Prerequisites, Checkpoints, Validation) already indicates importance
- Agents reading the command will follow ALL steps—emphasis markers add noise, not compliance
- Use
(Optional)to mark non-required items rather than marking required items as required
Allowed emphasis:
> **GATE:**blockquotes for mid-process checkpoints (schema-defined pattern)- Bold for structural labels (Check:, Pass:, Fail:, Method:, etc.)
- Code formatting for
commands,paths, andvalues - Tables and structured formats for complex information
Anti-pattern to avoid:
- Wrong: "*** CRITICAL *** You MUST verify this step is complete before proceeding!!!"
- Correct: Document the step. Use a checkpoint if verification is needed before continuing.
Naming Conventions
- Use
kebab-casefor command names - Use
SCREAMING_SNAKE_CASEfor variables - Use descriptive, action-oriented names
Documentation Quality
- Lead with purpose—what and why
- Process steps should be actionable
- Include both success and failure paths
- Provide concrete examples
- Assume all steps are required—mark exceptions with
(Optional)
Maintainability
- Keep commands focused (single responsibility)
- Extract common logic to base commands
- Version your commands
- Document breaking changes
User Experience
- Provide helpful error messages
- Show progress for long operations
- Support both simple and advanced usage
- Include "good vs bad" examples
Migration Guide
To convert an existing command to this schema:
- Extract metadata into frontmatter
- Identify sections in existing content
- Reorganize into schema sections
- Add missing sections (error handling, validation)
- Standardize formatting (tables, code blocks)
- Add examples if missing
- Validate against schema
Changelog
Version 1.4
- Added Summary section (section 12) as recommended post-execution reflection
- Summary provides outcome assessment, issues encountered, and next steps
- Three format options: Success with No Issues, Success with Notes, Partial Completion
- Renumbered References from section 12 to section 13
- Updated Section Reference table and Complete Template
- Summary is recommended but not mandatory—omit when no useful information to convey
Version 1.3
- Added "Writing Style" section to Best Practices
- Established three principles: structure conveys importance, concise over verbose, complete over brief
- Added conciseness guidelines with verbose/concise comparison table
- Added guidance: "Write like a reference manual, not a tutorial"
- Defined prohibited emphasis patterns (MANDATORY, CRITICAL, IMPORTANT, etc.)
- Added guidance to mark optional items with
(Optional)rather than marking required items as required - Documented allowed emphasis patterns (GATE: blockquotes, structural labels, code formatting)
Version 1.2
- Added
schemafrontmatter property for declaring schema compliance - Added required visible schema notice after frontmatter (blockquote format)
- Schema reference ensures agents read and follow schema when modifying commands
- If schema file not found, agents must ask user for schema location
- Enhanced Process section with "Embedding Implementation Details" guidance
- Added explicit encouragement for bash commands, code snippets, and schemas within steps
- Added "Common Step Subsection Patterns" table (Implementation, Output Schema, Input Schema, Search Patterns, File Template, API Request, Validation Rules)
- Updated Complete Template with concrete implementation examples
- Added principle: "If an agent would need to guess HOW to implement a step, the step lacks sufficient detail"
Version 1.1
- Added Key Principles section for documenting core philosophy and approach
- Added Prerequisites section for entry gates with early-exit support
- Added Cleanup section for resource management
- Extended Frontmatter with
model,tools,mcp_serversproperties - Added Checkpoint step type for mid-process gates in Process section
- Added Special Cases subsection pattern for item-specific overrides
- Refactored Validation to focus on post-execution with fix procedures
- Removed pre-execution checks from Validation (moved to Prerequisites)
- Refactored Inputs section to be format-agnostic (free text, JSON, named params, none, conditional)
- Replaced rigid
variablesfrontmatter with flexibleinputsummary - Removed Common Anti-Patterns from Error Handling (author's discretion)
- Renumbered sections to accommodate new additions (now 12 sections)
Version 1.0
- Initial schema definition
- Five command type templates
- Section specifications
- Best practices guide
/code-review - Code Review
Purpose
Execute comprehensive code analysis across quality, security, performance, and architecture domains.
Usage
/code-review [branch]
Execution
- Discover and categorize files for analysis based on the diff between the current branch and the target branch:
- Use
git diff {branch_argument}...$(git branch --show-current)where{branch_argument}is the first argument (defaults to 'master' if not provided)
- Use
- Apply appropriate analysis tools and techniques:
- Quality: Code style, complexity, maintainability, technical debt assessment, SOLID principles compliance, error handling patterns
- Security: Vulnerability scanning, dependency checks, threat modeling, authentication/authorization flaws, data exposure risks, input validation
- Performance: Profiling, bottleneck identification, resource usage analysis, scalability assessment, Core Web Vitals (frontend), memory management (leaks, dangling pointers, buffer overflows)
- Architecture: Design patterns, modularity, scalability, coupling analysis, separation of concerns, future-proofing evaluation
- Testing: Test quality, edge case handling, test pyramid compliance (DO NOT run tests, just analyze test
- Maintainability: Code readability, documentation quality, code comments, naming conventions, modularity coverage and quality)
- Based on an initial quick analysis, add additional checks if necessary
- Generate findings with severity ratings
- Create actionable recommendations with priorities, only if issues are found
- Severity levels:
- High: Critical issues that must be addressed immediately
- Medium: Important issues that should be resolved soon
- Low: Minor issues that can be addressed later
- List should be sorted by severity
- Include file project root relative filepaths and line numbers for each issue
- Focus on changes and the effects of those changes, not the entire file
- Severity levels:
- Present ONLY a nicely formatted compact markdown table of text-based analysis report nothing else
- If you have positive findings, just add a tick mark next to the section that you used as a point to review
- Start with the positive findings and then list the improvements at the end
- Only include list of improvements
- Include:
- File paths in a following format:
./path/to/file.js:line_number(DO NOT include ranges just where the issue is) - Issues found
- Severity
- Recommendations
- File paths in a following format:
Example Output
| Category | Assessment | Notes |
|----------------|------------|-------------------------------------------------------|
| Quality ✓ | Good | Clean JWT implementation following best practices |
| Security ⚠️ | Poor | Critical JWT verification vulnerability present |
| Performance ✓ | Good | Efficient key caching and library migration |
| Architecture ✓ | Good | Well-structured auth system with feature flag support |
Improvements Needed
| File | Issue | Severity | Recommendation |
|---------------------------------------------|------------------------------------------|----------|---------------------------------------------------------------------|
| ./src/util/jwt-token.ts:26 | Incorrect key selection for verification | High | Use publicKey instead of checking privateKey for token verification |
| ./src/middlewares/auth-middleware.ts:68 | Hardcoded httpOnly setting | Medium | Use consistent auth v2 flag check like in login route |
| ./src/app/portal/api/user/login/route.ts:82 | Age verification expiry inconsistency | Low | Consider using consistent expiry calculation method |
DO NOT include any other text, explanations, or comments outside the markdown table.
Claude Code Integration
- Uses Glob for systematic file discovery
- Leverages Grep for pattern-based analysis
- Applies Read for deep code inspection
- Maintains structured analysis reporting
/commit-suggest - Suggests a commit message for current changes
Purpose
This command suggests a well-formatted commit message with conventional commit messages based on the current changes in the repository.
Usage
/commit-suggest
Force breaking change structure with:
/commit-suggest --breaking
Force commit type with:
/commit-suggest --type <type>
Where <type> is one of: feat, fix, docs, style, refactor, perf, test, chore
Force ticket ID with:
/commit-suggest --ticket <ticket>
What This Command Does
-
Runs
.claude/scripts/find-ticket-from-branch.shscript to extract a related ticket ID from the current branch name and include it in the commit message if found- If a
--ticket <ticket>argument is provided, it MUST use that ticket ID instead of extracting from branch name - If no ticket ID is found you MUST prompt the user and wait to provide one before proceeding any steps further
- If a
-
Checks staged files with
git status- If no files are staged, automatically adds all modified/new files with
git add .
- If no files are staged, automatically adds all modified/new files with
-
Analyzes the changes with
git diff --cachedto understand what is being committed. Quickly identify:- File types modified (components, tests, docs, config, etc.)
- Nature of changes (new features, bug fixes, refactoring, etc.)
- Scope of impact (single feature, multiple areas, etc.)
-
Suggests a conventional commit message that accurately reflects the changes being committed
[<JIRA ticket reference>] <type>: <description>-
Types: feat, fix, docs, style, refactor, perf, test, chore
-
Use present tense, imperative mood
-
Keep first line under 72 characters
-
Be specific but concise
-
Use multiple lines if necessary
-
Single-line example:
[PROJ-123] fix: resolve memory leak in rendering process -
Multi-line example:
[PROJ-123] feat: add user authentication module - Implement login and registration endpoints - Add JWT-based authentication - Update user model with password hashing
-
-
Outputs the suggested git commit command with the message:
git commit -m "<suggested message>" -
Copies the suggested git commit command to clipboard with
pbcopy
Important Notes
- Do NOT execute the commit, only suggest the commit message and copy the commit command to clipboard
- You MUST follow conventional commit standards when suggesting the commit message
- You MUST suggest a commit message that accurately reflects the changes being committed
- Prioritize speed - make quick, accurate assessments
- Follow conventional commit standards strictly
- Be decisive in commit type classification
- Ensure commit message accurately reflects the actual changes
- Handle edge cases gracefully (no changes, merge conflicts, etc.)
Usage
/e2e-test:plan
Execution
- Explore $ARGUMENTS website and gathering information about its functionalities with e2e-test-qa subagent.
- With the gathered data, plan e2e test scenarios for later implementation into @test_plan.md file with e2e-test-planner subagent.
Usage
/e2e-test:write
Or, to focus on a specific section of the test plan:
/e2e-test:write [test_plan_section]
Execution
- Read the @test_plan.md in the project root directory and create e2e playwright test scenarios based on unmarked items and prompted plan sections
[test_plan_section]with e2e-test-writer subagent. - After finishing creating the tests, update the @test_plan.md file by marking the completed items with a checkmark.
⚠️ Schema: This command follows
.claude/command-schema.md. Read schema before modifying. If not found, ask user.
Feature Documentation Generator
Produces three complementary deliverables for a given feature: a full BDD specification, a business-focused Mermaid flowchart, and a technical Mermaid sequence diagram based on the feature's description and codebase behavior.
Purpose
This command analyzes source code evidence files and produces comprehensive documentation that captures both business behavior and technical implementation of a feature.
Use when:
- Documenting a new or existing feature for QA, product design, or reimplementation
- Creating specifications that bridge business requirements and technical implementation
- Generating visual documentation of complex feature workflows
- Establishing a complete behavioral blueprint for a feature
Do not use when:
- You need only a quick summary (use simpler documentation approaches)
- The feature is trivial and doesn't warrant three-document analysis
Key Principles
Transaction Completeness: Documentation captures the entire user transaction from initial action to application quiescence (idle state), not just the code within evidence files. The feature is not complete until the application reaches idle state with no pending operations and the user sees the final result.
- Anti-Pattern: "Login feature ends when LoginViewController calls completion"
- Correct: "Login feature ends when user sees main screen and app is idle"
Bidirectional Tracing: Trace code paths in BOTH directions:
- Forward: What happens after the feature completes (callbacks, navigation, state changes)
- Backward: What can invoke this feature and with what parameters/state
Features may behave differently based on entry context (e.g., Login screen showing "account blocked" toast when entered after forbidden auth state).
1:1 Correspondence: Maintain strict correspondence between documents:
- Between BDD scenarios and flowchart branches (business perspective)
- Between BDD scenarios and sequence diagram flows (technical perspective)
- Between flowchart business actions and sequence diagram technical implementations
Source Code as Truth: If contradictions are found during validation, always defer to the source code as the authoritative source. Documentation must match implementation.
Inputs
Expects: JSON object with feature metadata Required: Yes
JSON Schema
{
"feature_name": "Feature Name",
"category": "Category",
"surface": ["Screen", "Component"],
"actors": ["Guest", "EndUser"],
"flags_or_flavors": [],
"evidence": [ // OPTIONAL - will be discovered if not provided
"relative/path/to/file1.kt",
"relative/path/to/file2.xml:SpecificClass"
],
"description": "Business-level description of the feature"
}
Parameter Definitions
| Parameter | Required | Type | Description |
|---|---|---|---|
feature_name | Yes | string | Name of the feature (converted to lowercase with hyphens for folder/file names) |
category | Yes | string | Business category (e.g., "Acquisition", "Retention", "Monetization") |
surface | Yes | array | UI surface types where feature appears (e.g., "Screen", "Dialog", "Component", "Widget") |
actors | Yes | array | User roles interacting with the feature (e.g., "Guest", "EndUser", "Admin", "Performer") |
flags_or_flavors | No | array | Feature flags or build flavors that control this feature (empty if always enabled) |
evidence | No | array | File paths pointing to source code implementing the feature (if not provided, will be discovered based on feature_name and description) |
description | Yes | string | Concise business-level description of what the feature does and its purpose |
Evidence Path Format
Evidence paths support multiple formats:
- Simple path:
path/to/file.ext - Path with class reference:
path/to/file.ext:ClassName - Path with method reference:
path/to/file.ext:ClassName.methodName
Usage
/feature-documentation {"feature_name": "User Login", "category": "Authentication", "surface": ["Screen"], "actors": ["Guest"], "flags_or_flavors": [], "evidence": ["src/features/auth/LoginScreen.tsx"], "description": "Email and password authentication flow"}
Prerequisites
Gate 1: Evidence Available or Discoverable
Check: Evidence files are provided OR feature can be discovered from codebase Pass: Proceed to Gate 2 Fail: Exit only if discovery yields no results
If evidence provided:
- Verify at least one evidence file path can be resolved
- Mark unresolvable paths as
[MISSING EVIDENCE: path] - Continue with available files
If evidence not provided:
- Proceed to Step 2 for autonomous evidence discovery
Gate 1.5: Variant Implementation Verification
Check: If ANY evidence filename contains variant indicators (Default, Base, Standard, Main, Common, Impl), variant search has been performed
Pass: All variant implementations documented in evidence list, proceed to Gate 2
Fail: Return to Step 2 and complete variant discovery
Fail Recovery Procedure:
- Extract base name from indicator-containing filename (e.g.,
LoginUseCaseDefault→LoginUseCase) - Search for sibling classes matching base name pattern
- Search dependency injection / factory modules for Provider patterns referencing the base type
- Add all discovered variants to evidence list
- Document the selection mechanism (build-time flavor, runtime configuration, DI module)
- Re-validate this gate
Verification Questions (must answer ALL):
| Question | Required Answer |
|---|---|
| Does any evidence filename contain variant indicators? | Yes (list them) or No |
| If yes, what is the base name? | [Must name extracted base] |
| What sibling implementations exist? | [Must list all or state "None found" with search evidence] |
| What determines variant selection? | [Must identify mechanism: DI module, build flavor, runtime config] |
Gate 2: Mermaid CLI Available
Check: Project has Mermaid CLI installed (npx mmdc --version succeeds)
Pass: Proceed to Process
Fail: Warn user but continue (syntax validation will be skipped)
Process
Step 1: Parse JSON Input
Extract feature metadata from the JSON input:
- Parse the JSON object
- Extract
feature_nameand convert to kebab-case for folder/file naming - Store all metadata for use in output generation
Step 2: Resolve or Discover Evidence Files
Case A: Evidence Provided
For each evidence entry:
Substep 2.1: Parse Evidence Path
- Extract file path and optional class/method reference (after
:) - Example:
SplashActivity.kt:SplashActivity→ file:SplashActivity.kt, focus:SplashActivityclass
Substep 2.2: Locate Files Priority order:
- Try resolving as absolute path
- Try relative to current working directory
- Use Glob tool to search for filename in project
- Check paths relative to git repository root
If file not found:
- Mark as
[MISSING EVIDENCE: path] - Continue with available files
Substep 2.3: Extract Class/Method Context
- If reference provided (after
:), focus analysis on that specific component - Example:
AndroidManifest.xml:SplashActivity→ focus on SplashActivity configuration
Case B: Evidence Not Provided (Autonomous Discovery)
When evidence array is empty or not provided, discover relevant source files:
Substep 2.4: Search by Feature Name
- Convert feature_name to search patterns (e.g., "User Login" →
*Login*,*login*,*user-login*) - Search for source files matching the pattern, excluding:
- Dependency directories (
node_modules,vendor,Pods,.gradle,packages) - Build outputs (
dist,build,out,target,.next,__pycache__) - Version control (
.git,.svn) - Assets and media files (images, fonts, videos)
- Dependency directories (
- Prioritize files with common source code extensions for the detected project type
- Filter results by reading file headers to confirm source code (not assets, configs, or generated files)
Substep 2.5: Search by Surface Type
-
Use surface hints to identify architectural layer:
Surface Category Includes Common Patterns Presentation Screen, Page, Dialog, Modal, Component, Widget *Screen*,*Page*,*View*,*Dialog*,*Modal*,*Component*API/Endpoint Endpoint, Route, Controller, Handler *Controller*,*Handler*,*Router*,*Route*,*Resource*Service/Logic Service, UseCase, Interactor, Manager *Service*,*UseCase*,*Interactor*,*Repository*,*Manager*Data Repository, Store, Cache, Model *Repository*,*Store*,*Model*,*Entity*,*DAO* -
Patterns are illustrative; adapt to project naming conventions
Substep 2.6: Search by Description Keywords
- Extract key terms from description
- Use Grep to find files containing those terms
- Prioritize files with multiple keyword matches
Substep 2.7: Validate Discovered Files
- Read candidate files to confirm relevance
- Filter out test files, mocks, and unrelated matches
- Rank by relevance based on:
- Feature name match strength
- Surface type alignment
- Description keyword density
- Select top candidates as evidence files
Substep 2.8: Variant Implementation Discovery
Evidence files may represent one of several parallel implementations. Search for variants when indicators are present.
Indicators:
- File or class name contains qualifiers:
Default,Base,Standard,Main,Common,Impl - Class inherits from abstract base or implements interface/protocol
- Project structure contains parallel source directories for build variants
- Dependency injection or factory patterns reference multiple concrete types
When indicators detected:
- Search for sibling implementations sharing the same base name or parent type
- Examine build configuration and DI modules to identify all variants
- Add all discovered variant files to evidence list
- Document the selection mechanism (build-time, runtime, configuration)
Rationale: A feature documented from only one variant will miss conditional behavior present in other variants.
If no files discovered:
- Report
[DISCOVERY FAILED: No matching source files found for "${feature_name}"] - Exit with suggestions for manual evidence specification
Step 3: Analyze Source Code
Read all resolved evidence files and identify:
- Dependencies (imports, service calls, repository usage)
- Business logic and validation rules
- State transitions and navigation flows
- Error handling patterns
- External service integrations
Step 4: Expand Analysis with Transaction Tracing
Evidence files are the starting point, not the boundary. Treat the feature as an atomic transaction from user initiation to system quiescence.
Substep 4.1: Forward Tracing
Trace what happens after feature code executes:
- Direct method calls within evidence files
- Indirect callbacks, delegates, and observers
- Navigation/routing logic that redirects control flow
- Background tasks, async operations, and delayed executions
- State changes propagated through stores, repositories, or event buses
- Lifecycle events triggered in parent/coordinator components
Substep 4.1b: Parent Coordinator Tracing (MANDATORY)
CRITICAL: Feature completion is NOT the transaction end. You MUST trace what the PARENT coordinator/flow does after receiving the completion callback.
Discover invocations by searching for common patterns:
| Paradigm | Invocation Patterns to Search |
|---|---|
| Navigation/Routing | navigate(${FEATURE}), router.push(${FEATURE}), goto ${FEATURE}, redirect(${FEATURE}) |
| Instantiation | new ${FEATURE}(), ${FEATURE}.create(), ${FEATURE}Factory, build${FEATURE}() |
| Event-Driven | dispatch(${FEATURE}Action), emit('${FEATURE}'), publish(${FEATURE}Event), send(${FEATURE}Command) |
| Dependency Injection | provide(${FEATURE}), inject(${FEATURE}), resolve(${FEATURE}), ${FEATURE}Provider |
| Function Call | start${FEATURE}(), open${FEATURE}(), show${FEATURE}(), handle${FEATURE}() |
Examine each caller to understand:
- What parameters/state are passed to the feature
- What the caller does when the feature completes
- Any conditional logic before or after invocation
You MUST identify and document:
- Parent orchestrator name — the component that invokes this feature (e.g.,
AppRouter,MainController,RootCoordinator,Shell,RequestHandler) - What parent does after feature completion:
- Conditional navigation (state-dependent routing)
- Deferred operations (queued actions executed post-completion)
- State machine transitions
- Analytics or tracking events
- Any conditional post-completion logic based on:
- User state or session data
- Feature flags or configuration
- Pending operations queued before this feature started
Example pattern to trace:
${FEATURE_NAME}Flow.completion called
↓
ParentFlow receives completion
↓
ParentFlow checks [CONDITION A] → [DOCUMENT IF BRANCHES]
↓
ParentFlow checks [CONDITION B] → [DOCUMENT IF BRANCHES]
↓
ParentFlow starts NextFlow
↓
User sees destination screen [ACTUAL IDLE STATE]
Anti-pattern (WRONG):
${FEATURE_NAME}Flow.completion called → [STOP HERE - INCOMPLETE!]
Substep 4.2: Backward Tracing
Identify all entry points into this feature:
Discover:
- All callers that invoke, instantiate, or route to this feature
- Import or dependency statements that reference this feature
- Route definitions, navigation mappings, or URL patterns targeting this feature
For each caller, analyze:
- Parameters, props, or state passed to the feature
- Pre-invocation actions (notifications, analytics, permission checks, state preparation)
- Post-invocation handling (callbacks, subscriptions, navigation on completion)
- Whether different callers provide different contexts that affect feature behavior
Entry Point Documentation Format:
For each entry point discovered, capture in structured format:
| Field | Required | Description |
|---|---|---|
| Caller | Yes | Specific class and method that invokes this feature |
| Condition | Yes | What triggers this entry path (user action, system event, state) |
| Parameters | Yes | All parameters passed, with types and possible values |
| Pre-display Actions | If any | Operations performed BEFORE feature UI is shown |
| Post-display Actions | If any | Operations performed AFTER feature UI is shown |
| Context Effects | If any | How this entry context changes feature behavior |
This structured format must be used when documenting entry points in the BDD specification.
Substep 4.3: External UI Trigger Tracing
Identify external code that triggers UI elements associated with this feature:
- Toasts, snackbars, or notifications shown before/after feature display
- Conditional UI elements based on feature state or entry context
- Deep link or URL handlers that route to this feature
Substep 4.4: Determine Idle State
Continue tracing until reaching idle state conditions:
- No pending asynchronous operations (promises, futures, callbacks, background tasks, scheduled jobs)
- Navigation/routing has settled (final view/page/screen rendered to user)
- All data persistence complete (database writes, cache updates, secure storage, session state, user preferences)
- All network requests completed and responses processed
- All UI updates rendered and animations/transitions finished
- Application returns to awaiting user input or external event
Discovery Techniques:
- Completion handlers: Trace what happens after feature-specific code completes
- Navigation flows: Follow scene/activity transitions until final destination
- State observers: Track reactive state changes across app layers
- Lifecycle callbacks: Examine parent component lifecycle methods
- Deferred operations: Check for scheduled work, timers, or background jobs
Substep 4.5: Checkpoint — Transaction Completeness
GATE: Do not proceed to Step 5 until ALL items are verified.
Required Checklist:
- Parent coordinator identified: Named the specific class that STARTS this feature
- Parent's completion handler read: Examined the actual code that executes when this feature's completion callback fires
- Post-completion actions documented: Listed ALL conditional branches and actions the parent takes after this feature completes
- True idle state verified: Confirmed the FINAL screen user sees (not intermediate navigation)
- Cross-cutting concerns captured: Documented any behaviors triggered by parent that affect user experience
- Variant implementations verified: If any evidence filename contains variant indicators (Default, Base, Standard, Main, Common, Impl), all sibling implementations identified and added to evidence
Verification Questions (must answer ALL):
| Question | Your Answer |
|---|---|
| What class STARTS this feature? | [Must name specific class, not "unknown"] |
| What does parent do on completion? | [Must describe actual code behavior] |
| Any conditional post-completion flows? | [Must verify YES with details, or NO with evidence] |
| What screen does user ACTUALLY see? | [Must name final destination screen] |
| Any evidence files contain variant indicators? | [Must answer YES with list, or NO] |
| If YES, all variants discovered and documented? | [Must confirm variants added to evidence or state "No siblings found" with search evidence] |
If not satisfied: Return to Substep 4.1b and trace parent coordinator
Example of PASSING:
✓ Parent: ParentFlow (ParentFlow.swift:45)
✓ Completion handler: handle${FEATURE_NAME}Completion() line 234
✓ Post-completion: conditionalCheck (240), stateTransition (248), else NextFlow (255)
✓ Final screen: DestinationViewController
✓ Cross-cutting: [List any behaviors triggered by parent, not by this feature directly]
Example of FAILING:
✗ Parent: "${FEATURE_NAME}Flow itself" → WRONG: Must trace to PARENT
✗ Completion: "Not examined" → WRONG: Must read actual code
✗ Post-completion: "Feature just completes" → WRONG: Must verify parent's actions
Step 5: Create BDD Specification
Action: Create folder ${FEATURE_NAME}/ and write ${FEATURE_NAME}.bdd.md immediately.
Generate ${FEATURE_NAME}/${FEATURE_NAME}.bdd.md with:
Content Structure:
# BDD Specification: ${FEATURE_NAME}
> **Location:** `${FEATURE_NAME}/${FEATURE_NAME}.bdd.md`
## Metadata
- **Category:** ${CATEGORY}
- **Surface:** ${SURFACE} (e.g., Screen, Dialog, Component)
- **Actors:** ${ACTORS} (e.g., Guest, EndUser, Admin)
- **Feature Flags/Flavors:**
- `flagName` - Effect on feature behavior when enabled/disabled
- `anotherFlag` - What this flag controls
- (or "None - Always enabled" if no conditional behavior)
- **Variant Implementations:** (if applicable)
- `VariantA` - Used when [condition]
- `VariantB` - Used when [condition]
- **Selection Mechanism:** [DI module / build flavor / runtime config]
- **Evidence Files:**
- `path/to/file1.kt`
- `path/to/file2.xml:ClassName`
## Overview
${DESCRIPTION}
## Entry Points
### Entry Point 1: [Context Name]
- **Caller:** `ClassName.methodName()`
- **Condition:** What triggers this entry path
- **Parameters:** List all parameters with types
- **Pre-display Actions:** Operations before feature UI shown (if any)
- **Context Effects:** How this context affects feature behavior (if any)
### Entry Point 2: [Context Name]
...
## Business Rules
### BR-001: [Rule Name]
- **Rule:** [Precise description with specific values/thresholds]
- **Applies to:** [Which scenarios/conditions]
### BR-002: [Rule Name]
...
## Scenarios
### Scenario 1: ...
Given ...
When ...
Then ...
### Scenario 2: ...
...
BDD Requirements:
-
Document ALL user roles, permissions, validations, and preconditions
-
Capture every main path, alternate path, and error/edge case
-
Include limits, retries, rate limits, and timeouts
-
Mark external dependencies as
[REFERENCE: ServiceName]or[MISSING LINK] -
Document complete user transaction from initiation to idle state
-
Include cross-cutting concerns discovered during transaction tracing
-
Create scenario for each unique entry context that affects user experience
-
Each scenario must be exhaustive and business-readable
-
Extract and document all business rules with unique identifiers (BR-001, BR-002, etc.)
-
Business rules include: validation thresholds, selection logic, state machine transitions, conditional behaviors, rate limits, retry policies
-
Each rule must include specific values, not generic descriptions (e.g., "password minimum 8 characters" not "password must meet requirements")
-
Compound Condition Extraction: For conditional behaviors (feature triggers, navigation decisions, UI state changes), extract the COMPLETE boolean expression from source code. Do not paraphrase or simplify.
Anti-pattern (incomplete):
Rule: Feature X is shown when the user is eligible and the feature is enabledCorrect pattern (complete):
Rule: Feature X is shown when ALL conditions are true: (1) userType != TYPE_A (2) featureFlag.isEnabled == true (3) user.status == ACTIVEExtraction method: Locate the
if/when/guardstatement controlling the behavior and transcribe each sub-condition verbatim with its comparison operator and value. -
Document system-triggered behaviors: UI state changes from system events (keyboard visibility, orientation, network status), lifecycle callbacks, and timer-based operations
Step 6: Create Business Flowchart
Action: Write ${FEATURE_NAME}/${FEATURE_NAME}.flowchart.mmd immediately.
Generate ${FEATURE_NAME}/${FEATURE_NAME}.flowchart.mmd with:
Syntax Requirements:
- Use
flowchart TD(top-down layout) - Follow official Mermaid syntax: https://docs.mermaidchart.com/mermaid-oss/syntax/flowchart.html
Content Requirements:
- Represent every scenario and condition from BDD
- Include all decision points (
{condition}nodes) - Show all success, alternate, and failure paths
- Represent forks and joins as
((Fork))and((Join)) - Include business states or milestones
- Mark external dependencies as
[REFERENCE: ServiceName] - Model preconditions, validations, and permission checks
- Show external calls or async processes
- Include retry and fallback logic
- Capture all granular business behavior
Exclusions (Technical Details):
- Do NOT include internal variable setting or parameter assignments
- Do NOT break down API request construction into individual steps
- Focus on WHAT happens from business perspective, not HOW
Color Coding:
Apply styles using :::className syntax after node definitions.
IMPORTANT: Apply colors to ALL nodes on the critical path, including decision boxes, to create an unbroken visual flow.
flowchart TD
A[Start: User initiates feature]:::criticalPath --> B{Preconditions met?}:::criticalPath
B -->|No| X[Show error]:::errorPath
B -->|Yes| C[Validate input]:::criticalPath
C -->|Invalid| Y[Show validation error]:::errorPath
C -->|Valid| D[Send request to REFERENCE: ExternalService]:::externalCall
D --> E{Operation succeeded?}:::criticalPath
E -->|Yes| F[Persist result]:::criticalPath
E -->|No| G[Retry or flag failure]:::alternatePath
F --> Z[End]:::criticalPath
%% Color definitions
classDef criticalPath fill:#90EE90,stroke:#228B22,stroke-width:3px,color:#000
classDef errorPath fill:#FFB6C1,stroke:#DC143C,stroke-width:2px,color:#000
classDef alternatePath fill:#FFD700,stroke:#FF8C00,stroke-width:2px,color:#000
classDef externalCall fill:#87CEEB,stroke:#4169E1,stroke-width:2px,color:#000
Color Scheme:
| Class | Color | Usage |
|---|---|---|
criticalPath | Green (#90EE90) | Main happy path nodes AND decision boxes on critical path |
errorPath | Red (#FFB6C1) | Error handling, failure nodes, decision boxes leading to errors |
alternatePath | Yellow (#FFD700) | Alternate valid paths (not errors, not main flow) |
externalCall | Blue (#87CEEB) | External service dependencies |
Step 7: Create Technical Sequence Diagram
Action: Write ${FEATURE_NAME}/${FEATURE_NAME}.sequence.mmd immediately.
Generate ${FEATURE_NAME}/${FEATURE_NAME}.sequence.mmd with:
Syntax Requirements:
- Start with
sequenceDiagramkeyword (no spaces, no hyphens) - Follow official Mermaid syntax: https://docs.mermaidchart.com/mermaid-oss/syntax/sequenceDiagram.html
Content Requirements:
- Show ALL technical implementation details
- Include all actors, components, classes, and services
- Document every method call in execution flow
- Show parameter passing and data transformations
- Include API requests/responses with full technical details (see API Documentation Requirements below)
- Document database operations
- Show state changes and variable assignments
- Include internal validations and checks
- Document exception handling and error propagation
- Show callbacks, listeners, and async operations
- Include threading details (main thread, background threads, coroutines)
- Document lifecycle events
Architecture Layer Completeness:
The sequence diagram must show ALL architectural layers involved in data flow, not just entry and exit points.
Required layers to identify and include (when present):
- Presentation layer (Views, Activities, ViewControllers, Components)
- Domain layer (UseCases, Interactors, Services)
- Data layer (Repositories, DataStores, DAOs)
- Network layer (API clients, CloudDataStores, HTTP services)
- Persistence layer (Local storage, Caches, Databases)
Anti-pattern (incomplete):
Repository->>API: request()
Correct pattern:
Repository->>DataStore: getData()
DataStore->>APIClient: request()
APIClient->>HTTPService: execute()
If intermediate layers exist between a caller and an external service, they must appear as separate participants.
API Documentation Requirements:
Every API call in the sequence diagram MUST include sufficient detail for complete reimplementation. API documentation follows the OpenAPI 3.1 Specification (https://swagger.io/specification/).
Required API Details (OpenAPI-aligned):
| OpenAPI Element | Description | Example |
|---|---|---|
servers[].url | Base URL / domain | https://api.example.com |
paths.{path} | Endpoint path with path parameters | /v1/auth/login, /users/{userId} |
paths.{path}.{method} | HTTP operation | post, get, put, delete |
parameters | Path, query, header, cookie params | in: header, name: Authorization |
requestBody.content | Request body schema by media type | application/json: {schema: ...} |
responses.{code} | Response schemas by status code | 200: {content: ...}, 401: {content: ...} |
security | Authentication requirements | bearerAuth: [] |
API Documentation Format in Sequence Diagram:
API calls in the sequence diagram should reference the OpenAPI specification file using operationId. Do NOT duplicate API details inline—the OpenAPI file is the single source of truth.
sequenceDiagram
participant App as Application
participant API as AuthService API
App->>API: POST /v1/auth/login
Note right of API: See: openapi.yaml#loginUser
API-->>App: 200 OK + AuthResponse
Reference Format: See: openapi.yaml#{operationId}
This approach:
- Maintains single source of truth in OpenAPI file
- Keeps sequence diagrams readable and focused on flow
- Enables API changes without updating diagrams
- Allows code generation from authoritative OpenAPI spec
Companion OpenAPI Specification File (Required for features with API calls)
Create a companion file ${FEATURE_NAME}/${FEATURE_NAME}.openapi.yaml following OpenAPI 3.1 specification:
openapi: 3.1.0
info:
title: ${FEATURE_NAME} API
description: API endpoints for the ${FEATURE_NAME} feature
version: 1.0.0
servers:
- url: https://api-gw.production-domain.com
description: Production API Gateway
- url: https://api-gw.staging-domain.com
description: Staging environment (if applicable)
# List ALL actual production domains used by this feature
# Do NOT use placeholder domains like example.com
paths:
/v1/auth/login:
post:
operationId: loginUser
summary: Authenticate user with email and password
tags:
- Authentication
parameters:
- name: X-Client-Version
in: header
required: true
schema:
type: string
description: Application version string
- name: X-Device-ID
in: header
required: false
schema:
type: string
description: Unique device identifier
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/LoginRequest'
responses:
'200':
description: Successful authentication
content:
application/json:
schema:
$ref: '#/components/schemas/AuthResponse'
'400':
description: Validation error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Invalid credentials
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'403':
description: Account locked
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'429':
description: Rate limited
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
example:
error: rate_limited
message: Too many login attempts
details:
retry_after: 60
security: [] # Public endpoint
components:
schemas:
LoginRequest:
type: object
required:
- email
- password
properties:
email:
type: string
format: email
description: User email address
password:
type: string
minLength: 8
description: User password
remember_me:
type: boolean
default: false
description: Extend token lifetime
AuthResponse:
type: object
required:
- access_token
- refresh_token
- expires_in
- token_type
- user
properties:
access_token:
type: string
description: JWT access token
refresh_token:
type: string
description: Refresh token for token renewal
expires_in:
type: integer
description: Seconds until access_token expires
token_type:
type: string
enum: [Bearer]
user:
$ref: '#/components/schemas/User'
User:
type: object
required:
- id
- email
- display_name
properties:
id:
type: string
format: uuid
description: User UUID
email:
type: string
format: email
display_name:
type: string
avatar_url:
type: string
format: uri
nullable: true
ErrorResponse:
type: object
required:
- error
- message
properties:
error:
type: string
enum:
- validation_error
- invalid_credentials
- account_locked
- rate_limited
message:
type: string
description: Human-readable error message
details:
type: object
nullable: true
description: Additional error context
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
description: JWT token obtained from login endpoint
Minimum Requirements for API Reimplementation (OpenAPI Checklist):
The following MUST be present in the ${FEATURE_NAME}.openapi.yaml:
-
openapiversion specified (3.1.0) -
serversarray with ACTUAL production URLs (not placeholder domains like example.com) - If multiple environments or regional domains exist, ALL are listed in
servers - All
pathswith complete endpoint definitions - All
parameters(path, query, header) within,required, andschema -
requestBodywithcontentmedia type and schema reference - All
responseswith status codes, descriptions, and schema references -
components/schemaswith fully typed request/response objects -
components/securitySchemesif authentication required -
securityrequirements on operations or globally - Schema
requiredarrays for mandatory fields - Schema
type,format, and constraints (minLength,enum, etc.) - Lifecycle/inverse endpoints documented (if applicable)
- Error recovery endpoints documented (if applicable)
Related Endpoints Discovery:
The OpenAPI specification must include not only endpoints directly called by the feature, but also:
- Lifecycle endpoints - Endpoints that undo/reverse the feature's action (e.g., logout for login, unsubscribe for subscribe, revoke for grant)
- Dependent endpoints - Endpoints called as prerequisites or follow-ups within the same user transaction
- Error recovery endpoints - Endpoints called when the primary flow fails
Discovery method:
- Search for inverse operations in codebase (create↔delete, login↔logout, subscribe↔unsubscribe)
- Trace error handlers to identify recovery API calls
- Examine session/state cleanup code for additional endpoints
Diagram Elements:
- Use activation boxes (
activate/deactivate) for execution context - Use
loopblocks for iterations - Use
altblocks for conditional logic - Use
parblocks for concurrent operations - Use
Noteannotations for clarifications
Color Coding with rect Blocks:
CRITICAL PATH RULES:
- ONLY include main success/happy path where everything works correctly
- NEVER include error handling, validation failures, or negative conditions inside critical path
rectblocks - NEVER include
altblocks with failure cases inside critical path sections - Error recovery and validation failures must be in separate error path
rectblocks
sequenceDiagram
actor User
participant View as LoginView
participant Handler as LoginHandler
participant Service as AuthService
rect rgb(200, 255, 200)
Note over User,View: [CRITICAL PATH - Happy Flow]
User->>View: Submit credentials
View->>Handler: login(credentials)
Handler->>Service: authenticate(credentials)
Service-->>Handler: Success(tokens)
Handler-->>View: State.Authenticated
View->>View: navigateTo(destination)
end
rect rgb(255, 200, 200)
Note over User,View: [ERROR PATH - Invalid Credentials]
User->>View: Submit credentials
View->>Handler: login(credentials)
Handler->>Service: authenticate(credentials)
Service-->>Handler: Error(INVALID_CREDENTIALS)
Handler-->>View: State.Error
View->>View: showError(message)
end
Color Scheme for rect blocks:
| RGB Value | Usage |
|---|---|
rgb(200, 255, 200) | Critical path sections (light green) |
rgb(255, 200, 200) | Error handling sections (light red) |
rgb(255, 255, 200) | Alternate path sections (light yellow) |
rgb(200, 230, 255) | External service calls (light blue) |
Step 8: Checkpoint — Entry Point Coverage
GATE: Do not proceed until satisfied.
- All callers of feature's entry point identified (Step 4.2)
- Each caller's context analyzed for parameters and pre/post-display actions
- External UI triggers traced (Step 4.3)
- BDD scenarios exist for each unique entry context that affects user experience
If not satisfied: Return to Step 4 and complete bidirectional tracing
Step 9: Validate Mermaid Syntax
Run Mermaid CLI to validate both diagram files:
# Flowchart validation
npx mmdc -i ${FEATURE_NAME}/${FEATURE_NAME}.flowchart.mmd -o /dev/null
# Sequence diagram validation (use nul on Windows)
npx mmdc -i ${FEATURE_NAME}/${FEATURE_NAME}.sequence.mmd -o /dev/null
If syntax errors reported:
- Read error message carefully
- Identify line number and error type
- Fix syntax error in diagram file
- Re-run CLI validation
- Repeat until both diagrams pass without errors
Step 10: Cross-Document Validation
Compare every scenario in BDD against both diagrams:
Verification Checklist:
- Each BDD scenario has corresponding path in flowchart
- Each BDD scenario has corresponding sequence in sequence diagram
- All decision points in flowchart are described in BDD scenarios
- All technical method calls in sequence diagram support BDD behaviors
- Success, error, and alternate paths match across all three documents
- Preconditions, validations, and outcomes are consistently represented
- Sequence diagram shows technical HOW for flowchart's business WHAT
- All entry point scenarios documented
Critical Path Verification:
- Flowchart: Critical path nodes (including decision boxes) ONLY on main success path
- Sequence diagram: Critical path
rectblocks ONLY contain happy path - Error handling in separate colored sections
- No
altblocks with failure branches inside critical path colored blocks
API Reimplementation Verification (OpenAPI Compliance):
-
${feature-name}.openapi.yamlfile exists for features with API calls - OpenAPI
serversarray contains all API base URLs - All
pathsmatch endpoints shown in sequence diagram - All
parametersincludein,required, andschemaproperties - All
requestBodydefinitions includecontentwith media type and schema - All
responsesinclude status codes withcontentand schema references -
components/schemasdefine all request/response data types -
components/securitySchemesdefine authentication mechanisms if used - Schema
requiredarrays correctly identify mandatory fields - Schema properties include
type,format, and validation constraints - OpenAPI file validates against OpenAPI 3.1 specification
- A developer could generate API client code from the OpenAPI spec
If discrepancies found: Document as [VALIDATION ISSUE] and proceed to Step 11
Step 11: Reconcile Against Source Code
For any discrepancies or [VALIDATION ISSUE] markers:
- Return to source code
- Re-analyze actual implementation behavior
- Determine which document(s) are incorrect
- Update incorrect document(s) to match source code
- Remove
[VALIDATION ISSUE]markers once resolved
Areas to verify:
- Business logic (BDD & Flowchart): Validation rules, error handling, business sequences
- Technical implementation (Sequence Diagram): Method calls, class interactions, data flow
- External service dependencies
- State transitions
- Exception handling and error propagation
- API contracts: Verify documented domains, paths, request/response schemas match actual network layer implementation
Outputs
Directory Structure
${feature-name}/
├── ${feature-name}.bdd.md # BDD specification with metadata
├── ${feature-name}.flowchart.mmd # Color-coded business flowchart
├── ${feature-name}.sequence.mmd # Color-coded technical sequence diagram
└── ${feature-name}.openapi.yaml # OpenAPI 3.1 specification (if feature has API calls)
Naming Convention: Convert feature name to lowercase with hyphens replacing whitespaces (e.g., "Email Password Login" → email-password-login/)
File Specifications
${feature-name}.bdd.md
- Metadata section with category, surface, actors, flags, evidence
- Overview from description
- Exhaustive BDD scenarios covering all paths
- References to external dependencies
- Annotations for unclear logic or missing behavior
${feature-name}.flowchart.mmd
- Mermaid flowchart syntax (flowchart TD)
- All business logic paths visualized
- Color-coded critical path (unbroken green flow)
- Decision points, validations, external calls
- No technical implementation details
${feature-name}.sequence.mmd
- Mermaid sequence diagram syntax
- All technical implementation details
- Method calls, class interactions, data flow
- Color-coded rect blocks for path types
- Threading and lifecycle details
- API calls with full endpoint documentation (domain, path, method)
- Request/response schemas for all API interactions
${feature-name}.openapi.yaml
- Created for any feature that makes API calls
- Follows OpenAPI 3.1 Specification (https://swagger.io/specification/)
serversarray with base URLs for all API domainspathswith complete endpoint definitions andoperationIdparametersfor path, query, header params with schemasrequestBodywith content type and schema referencesresponsesfor all status codes with schema referencescomponents/schemaswith fully typed data modelscomponents/securitySchemesfor authentication definitions- Enables code generation and API client reimplementation
Examples
Example 1: With Evidence Provided
Input:
{
"feature_name": "Splash Screen",
"category": "Onboarding",
"surface": ["Screen"],
"actors": ["Guest", "EndUser"],
"flags_or_flavors": [],
"evidence": [
"src/features/splash/SplashScreen.tsx",
"src/features/splash/SplashHandler.ts"
],
"description": "Initial app launch screen displayed during startup and initialization"
}
Process:
- Parse JSON: Extract "Splash Screen", convert to
splash-screen - Resolve evidence: Locate SplashScreen.tsx and SplashHandler.ts
- Analyze code: Read implementation, identify dependencies, lifecycle, navigation
- Create BDD: Document all scenarios (app launch, initialization, navigation, errors)
- Create flowchart: Visualize business startup flow with color-coded critical path
- Create sequence diagram: Document technical implementation with method calls
- Validate: Run syntax validation, cross-check documents, reconcile with source
Output:
splash-screen/
├── splash-screen.bdd.md
├── splash-screen.flowchart.mmd
└── splash-screen.sequence.mmd
Example 2: Without Evidence (Autonomous Discovery)
Input:
{
"feature_name": "User Login",
"category": "Authentication",
"surface": ["Screen"],
"actors": ["Guest"],
"flags_or_flavors": [],
"description": "Email and password authentication flow for user sign-in"
}
Process:
- Parse JSON: Extract "User Login", convert to
user-login - Discover evidence:
- Search for
*Login*files → findsLoginScreen.tsx,LoginHandler.ts - Search by surface "Screen" → confirms
LoginScreen.tsx - Search by keywords "authentication", "sign-in" → finds
AuthService.ts - Validate and select:
LoginScreen.tsx,LoginHandler.ts,AuthService.ts
- Search for
- Analyze discovered code: Read implementations, trace dependencies
- Create BDD, flowchart, sequence diagram
- Validate all documents
Output:
user-login/
├── user-login.bdd.md
├── user-login.flowchart.mmd
└── user-login.sequence.mmd
Transaction Tracing Example
Login Feature Transaction:
[USER ACTION] User submits credentials
↓
[VALIDATION] Input validation (format, required fields)
↓
[SERVICE CALL] Authentication service calls backend API
↓
[API RESPONSE] Backend returns tokens or error
↓
[PERSISTENCE] Tokens stored in secure storage
↓
[COMPLETION] Feature signals success to parent
↓
[PARENT HANDLER] Parent orchestrator receives completion
↓
[STATE CHECK] Parent checks for pending actions (deep links, redirects)
↓
[NAVIGATION] Route to final destination
↓
[RENDER] Destination view displayed
↓
[IDLE] Application awaits next input [END]
Validation
Check 1: Mermaid Syntax Validation
Method: Run npx mmdc -i <file> -o /dev/null for each diagram
On success: Proceed to Check 2
On failure:
- Read error output to identify syntax error
- Locate line number in diagram file
- Fix syntax according to official Mermaid documentation
- Re-run validation
- Repeat until passes
Max retries: Until success
Check 2: BDD-Flowchart Consistency
Method: Compare each BDD scenario against flowchart paths On success: Proceed to Check 3 On failure:
- Identify missing or mismatched scenarios/paths
- Return to source code to verify correct behavior
- Update BDD or flowchart to match source
- Re-validate
Check 3: BDD-Sequence Consistency
Method: Compare each BDD scenario against sequence diagram flows On success: Proceed to Check 4 On failure:
- Identify missing or mismatched technical flows
- Return to source code to verify implementation
- Update sequence diagram to match source
- Re-validate
Check 4: Critical Path Integrity
Method: Verify critical path coloring follows rules On success: Proceed to Check 5 On failure:
- Identify nodes/blocks incorrectly colored as critical path
- Move error handling to appropriate colored sections
- Ensure unbroken visual flow on actual critical path
- Re-validate
Check 5: Entry Point Coverage
Method: Verify all entry points have corresponding BDD scenarios On success: Proceed to Check 6 On failure:
- Identify undocumented entry points
- Analyze each entry point's context and behavior
- Add BDD scenarios for each unique entry context
- Update diagrams to include new paths
- Re-validate
Check 6: Final Verification
Method: Perform final pass comparing BDD ↔ Flowchart ↔ Sequence Diagram ↔ Source Code On success: Validation complete
Verification Checklist:
- No contradictions exist between documents
- All business behaviors accurately captured
- All technical details accurately documented
- Three documents complement each other without duplication or conflict
- Critical paths correctly identified in both diagrams
- Error paths consistently documented
- Both Mermaid diagrams pass CLI syntax validation
On failure:
- Identify specific contradiction or gap
- Return to source code as authoritative reference
- Update affected document(s)
- Re-run all validation checks from Check 1
Error Handling
ERR-001: Evidence File Not Found
Symptoms:
- File path cannot be resolved
[MISSING EVIDENCE: path]annotation in output
Possible Causes:
- Path is relative but working directory differs from project root
- File was renamed or moved
- Typo in file path
Resolution Steps:
- Verify the file exists in the project
- Use Glob tool to search:
**/*filename* - Check git history for renames:
git log --follow --name-only -- "*filename*" - Update evidence path and retry
ERR-002: Mermaid Syntax Error
Symptoms:
npx mmdcreports parsing error- Diagram fails to render
Resolution Steps:
- Read error output to identify the specific error and line number
- Analyze the error message to understand the cause
- Locate the problematic line in the diagram file
- Fix the syntax error based on the error message context
- Re-run
npx mmdcvalidation - Repeat until diagram renders without errors
Reference: Consult official Mermaid documentation if error is unclear:
- Flowchart: https://docs.mermaidchart.com/mermaid-oss/syntax/flowchart.html
- Sequence: https://docs.mermaidchart.com/mermaid-oss/syntax/sequenceDiagram.html
ERR-003: Document Inconsistency
Symptoms:
- BDD scenario has no corresponding flowchart path
- Sequence diagram shows behavior not in BDD
- Validation issues flagged
Resolution Steps:
- Identify the discrepancy
- Return to source code as authoritative reference
- Determine which document is incorrect
- Update incorrect document
- Re-validate all checks
ERR-004: Incomplete Transaction Tracing
Symptoms:
- Feature ends prematurely in documentation
- Cross-cutting concerns not captured
- Entry points missing
Resolution Steps:
- Re-trace forward from feature completion
- Search for all callers of entry point
- Check for deferred operations (timers, async jobs)
- Follow navigation until idle state reached
- Update all three documents with discovered paths
References
External Documentation
Annotation Markers
| Marker | Usage |
|---|---|
[REFERENCE: ServiceName] | External dependency reference |
[MISSING LINK] | Unresolved external dependency |
[MISSING EVIDENCE: path] | Evidence file not found |
[DISCOVERY FAILED: reason] | Autonomous evidence discovery yielded no results |
[UNCLEAR LOGIC] | Ambiguous behavior in source |
[MISSING BEHAVIOR] | Incomplete implementation |
[VALIDATION ISSUE] | Temporary marker during validation |
[API: domain/path] | API endpoint specification marker |
[API INCOMPLETE: field] | Missing API documentation (request/response schema, headers, etc.) |
Exhaustive Business Feature Inventory for Complex Apps (Mobile, SPA, Stateful Web, Multi-Tier)
Goal
From the full codebase(s)—including frontends, backends, services, and databases—produce an exhaustive, structured list of all business features implemented. Only list and categorize features (no descriptions, rules, or UX details). Emphasize coverage and completeness.
What counts as a “feature”
A business feature is any user- or business-facing capability exposed via UI, API, background workflow, or data contract that delivers product value.
✅ Include
- User-visible capabilities (e.g., onboarding, auth/SSO, profile, search, content, messaging, notifications).
- Commercial flows (checkout, subscriptions, billing, invoices, coupons, trials, entitlements).
- Growth & re-engagement (referrals, invites, rewards, email/SMS/push campaigns, paywalls).
- Admin/agent/staff consoles and moderation tools.
- Data rights & compliance (export/delete account, consents, age-gating).
- Multi-tenancy, roles/permissions, regional/locale variants.
- Integrations that surface to users (payments, shipping, ID verification, maps, social, support chat).
- API-only or backend-only business workflows (e.g., order lifecycle, KYC, ticketing) even if not directly surfaced in UI.
🚫 Exclude
- Pure infra/library code without a direct business capability (e.g. ORM adapters, DI, logging, generic caching, etc.), unless it implements a named product capability (e.g., “In-App Purchases”, “Subscriptions”).
Inputs available
- Source code (frontend/mobile + backend/services), configs, environment templates, migrations, seeders, CI/CD files.
- Static assets/templates, i18n resources, email/SMS templates, push payloads.
- API definitions (OpenAPI/Swagger, GraphQL schemas), job/workflow definitions, queue/topic names.
- Tests (unit/integration/E2E), READMEs, architectural docs found in repos.
Assume static analysis only (no live systems).
Discovery strategy (be systematic & exhaustive)
A. Clients
-
Routing & navigation
- Views/screens, navigation structure (stacks/graphs/routes), deep/external linking handlers, home screen widgets/extensions, platform-specific integrations (wearables, automotive, TV).
-
State & capability markers
- Redux/MobX/Zustand/NgRx/Pinia, feature slices/modules.
- Feature flag clients (LaunchDarkly, Unleash, custom), A/B framework hooks.
- UI text (
i18n,strings, menus), component directories named for product surfaces.
-
Channels
- Push/in-app messaging renderers, notifications center, inbox, banners, tooltips, NPS/rating prompts.
-
Growth surfaces
- Referral screens, invite flows, paywalls/upsells, trials, “rate this app”, sharing.
B. Backends (PHP, Python, Node.js; monoliths & services)
-
Endpoints & resolvers
- REST (controllers/routes/middleware), GraphQL (queries/mutations), RPC/gRPC handlers.
- Auth providers (email/phone/OAuth/SSO/SAML), session & token flows; RBAC/ABAC policy files.
-
Workflows & jobs
- Queue/worker systems: Celery/RQ (Python), Bull/BullMQ/Agenda/bee-queue (Node), Laravel Queues (PHP); job names that encode business processes.
- Schedulers/CRON, orchestrations (Temporal, Airflow).
-
Integrations
- Payment gateways, tax/VAT, invoicing; IDV/KYC; shipping; maps/geocoding; communications (email/SMS/push); analytics/events.
-
Growth & compliance
- Promo/coupon services, referral services; GDPR/CCPA endpoints (export/delete), consent registries.
-
Multi-tenancy & regionalization
- Tenant resolution, per-tenant configs, regional toggles, entitlement checks.
C. Data layer (SQL/NoSQL/Graph)
-
Schemas & migrations
- Tables/collections/indices whose names imply features (e.g.,
subscriptions,orders,messages,rewards,consents,feature_flags,entitlements).
- Tables/collections/indices whose names imply features (e.g.,
-
Events & contracts
- Kafka/RabbitMQ/SNS/SQS topics; event types indicating business flows (e.g.,
OrderPaid,UserVerified,TrialStarted).
- Kafka/RabbitMQ/SNS/SQS topics; event types indicating business flows (e.g.,
-
Stored procedures / views
- Anything implementing business logic (e.g., statements assembling invoices, fraud signals).
-
Seed data
- Default roles, feature toggles, sample plans/tiers.
D. Cross-cutting signals
- Feature flags / remote config
- Experiment frameworks (experiment keys, cohorting).
- Access control (roles, permissions, scopes).
- Region/locale/product tier branching (Pro/Enterprise/Geo).
Deduplication & naming
- Merge duplicates across repos/services/clients; choose product-facing names (prefer UI text/menu labels over internal class names).
- If a capability is gated (flag/plan/region), keep it and tag with the gate(s).
Output format
JSON (authoritative)
[
{
"feature_name": "string",
"category": "Acquisition | Account | Discovery | Creation | Consumption | Commerce | Engagement | Support | Admin/Moderation | Platform Integration | Data & Compliance | Roles & Access | Localization & Accessibility | Other",
"surface": ["ClientUI", "API", "BackgroundJob", "Workflow", "AdminPanel", "Integration", "Notification", "DataContract"],
"platform": ["<client>", "<server>", "service:<name>", "db"],
"actors": ["Guest", "EndUser", "Admin", "Agent", "Moderator", "Merchant", "Tenant"],
"channels": ["Push", "Email", "SMS", "InApp", "Webhook", "Widget"],
"flags_or_variants": ["flag:<key>", "experiment:<key>", "plan:<tier>", "region:<code>", "tenant:<id>"],
"evidence": [
"repo/path/file:LineOrSymbol",
"route:POST /v1/orders",
"graphql:mutation createSubscription",
"migration:2024_10_01_add_subscriptions.sql",
"queue:orders.created",
"cron:invoice_generation"
]
}
]
Rules: no descriptions; 1–5 high-signal evidence entries per feature; unique feature_names.
Coverage checklist (must satisfy before finishing)
- Frontends: all routes/pages/screens/components mapped; deep links/app links/web routes included; state slices/modules scanned; i18n/menu labels covered.
- Backends: all REST/GraphQL endpoints and handlers scanned; background jobs/CRON/workflows enumerated; integrations (payments, IDV, comms, maps) captured.
- Auth/Access: signup/login/SSO/2FA flows; roles/permissions/scopes; multi-tenant resolution.
- Commerce: carts/checkout/payments/subscriptions/invoices/refunds/coupons/trials/entitlements.
- Engagement & Growth: notifications (push/email/SMS/in-app), referrals/invites/rewards, ratings/reviews prompts.
- Data & Compliance: data export/delete, consents, age gates, regional restrictions.
- Experiments & Flags: feature flags, remote config keys, experiment IDs; plan/tier/region gates.
- Databases & Events: business tables/collections, migrations, stored procedures/views, event topics and webhooks.
- Admin/Moderation: consoles, reports, case management, content moderation.
- Localization & Accessibility: locales, RTL, a11y toggles.
- Cross-platform parity: same feature appearing on mobile/web/backend tagged appropriately.
Constraints
- No feature descriptions or implementation details.
- Prefer product terminology extracted from UI text, route names, email/SMS templates.
- If uncertain but plausible, include with
"category": "Other"and tag"candidate": trueinflags_or_variants.
Deliverables
- JSON file (authoritative feature list).
- Final line:
Coverage checklist completed: YES/NO.
/manual-test - Manual test change in production
Purpose
This command allows you to manually test changes in production with a chrome browser by reading merged commit changes and testing the related features on production using Playwright MCP.
Usage
/manual-test [production_url] [commit_hash]
Or --no-verify to skip the manual test plan confirmation step:
/manual-test [production_url] [commit_hash] --no-verify
What This Command Does
- Reads and Analyzes the changes to identify the features that need to be tested based on the provided $commit_hash changes.
- Uses the
git diffcommand to get the changes made in the specified commit only. - Identifies the files and functionalities that have been modified or added.
- Constructs a list of features that need to be tested based on the commit changes.
- Constructs a manual test plan based on the identified features.
- You MUST output the test plan in a structured format for the user.
- If
--no-verifyis not specified you MUST ask for confirmation or modifications on the plan to proceed with the manual testing.
- Uses the
- Run the manual tests on the production URL provided:
- Open the specified $production_url and follows the test plan created in the first step.
- DO NOT write any code or scripts, this is a manual testing process.
- Accept cookies and privacy policies if needed.
- If in doubt or the application requires authentication (login), stop and ask the user for clarification on how to proceed with the testing otherwise DO NOT wait for user to interact with the browser.
- Outputs the results of the manual tests, including any issues, bugs, ux concerns found or confirmations of successful tests in a structured format.
- If any issues were found, provide detailed information about the issue, including steps to reproduce, expected vs actual behavior.
- If all tests pass, confirm that the features are functioning as expected.
- Close the browser after completing the tests.
- Clear
.playwright-mcpdirectory to ensure no test data is left behind.
Schema: This command follows
aitt/commands/cmd.md. Read schema before modifying.
Orchestrate
Implementation coordinator that fully implements a plan to production quality within the main context, with intelligent verification that adapts to project capabilities.
Purpose
Fully implement the plan at the provided path directly in the main context. With 1M token context, all planning and implementation happen in a single conversation. Final verification and code review are delegated to parallel subagents for thoroughness and speed.
Your role:
- Read and analyze the plan
- Decompose work into milestones and tasks
- Implement each task directly using Edit/Write/Bash tools
- Run milestone-level verification (tests, typecheck, lint) directly
- Launch parallel subagents for final verification and code review
- Validate that implementation meets all original requirements
Use when:
- Implementing a multi-phase feature from a detailed plan
- Coordinating implementation across multiple files/modules
Do not use when:
- Simple single-file changes or quick bug fixes
- Exploratory research tasks
Key Principles
Execution Model
Direct Implementation with Inline Verification: Each milestone is implemented and verified directly. Write code, generate migrations (if schema changes are involved), apply migrations, then run CLI checks (unit tests, typecheck, lint). After all milestones, parallel subagents handle comprehensive final verification (runtime, E2E, browser testing) and code review (security, clean code, architecture, performance, error handling, dead code).
Adaptive Verification (most to least efficient):
- Unit tests and automated test suites
- CLI/script execution (API endpoints, command-line tools)
- Browser-based testing via Chrome Devtools MCP
- Full E2E testing via Playwright/Selenium
Migration-First Execution: When a milestone involves database schema changes, migrations must be generated and applied before verification runs. Code that depends on new columns, tables, or relations cannot be tested against an outdated schema. When possible, break schema-dependent work into smaller increments: generate migration, apply, implement code, verify. This keeps the feedback loop tight.
Complete Execution — No Deferral: Every plan item MUST be fully implemented. If a task proves harder than expected, solve it — don't defer it. The final requirements validation treats any deferred or missing item as mandatory work.
Server Health Invariant: A broken dev server is a broken feedback loop. If the dev server crashes, fails to start, or becomes unresponsive at any point during implementation — whether from a code change, a new endpoint, a missing dependency, a schema mismatch, or any other cause — diagnose and fix the issue before any further implementation work proceeds. Continuing to write code against an untestable system is forbidden.
Code Standards
Simplicity: Prefer the smallest solution that meets the plan. No code duplication, no speculative abstractions. Reuse existing primitives; match existing code style, patterns, and conventions.
Discovery Before Creation: Before implementing new functionality, search the codebase for existing code to reuse or extend. Check shared packages, utilities, and helpers. If something already exists that covers the same concern, extend or wrap it — do not create a parallel version.
Code Hygiene: Before declaring completion, the codebase must be clean: no dead code, unused exports, debug logs, temp scripts, or leftover experimental code. The final state contains only what's necessary.
Inputs
Expects: Path to implementation plan markdown file Required: Yes
Usage
/orchestrate docs/plans/feature-name.md
Plan File Requirements
The plan file should contain:
- Requirements and acceptance criteria
- Architecture or file structure overview
- Implementation checklist or phases
- Verification/testing expectations
Prerequisites
Gate 1: Plan File Exists
Check: Provided path resolves to a readable markdown file
Pass: Proceed to Gate 2
Fail: Exit — Plan file not found: <path>. Verify the path and try again.
Gate 2: Plan Contains Actionable Content
Check: Plan has identifiable tasks, phases, or checklist items
Pass: Proceed to Process
Fail: Exit — Plan file lacks actionable structure. Expected: phases, checklist items, or task breakdown.
Process
Step 1: Analyze the Plan
Read the plan file and extract:
- Requirements — What must be built
- Acceptance criteria — How to verify success
- Dependencies — What must exist before implementation
- Risks — What could go wrong
- Work breakdown — Epics, tasks
Project Capability Detection
Detect available project capabilities for verification and cleanup:
| Capability | Detection Method | Used In |
|---|---|---|
| Unit tests | package.json scripts (test, jest, vitest, mocha) | Milestone & final verification |
| API endpoints | Route files, OpenAPI specs, server code | Milestone & final verification |
| CLI scripts | package.json scripts, scripts/ folder | Milestone & final verification |
| Playwright | playwright.config.*, @playwright/test dependency | Final verification |
| E2E Screenshots | e2e/fixtures/screenshots.ts or similar | Final verification |
| Chrome Devtools MCP | MCP server availability | Final verification |
| Dead code analyzer | package.json scripts/deps (knip, ts-prune, unimported) | Cleanup phase |
| DB migrations | package.json scripts (db:migrate, db:push, db:generate), Drizzle/Prisma/Knex config, migration directories | Milestone execution — run before verification |
Detection priority: package.json scripts, test config files, test directories, E2E screenshot fixtures, API route definitions, MCP server availability, dead code analyzer, migration config/scripts.
Unknowns Handling
If critical information is missing: make reasonable assumptions, document them, and proceed.
Output Schema
plan_analysis:
requirements: [list]
acceptance_criteria: [list]
dependencies: [list]
risks: [list]
work_breakdown:
- milestone: "Milestone Name"
tasks:
- name: "Task name"
files: [affected files]
depends_on: [task names]
has_schema_changes: true/false
verification_capabilities:
unit_tests: { available: bool, command: string, framework: string }
api_testing: { available: bool, endpoints: [list] }
e2e_testing: { available: bool, framework: string, command: string, screenshots: { available: bool, env_var: string } }
browser_testing: { available: bool, method: string }
dead_code_analyzer: { available: bool, tool: string, command: string }
db_migrations: { available: bool, tool: string, generate_command: string, migrate_command: string, backup_command: string }
Step 2: Design Execution Strategy
Using the analysis from Step 1, produce an execution plan:
- Ordered milestones — Sequential phases with clear boundaries
- Task ordering within milestones — Dependency-respecting sequence
- Definition of done — Per milestone: what must be implemented and what verification must pass
- Verification strategy — Based on detected capabilities (see below)
Verification Strategy
Per milestone:
- Implement code and generate migration files (if schema changes involved)
- Apply migrations before verification
- Run CLI checks (unit tests, typecheck, lint)
Once after all milestones: Full verification — all CLI tests, runtime startup check, E2E tests, browser testing via Chrome Devtools MCP (if feature has UI).
Skip UI verification for: Backend/API-only changes, config/data changes, library/utility code.
Step 3: Checkpoint — Ready to Execute
GATE: Do not proceed until satisfied.
- All milestones ordered with clear boundaries
- Tasks within each milestone ordered by dependencies
- Schema-change tasks identified with migration steps
- Verification checks specified per milestone
If not satisfied: Return to Step 2
Step 4: Execute Milestones
For each milestone in order, implement all tasks and verify results before moving on.
Per Milestone
- Discovery — Before implementing, search the codebase for existing code to reuse or extend. Check shared packages, utilities, helpers, type definitions, and constants.
- Implement tasks — Work through each task in dependency order:
- Read affected files to understand current state
- Write code using Edit/Write tools
- Generate migration files if schema changes are involved
- Apply migrations — If any task in this milestone generated migration files:
- Back up the database
- Run all pending migrations
- If migration fails, diagnose and fix the schema issue, then re-apply
- Run verification — Run CLI checks (unit tests, typecheck, lint) against the now-migrated database
- Verify server health — If the dev server should be running (or needs to run for verification), confirm it starts and stays running. If it crashes after the milestone's changes, diagnose and fix before advancing.
- If pass — Proceed to next milestone
- If fail — Fix issues and re-verify
Migration Timing
The default flow batches migrations per milestone. For milestones with multiple schema-dependent tasks, use a tighter loop:
Task A (schema change) → generate migration → apply migration → Task B (depends on A's schema) → generate migration → apply migration → verify all
Choose the granularity based on task dependencies:
- Batch per milestone — When tasks don't depend on each other's schema changes
- Incremental (per task) — When a later task depends on an earlier task's schema changes
Quality Gates (apply to all work)
Functionality:
- Features work per plan + acceptance criteria
- No partial implementations
Correctness & Safety:
- Input validation at system boundaries
- Error handling consistent with codebase
- No security vulnerabilities
Code Quality:
- No copy/paste duplication, unnecessary layers, or dead code
- No unused imports, variables, exports, or type definitions
- No commented-out code blocks
- Clear file responsibilities, small readable functions
Code Hygiene:
- No
console.log/console.debug/debugger(except intentional logging) - No TODO/FIXME from this implementation (existing ones OK)
- No temp scripts, experimental code paths, or stub implementations
Documentation:
- README.md updated if new commands/scripts/setup steps added
- CLAUDE.md updated if new patterns/conventions added
Step 5: Code Cleanup
After all milestones pass, perform quick cleanup before final verification. Thorough code quality analysis (dead code, duplication, architecture) is handled by dedicated subagents in Step 6.
- Remove debug artifacts —
console.log/debug/debuggerstatements, TODO/FIXME from this implementation - Remove temp artifacts — Temp files, scripts, one-time migration scripts
- Update documentation — README.md if new scripts/commands; CLAUDE.md if new patterns
Cleanup runs BEFORE final verification so any breakage from removal is caught.
Step 6: Final Verification
After cleanup, run comprehensive verification and code review using parallel subagents. Each subagent is responsible for its own domain — it finds issues, validates they are real (not false positives), fixes them, and reports what was changed.
Wave 1: CLI Gate (blocking)
Launch a single subagent. Wave 2 cannot start until this passes.
| Subagent | Responsibility |
|---|---|
| CLI Verifier | Run unit tests, typecheck, lint. Fix all failures. Re-run until green. |
Wave 2: Parallel Verification + Code Review
Launch all applicable subagents in parallel after Wave 1 passes. Each subagent receives the plan file path and the list of files changed during this implementation.
Verification subagents:
| Subagent | Responsibility |
|---|---|
| Runtime Verifier | Start dev server, verify no crashes within 30s, smoke test key pages/endpoints, check for 500s and module errors. Fix crashes and re-verify. |
| E2E Test Runner | Run Playwright tests, capture screenshots, review screenshots with AI for visual regressions. Fix failing tests. (Skip if no UI changes) |
| Browser Tester | Chrome MCP walkthrough — manually verify the feature works, test happy paths and edge cases, check console errors and network requests. Fix issues found. (Skip if no UI changes) |
Code review subagents:
| Subagent | Responsibility |
|---|---|
| Security Reviewer | Audit changed files for injection risks (SQL, XSS, command), auth/authz gaps, secrets in code, OWASP top 10 patterns. Validate each finding is a real risk (not a false positive). Fix confirmed vulnerabilities. |
| Clean Code Reviewer | Review changed files for code duplication, poor naming, oversized functions, readability issues, SRP violations. Validate findings make sense in context. Fix confirmed violations. |
| Architecture Reviewer | Review changed files for module boundary violations, incorrect dependency direction, tight coupling, inconsistent patterns, missed abstractions. Validate findings against project conventions. Fix confirmed violations. |
| Performance Reviewer | Review changed files for N+1 queries, missing indexes on new queries, unnecessary DB calls, bundle size impact from heavy imports, redundant computations. Validate findings are actual bottlenecks. Fix confirmed issues. |
| Error Handling Reviewer | Review changed files for unhandled promise rejections, missing try/catch at boundaries, silent error swallowing, missing React error boundaries, poor error messages. Validate findings are real gaps. Fix confirmed issues. |
| Dead Code Analyzer | Run dead code analysis tool (knip/ts-prune if available, otherwise grep-based search). Analyze results to distinguish genuinely dead code from dynamically used code. Remove confirmed dead exports, imports, functions, types. Preserve items used via dynamic imports or public API with justification. |
Subagent Instructions (shared across all Wave 2 subagents)
Each subagent must:
- Scope — Focus only on files changed during this implementation (provided in task spec) and their immediate callers/callees
- Find — Identify issues within their domain
- Validate — Judge whether each finding is real and worth fixing (not a false positive, not a style preference, not pre-existing)
- Fix — Apply fixes directly for all confirmed issues
- Report — Return a structured report of findings and changes made
Report format per subagent:
## [Reviewer Name] Report
### Findings & Fixes
- [Finding]: [why it's real] → Fixed in `path/file.ts:line`
### No Issues (if applicable)
All checked, no issues found.
### Skipped (if applicable)
[What was skipped and why — e.g., pre-existing issues outside scope]
Wave 2 Completion
After all Wave 2 subagents complete:
- Collect reports — Read all subagent reports
- Re-run CLI gate — Code review fixes may have introduced regressions. Run unit tests, typecheck, lint again. Fix if needed.
- Resolve conflicts — If multiple reviewers changed the same file, verify changes are compatible
- Confirm server health — Verify dev server still starts and runs after all fixes
Step 7: Requirements Validation
Read the plan file and extract every requirement and acceptance criterion. For each one, determine whether it is fully satisfied by searching the codebase for implementation evidence.
Produce a traceability report:
## Requirements Traceability
- Requirement 1: implemented in `path/file.ts:line`, verified by [method]
- Requirement 2: implemented in `path/file.ts:line`, verified by [method]
## Acceptance Criteria
- Criterion 1: [evidence]
## Gaps Found
[Any requirements not fully satisfied]
## Verdict
ALL SATISFIED | GAPS FOUND (list count)
If all requirements satisfied — Proceed to Step 8. If gaps found — Implement missing requirements, re-run verification (Steps 4-6), then re-validate until all requirements are met.
Step 8: Completion
When all acceptance criteria are met, requirements validation passes, and code is clean:
- Produce final report (see Outputs)
- Produce release checklist for merge/deploy
Outputs
Final Report
The final report is a structured markdown document for a tech lead / architect audience. Every section is mandatory. Use bullet points — no prose paragraphs. Be specific with counts, file paths, and results. The report must answer: what was built, does it work, were there surprises, is it safe to merge.
# Implementation Report: [Feature Name]
## Overview
- **Verdict:** ready to merge / blocked / issues remaining
- **Scope:** [modules/packages affected]
- **New dependencies:** [list, or none]
- **Migrations:** [list migration files applied, or none]
## What Was Built
- [Capability 1: what users can now do]
- [Capability 2: what users can now do]
- [...]
### Key Decisions
- [Decision and rationale]
- [Trade-off chosen and why]
### Files Changed
- `path/file.ts` — [what changed]
- `path/other.ts` — [what changed]
- [...]
## Verification
### CLI
- **Unit tests:** pass/fail — [X tests, Y suites]
- **Typecheck:** pass/fail
- **Lint:** pass/fail
### Runtime
- **Server startup:** [starts on port X, no crashes / failed — reason]
- **Smoke tests:** [endpoints/pages tested with status codes]
- **Console errors:** [none / list]
### E2E Tests
- **Status:** pass / skipped ([reason])
- **Tests run:** [test files and scenarios]
- **Screenshots:** [reviewed, visual issues found / clean]
### Browser Testing (Chrome MCP)
- **Status:** pass / skipped ([reason])
- **Scenarios tested:** [list each with result]
- **Console errors:** [none / list]
- **Network issues:** [none / list failed requests]
## Code Review
### Security — [X findings, X fixed]
- [Finding: what, where, severity] → Fixed in `path/file.ts:line`
- [Or: Clean — no issues]
### Clean Code — [X findings, X fixed]
- [Finding: what, where] → Fixed: [how]
- [Or: Clean — no issues]
### Architecture — [X findings, X fixed]
- [Finding: what, where] → Fixed: [how]
- [Or: Clean — no issues]
### Performance — [X findings, X fixed]
- [Finding: what, where] → Fixed: [how]
- [Or: Clean — no issues]
### Error Handling — [X findings, X fixed]
- [Finding: what, where] → Fixed: [how]
- [Or: Clean — no issues]
### Dead Code — [X items removed]
- [What was removed, from where]
- [Or: Clean — nothing found]
### Post-Review Regression Check
- **CLI re-run:** pass/fail
## Risks & Limitations
- [Edge cases not covered]
- [Assumptions made during implementation]
- [Areas deserving extra scrutiny]
- [Or: None identified]
## Release Checklist
- [ ] Requirements satisfied (X/X)
- [ ] Tests passing
- [ ] Server runs
- [ ] Code review clean
- [ ] Documentation updated
- [ ] Ready for merge
Examples
Basic Usage
/orchestrate docs/plans/feature-name.md
Example Execution Flow
1. Analyze plan: docs/plans/feature-name.md
→ 3 phases, 12 tasks
→ Capabilities: vitest, playwright, Chrome MCP, knip
2. Execution strategy:
→ Per milestone: implement → migrate → verify (CLI)
→ Final: CLI + runtime + E2E + Chrome MCP
3. Execute milestones:
Phase 1: Foundation
→ Schema + migration generated
→ DB backed up, migration applied ✓
→ Types + repository implemented
→ Verification pass ✓
Phase 2: Core logic
→ New column migration generated → applied ✓
→ Service + API implemented
→ 1 test failure → fixed → pass ✓
Phase 3: Integration (no schema changes)
→ UI wired to API → pass ✓
4. Code cleanup:
→ knip: removed unused helper, 5 imports
→ Removed 4 console.logs, 1 temp script
→ Updated README.md
5. Final verification:
Wave 1 (CLI gate):
→ Unit tests, typecheck, lint: all pass ✓
Wave 2 (parallel):
→ Runtime: server starts on :3010, smoke tests pass ✓
→ E2E: Playwright pass, screenshots reviewed ✓
→ Browser: Chrome MCP walkthrough pass ✓
→ Security: 1 finding (unescaped input) → fixed ✓
→ Clean Code: 2 findings (naming, duplication) → fixed ✓
→ Architecture: no issues ✓
→ Performance: 1 finding (N+1 query) → fixed ✓
→ Error Handling: 1 finding (missing try/catch) → fixed ✓
→ Dead Code: removed 3 unused exports ✓
Post-review CLI re-check: all pass ✓
6. Requirements validation: 3/3 satisfied
✓ IMPLEMENTATION COMPLETE — ready for review
Error Handling
ERR-001: Plan File Not Found
Cause: Invalid path or file doesn't exist
Resolution: Verify path, check for typos, ensure .md extension
ERR-002: Verification Loop Stuck
Cause: Unclear requirements or conflicting constraints Resolution:
- Document the specific failure
- Assess if the requirement is achievable
- Adjust approach or flag for manual review
ERR-003: Cleanup Breaks Tests
Cause: Removed code that was actually used Resolution:
- Identify which removal caused the failure from git diff
- Restore the removed code
- Document why it appeared dead but wasn't
- Re-run cleanup with updated understanding
If uncertain about removal (public API, dynamic imports, reflection): preserve with justification and flag for human review.
ERR-004: Dev Server Crash or Failure to Start
Cause: Code changes introduced a runtime error, missing import, broken route, schema mismatch, or dependency issue that prevents the dev server from running.
Resolution:
- Stop all implementation work — do not write more code against a broken system
- Read the server's error output (crash logs, stack trace, startup errors)
- Identify the specific change that caused the failure
- Diagnose root cause, apply fix, and confirm the server starts and stays running
- Only after server health is confirmed, resume implementation work
- If the fix requires reverting changes, revert and re-implement with a corrected approach
Completion Rules
"Partially complete" is NOT a valid final state. If any requirements remain unmet, loop back to implement them. Only use the blocked status for genuine external dependencies outside the orchestrator's control:
⚠ ORCHESTRATE BLOCKED (external dependency)
Completed: [what succeeded]
Blocked By: [specific external blocker]
Requirements Fully Implemented: X/Y
Blocked Requirements: [what and why]
References
Related Commands
/commit- Create git commit after implementation/plan- Create implementation plan to feed into orchestrate
Schema: This command follows
aitt/commands/cmd.md. Read schema before modifying.
Plan
Creates structured implementation plans by exploring the codebase, analyzing architecture, evaluating trade-offs, and producing an actionable plan document ready for
/orchestrate.
Purpose
Produce a thorough, opinionated implementation plan for a feature, refactor, or change. The plan is the bridge between an idea and /orchestrate execution — it captures the "what," "why," and "how" so the orchestrator can focus purely on delegation.
Use when:
- Implementing a new feature that touches multiple files or modules
- Refactoring existing systems where multiple valid approaches exist
- Making architectural decisions that affect the codebase long-term
- The scope or approach is unclear and needs exploration first
Do not use when:
- Single-file bug fixes with obvious solutions
- Trivial changes (typos, config tweaks, adding a log line)
- Pure research or exploration tasks (use the Explore agent directly)
Key Principles
Exploration Before Opinion: Read the code before forming conclusions. Every architectural recommendation must be grounded in what actually exists, not assumptions about what should exist.
Anti-Pattern to Avoid:
- Wrong: Proposing a Redux store without checking if the project already uses Zustand
- Correct: Explore state management patterns in the codebase, then recommend an approach consistent with existing conventions
Plan the Seams, Not the Code: The plan defines the connection points between work scopes — not the code inside them. Include everything needed to implement correctly, nothing more. Each phase declares the interfaces, types, contracts, and data shapes it exposes to the next phase. Be concrete — type signatures, method signatures, API shapes, and data schemas, not prose descriptions.
Do not include: function bodies, SQL queries, component JSX, step-by-step implementation logic, exact variable names, line-by-line code changes, or pixel-perfect UI specs. Describe what each component/module should do, which patterns to follow, what interfaces it exposes, and what the acceptance criteria are — let the implementer handle the internals.
Anti-Pattern to Avoid:
- Wrong: Writing out function bodies, full component implementations, or specifying exact variable names and line-by-line changes
- Correct: Define the type signatures, API contracts, data schemas, and module boundaries. The implementer writes the code; the plan defines where the pieces snap together.
Example: If Phase 1 creates a repository and Phase 2 builds a service that uses it, the plan should specify the repository's public interface (method signatures, return types, error contract) — not the SQL queries inside it. Phase 2's implementer then knows exactly what they can call without reading Phase 1's internals.
Orchestrate-Ready Output:
Plans must contain what /orchestrate needs: requirements, acceptance criteria, architecture overview, implementation phases with interface contracts, and verification expectations. If the plan can't be handed directly to /orchestrate, it's incomplete.
Consistency Over Novelty: When the codebase has established patterns, follow them. Introducing a new pattern requires justification beyond "it's better" — it must be demonstrably necessary.
Inputs
Expects: Description of the feature, task, or change to plan Required: Yes
Usage
/plan add user authentication with JWT
/plan migrate the scheduling system from cron to a queue-based approach
/plan refactor the media library to support S3 storage
The input should describe the goal clearly enough to guide exploration. Additional context (constraints, preferences, related issues) is welcome.
Prerequisites
Gate 1: Input Contains Actionable Goal
Check: The input describes a concrete feature, change, or task (not a vague wish) Pass: Proceed to Process Fail: Ask the user to clarify what they want to build or change
Fail Output:
I need a clearer picture of what to plan. Could you describe:
- What feature or change you want to implement?
- What problem it solves or what capability it adds?
Process
Step 1: Understand the Goal
Parse the input to extract:
- What — The feature, change, or refactor being requested
- Why — The motivation or problem being solved (ask if not obvious)
- Scope boundaries — What's in scope vs. explicitly out of scope
If the goal is ambiguous, ask one focused clarifying question before proceeding. Do not stall — make reasonable assumptions and document them.
Step 2: Explore the Codebase
Thoroughly investigate the relevant parts of the codebase. This is the most important step — skipping it leads to plans that fight the existing architecture.
2.1 Map the Relevant Architecture
- Identify which packages, modules, and files are involved
- Trace data flow through the affected area (API routes → services → repositories → data layer)
- Understand existing patterns: naming conventions, file organization, error handling, testing approach
2.2 Identify Existing Conventions
| Aspect | What to Look For |
|---|---|
| File structure | How are similar features organized? (co-located tests, barrel exports, etc.) |
| Naming | Variable/function naming patterns, file naming conventions |
| Error handling | Thrown errors vs. returned errors, error types used |
| Testing | Unit vs. integration split, mocking strategy, test data patterns |
| State management | How is state handled in similar features? |
| API patterns | Route structure, validation, response formats |
| Type patterns | Interface vs. type, branded types, generic patterns |
2.3 Identify Dependencies and Constraints
- What must exist before this can be built? (prerequisite features, migrations, config)
- What existing behavior must not break? (regression risks)
- Are there performance constraints? (data volume, response time expectations)
- Are there security considerations? (auth, input validation, data exposure)
Search Patterns
Use these to efficiently explore:
# Find similar features for pattern reference
glob: src/**/*{feature-keyword}*
grep: "class.*Repository" or "function.*Service" in relevant packages
# Understand the module boundary
grep: "export" in the module's index.ts
grep: "import.*from.*{module}" across the codebase
# Find test patterns
glob: **/*.test.{ts,tsx} near the affected area
Step 3: Evaluate Approaches
When multiple implementation paths exist, evaluate each against these criteria:
| Criterion | Question |
|---|---|
| Consistency | Does this match existing patterns in the codebase? |
| Simplicity | Is this the smallest change that solves the problem? |
| Maintainability | Will this be easy to understand and modify later? |
| Testability | Can this be tested without complex setup? |
| Performance | Does this meet the performance requirements? |
| Security | Does this follow security best practices? |
| Migration risk | How risky is the transition? Can it be done incrementally? |
Decision Format
For each significant decision, document:
### Decision: [Topic]
**Options considered:**
1. **[Option A]** — [Brief description]
- Pro: [advantage]
- Con: [disadvantage]
2. **[Option B]** — [Brief description]
- Pro: [advantage]
- Con: [disadvantage]
**Chosen:** Option [X]
**Rationale:** [Why this option wins given the codebase context]
If the decision is genuinely ambiguous and user preference matters, ask using AskUserQuestion. Otherwise, make the call and document the reasoning.
Step 4: Checkpoint — Exploration Complete
GATE: Do not proceed to plan composition until satisfied.
- Relevant codebase areas explored (not assumed)
- Existing patterns and conventions identified
- Dependencies and constraints documented
- Key architectural decisions made (or questions asked)
- Module boundaries and interface patterns understood (how existing modules expose their contracts)
- No critical unknowns remaining
If not satisfied: Return to Step 2 or Step 3
Step 5: Compose the Plan Document
Write the plan as a Markdown file in docs/plans/${PROJECT_NAME}/. Use descriptive kebab-case filenames (e.g., add-jwt-authentication.md, migrate-scheduler-to-queue.md).
Number the main sections sequentially (1, 2, 3...). Include only sections relevant to the plan — required sections are always present, optional sections appear when applicable.
Plan Document Structure
# [Feature Name]: Implementation Plan
## Overview (required)
[1-3 paragraphs explaining what this plan achieves, why it's needed,
and the high-level approach. This should be understandable by someone
who hasn't read the rest of the document.]
## [N]. Technology & Architecture Decisions (include when relevant)
[Document each significant decision using the format from Step 3.
Include: chosen approach, alternatives considered, rationale.]
## [N]. Design (include when relevant)
[The visual and interaction design for user-facing changes.
Include: screen layouts as ASCII wireframes, component inventory
with placement and purpose, interaction patterns (click flows,
form behavior, modals, transitions), UI states (empty, loading,
error, success), and responsive behavior across breakpoints.
For technical design (schemas, APIs, data flow, type definitions),
use the Architecture Decisions or Implementation Phases sections.]
## [N]. Configuration & Environment (include when relevant)
[Environment variables, config file changes, or infrastructure
requirements needed for the feature.]
## [N]. Files to Modify (required)
### New Files
| File | Purpose |
|------|---------|
| `path/to/new-file.ts` | [What it does] |
### Modified Files
| File | Changes |
|------|---------|
| `path/to/existing-file.ts` | [What changes and why] |
### Deleted Files
| File | Reason |
|------|--------|
| `path/to/obsolete-file.ts` | [Why it's no longer needed] |
### No Changes Required
[List areas that might seem affected but actually aren't, with reasoning]
## [N]. Implementation Phases (required)
[Break the work into sequential phases. Each phase should be
independently verifiable — after completing it, you can confirm
it works before moving to the next.
Each phase MUST define its interface contract: what it exposes
to subsequent phases. This is the critical connective tissue
that allows milestones to snap together without guesswork.]
### Phase 1: [Name] (foundation)
- [Task 1]
- [Task 2]
**Exposes to next phase:**
[The interfaces, types, API contracts, or data shapes this phase
creates that subsequent phases depend on. Be specific — method
signatures, type definitions, endpoint shapes, database schemas.]
```typescript
// Example: what Phase 2 can rely on
interface UserRepository {
findById(id: string): Promise<User | null>;
create(data: CreateUserInput): Promise<User>;
}
Verify: [How to confirm this phase works]
Phase 2: [Name]
Receives from Phase 1: [Reference the interfaces/contracts defined in Phase 1 that this phase consumes]
- [Task 1]
- [Task 2]
Exposes to next phase: [Interfaces this phase adds or extends for Phase 3]
Verify: [How to confirm this phase works]
[Continue for all phases. The final phase has no "Exposes" section — it completes the feature.]
[N]. Testing Strategy (include when relevant)
[What tests need to be written or updated. Unit, integration, E2E coverage expectations. Test data requirements.]
[N]. Risks and Mitigations (include when relevant)
| Risk | Impact | Mitigation |
|---|---|---|
| [What could go wrong] | [Consequence] | [How to prevent or recover] |
[N]. Migration & Rollback Strategy (include when relevant)
[Data migration steps, rollback procedures, incremental rollout strategy if applicable.]
Summary (required)
[Concise recap: what this plan delivers, the key architectural choices, and why this approach was selected over alternatives. This is what someone reads to understand the full concept without reading implementation details.]
Implementation Tracking Checklist (required)
[Checkbox list of every task across all phases. This is what /orchestrate uses to track progress.]
Phase 1: [Name]
- Task 1
- Task 2
Phase 2: [Name]
- Task 1
- Task 2
---
### Step 6: Checkpoint — Plan Quality
> **GATE:** Do not present the plan until all validation checks pass.
Run every check in the **Validation** section below. If any check fails, follow its fix procedure, then re-check.
**If not satisfied:** Return to Step 5 and improve.
---
### Step 7: Parallel Review Subagents
Launch two review subagents in parallel to validate the plan from different perspectives. Both must complete before proceeding.
#### 7.1 Architectural Review Agent
Use Task tool with `subagent_type: Plan` to review the plan document for architectural quality.
**Review Criteria:**
- **No cheap shortcuts:** Solutions address root causes, not symptoms; no workarounds or temporary fixes disguised as permanent solutions
- **Clean responsibilities:** Each module/component has a single, well-defined purpose; no god objects or kitchen-sink modules
- **No duplications:** No redundant code paths, duplicate data structures, or repeated logic across phases
- **Architectural best practices:** Follows SOLID principles, maintains loose coupling, respects existing codebase patterns
- **No over-engineering:** Solutions match the problem complexity; no premature abstractions, unnecessary indirection, or speculative generality
**Prompt template:**
Review the implementation plan at docs/plans/${PROJECT_NAME}/.md for architectural quality.
Evaluate against these criteria:
- No cheap shortcuts - Are solutions addressing root causes or just patching symptoms?
- Clean responsibilities - Does each component have a single, well-defined purpose?
- No duplications - Is there any redundant logic, duplicate data structures, or repeated code paths?
- Best practices - Does it follow SOLID, maintain loose coupling, respect existing patterns?
- No over-engineering - Is the solution complexity appropriate to the problem? No premature abstractions?
If issues found, list each with:
- What: The specific issue
- Where: Which section/phase
- Fix: How to address it
If the plan passes all criteria, confirm: "Architectural review: PASSED"
#### 7.2 Coverage Review Agent
Use Task tool with `subagent_type: Plan` to verify the plan covers all necessary aspects.
**Review Criteria:**
- **Complete feature coverage:** All aspects of the requested feature are addressed
- **Edge cases identified:** Error states, boundary conditions, and exceptional flows considered
- **Integration points covered:** All touchpoints with existing systems are addressed
- **Testing coverage:** Test strategy covers the feature adequately
- **Migration/rollback:** Data migration and rollback scenarios addressed (if applicable)
- **Security considerations:** Auth, validation, data exposure risks addressed (if applicable)
- **No orphaned dependencies:** All prerequisites and downstream effects are accounted for
**Prompt template:**
Review the implementation plan at docs/plans/${PROJECT_NAME}/.md for completeness.
Check for missing aspects:
- Feature coverage - Are all aspects of the requested feature addressed?
- Edge cases - Are error states, boundary conditions, and exceptional flows covered?
- Integration points - Are all touchpoints with existing systems addressed?
- Testing coverage - Does the test strategy adequately cover the feature?
- Migration/rollback - Are data migration and rollback scenarios addressed (if needed)?
- Security - Are auth, validation, and data exposure risks addressed (if needed)?
- Dependencies - Are all prerequisites and downstream effects accounted for?
If gaps found, list each with:
- What: The missing aspect
- Impact: Why it matters
- Suggestion: How to address it
If the plan is complete, confirm: "Coverage review: PASSED"
#### Handling Review Results
**If both agents return PASSED:** Proceed to Step 8
**If either agent identifies issues:**
1. Read the agent feedback
2. Return to Step 5 to address the identified issues
3. Re-run Step 6 checkpoint
4. Re-run Step 7 reviews
5. Repeat until both reviews pass
---
### Step 8: Present Summary and Request Approval
After writing the plan file, present a structured summary to the user. The summary has three mandatory sections and two conditional sections that together convey the full concept without requiring the user to open the plan file.
#### 8.1 Business Strategy
Explain the business-level behavior this plan delivers. Not long prose — concise, structured points that answer:
- **What changes for the user?** — Observable behavior from the end-user perspective
- **What business rules are introduced or modified?** — Decision logic, constraints, triggers
- **What workflows change?** — Step-by-step user journeys affected, new flows added
- **What data relationships are created?** — How entities connect, what depends on what
Use bullet points or a short table. Each point should describe a concrete behavior, not an abstract goal.
#### 8.2 User Journey (conditional — include when the plan introduces or changes user-facing workflows)
Map the step-by-step experience from the user's perspective. Show what the user does, what the system responds with, and decision points along the way.
Use a numbered flow format:
- User does [action]
- System responds with [result]
- User chooses [option A] or [option B] → A: [what happens] → B: [what happens]
- ...
Include:
- **Happy path** — The primary flow from start to completion
- **Key branches** — Where the user can take different paths and what each leads to
- **Error/edge states** — What happens when things go wrong (validation failures, permission denied, network errors)
Keep it concise — this is a journey map, not a spec. One flow per major user interaction. If the plan has multiple distinct user journeys, show each separately with a label.
#### 8.3 Design Plan (conditional — include when the plan involves UI changes, new screens, or visual/interaction design)
Present the visual and interaction design using ASCII mockups, layout descriptions, or structured component breakdowns. This section answers "what does the user see and interact with?"
Include:
- **Screen layouts** — ASCII wireframes or structured descriptions of new/changed screens, showing component placement, visual hierarchy, and responsive breakpoints
- **Component inventory** — New UI components needed, their purpose, and where they appear
- **Interaction patterns** — How users interact with the UI (click flows, form behavior, drag-and-drop, modals, transitions)
- **States and variations** — Empty states, loading states, error states, success states, and how the UI adapts to different data conditions
- **Responsive behavior** — How layouts adapt across breakpoints (mobile, tablet, desktop) if applicable
Use ASCII art for wireframes when spatial layout matters:
┌─────────────────────────────────┐ │ Header / Navigation │ ├──────────┬──────────────────────┤ │ Sidebar │ Main Content Area │ │ │ ┌──────────────────┐ │ │ │ │ Component A │ │ │ │ └──────────────────┘ │ │ │ ┌──────────────────┐ │ │ │ │ Component B │ │ │ │ └──────────────────┘ │ └──────────┴──────────────────────┘
Use structured lists when describing component behavior or states:
[Screen/Component Name]:
- Layout: [description]
- Components: [list]
- States: default | loading | empty | error
- Actions: [what user can do]
Keep it design-focused — describe what users see and how they interact, not the implementation details behind it.
#### 8.4 Data Flow (conditional — include when the plan involves data moving through multiple system layers)
Visualize how data moves through the system using an arrow-chain format:
[Entry point] → [Processing step] → [Storage] → [Output]
Include:
- **Input sources** — Where data enters (UI form, API call, cron trigger, webhook, etc.)
- **Transformations** — What processing happens at each step (validation, enrichment, computation)
- **Storage touchpoints** — Where data is persisted or read (database tables, cache, external APIs)
- **Output destinations** — Where data ends up (UI render, API response, notification, external service)
For plans with multiple data paths (e.g., write flow vs. read flow), show each separately. Label each flow.
#### 8.5 Architectural Plan
Describe the technical approach at system level:
- **Pattern/approach chosen** — What architectural pattern drives the implementation and why
- **Key decisions** — Technology choices, trade-offs made, alternatives rejected (with rationale)
- **Integration points** — What existing systems this connects to and how
- **Phase overview** — Number of phases, what each phase delivers, dependency chain between them
#### 8.6 Affected File Structure
Present the file impact as a structured tree or table:
- **New files** — Path and one-line purpose
- **Modified files** — Path and what changes
- **Deleted files** — Path and why (if any)
Group by package/module for readability.
#### 8.7 Close
State where the full plan lives (`docs/plans/${PROJECT_NAME}/<name>.md`) and ask the user if they'd like to:
- Approve and proceed to implementation (via `/orchestrate`)
- Request modifications to the plan
- Discuss specific decisions further
## Outputs
### Files Generated
docs/plans/${PROJECT_NAME}/.md # The implementation plan
### Plan Document Properties
- Written in Markdown
- Saved to `docs/plans/${PROJECT_NAME}/` with descriptive kebab-case filename
- Self-contained — readable without additional context
- Structured for consumption by `/orchestrate`
- Contains implementation tracking checklist with unchecked boxes
## Examples
### Basic Usage
/plan add dark mode toggle to the admin app
### Complex Feature
/plan migrate the post scheduling system from single-timezone to multi-timezone support with per-user timezone preferences
### Refactoring
/plan refactor the media library repository to support pluggable storage backends (local filesystem and S3)
### Example Summary Output
https://github.com/mksglu/claude-context-mode?tab=readme-ov-file
Plan: JWT Authentication
Business Strategy
- User behavior: Users log in with email/password, receive a persistent session. Authenticated users access admin routes; unauthenticated users are redirected to login
- Session lifecycle: Sessions expire after 7 days of inactivity; refresh tokens extend active sessions transparently
- Authorization model: Role-based —
adminandviewerroles. Admins manage content, viewers read-only. Role assigned at user creation - Security rules: Max 5 failed login attempts per 15 minutes per IP. Passwords require 8+ chars with mixed case + number. Tokens invalidated on password change
- Account recovery: Password reset via email link (24h expiry, single-use token)
User Journey
Login flow:
- User navigates to any admin page
- System detects no valid session → redirects to
/login - User enters email + password, clicks "Log in"
- System validates credentials
→ Success: Sets httpOnly cookie, redirects to original destination (or
/dashboard) → Invalid credentials: Shows inline error "Invalid email or password", stays on login page → Rate limited: Shows "Too many attempts. Try again in X minutes" - User is now authenticated — all admin routes accessible
Session expiry:
- User's token expires after 7 days of inactivity
- Next request → system returns 401
- Client-side middleware catches 401 → redirects to
/loginwith return URL preserved - User re-authenticates → returns to where they left off
Password reset:
- User clicks "Forgot password?" on login page
- User enters email → system sends reset link (regardless of whether email exists — no user enumeration)
- User clicks link → lands on reset form (or "Link expired" if >24h)
- User sets new password → all existing sessions invalidated → redirected to login
Design Plan
Login page (/login):
┌─────────────────────────────────────┐
│ [Logo / Brand] │
│ │
│ ┌───────────────────────────────┐ │
│ │ Email │ │
│ └───────────────────────────────┘ │
│ ┌───────────────────────────────┐ │
│ │ Password [👁] │ │
│ └───────────────────────────────┘ │
│ [ Forgot password? ] │
│ │
│ ┌───────────────────────────────┐ │
│ │ Log in │ │
│ └───────────────────────────────┘ │
│ │
│ [!] Error message area (hidden) │
└─────────────────────────────────────┘
- Layout: Centered card on muted background, max-width 400px, vertically centered
- Components: TextInput (email), PasswordInput (with visibility toggle), Button (primary), inline Alert
- States:
- Default: Empty form, button enabled
- Loading: Button shows spinner, inputs disabled
- Error: Inline alert below form with error message, inputs re-enabled
- Rate limited: Alert with countdown timer, submit disabled
Password reset page (/reset-password):
- Same centered card layout as login
- Single email input + submit button (request flow)
- New password + confirm password inputs (reset flow)
- Success state: confirmation message with link back to login
Data Flow
Authentication:
Login form → POST /api/auth/login → rate limiter check → bcrypt verify against users table → JWT minted (userId + role in payload) → httpOnly cookie set → 200 response
Request authorization:
Incoming request → Fastify onRequest hook → extract JWT from cookie → verify signature + expiry → decode payload → attach request.user → route handler executes (or 401 if invalid)
Token refresh: Client request with near-expiry token → auth middleware detects <1h remaining → mints fresh token → sets updated cookie → original request proceeds
Architectural Plan
- Pattern: Fastify plugin-based auth middleware (consistent with existing plugin patterns in the codebase)
- Key decisions:
- JWT in httpOnly cookies over localStorage → XSS protection
- bcrypt for password hashing → already a project dependency
- PostgreSQL users table in social database → reuses existing Drizzle setup
- Fastify
onRequesthook for route protection → non-invasive, per-route opt-in
- Integration: Connects to existing Drizzle ORM layer and Fastify server. No new external dependencies
- Phases: 5 phases — (1) DB schema & migration → (2) Auth service & JWT utils → (3) Fastify middleware plugin → (4) Login/logout UI → (5) Protected route migration
Affected File Structure
packages/social/
| Action | File | Purpose |
|---|---|---|
| New | src/db/schema/users.ts | User table schema with roles |
| New | src/auth/auth-service.ts | Login, logout, token refresh logic |
| New | src/auth/jwt-utils.ts | Token mint/verify helpers |
| Modified | src/db/schema.ts | Export new users table |
| Modified | src/index.ts | Wire auth service singleton |
web/oxyness-admin/
| Action | File | Purpose |
|---|---|---|
| New | server/plugins/auth.ts | Fastify auth plugin |
| New | pages/login/+Page.tsx | Login page UI |
| Modified | server/index.ts | Register auth plugin |
| Modified | pages/+config.ts | Add route guard config |
Full plan: docs/plans/oxyness-admin/add-jwt-authentication.md
Shall I proceed with /orchestrate, or would you like to adjust anything?
## Validation
Step 6 references this section as the authoritative quality gate. Run all checks in order.
### Check 1: Plan File Exists
**Method:** Verify `docs/plans/${PROJECT_NAME}/<name>.md` was written successfully
**On success:** Proceed to next check
**On failure:** Write the file and re-validate
### Check 2: Required Sections Present
**Method:** Verify the plan contains all required sections: Overview, Files to Modify, Implementation Phases, Summary, Implementation Tracking Checklist
**On success:** Proceed to next check
**On failure:** Add missing sections and re-validate
### Check 3: Interface Contracts Defined
**Method:** Verify every phase (except the final one) has an "Exposes to next phase" section with concrete type signatures, method signatures, or API shapes. Verify every phase (except the first) has a "Receives from" reference to what it depends on. Connection points must be concrete code-level definitions, not prose descriptions.
**On success:** Proceed to next check
**On failure:**
1. Identify phases missing interface contracts
2. Add concrete contracts — types, function signatures, endpoint shapes
3. Ensure the receiving phase references what it depends on
4. Re-validate
### Check 4: No Implementation Code
**Method:** Verify the plan does not contain function internals, SQL query bodies, component JSX, or implementation logic. Interface definitions (type signatures, method signatures, schemas) are expected; code that goes inside functions is not.
**On success:** Proceed to next check
**On failure:**
1. Identify code body content
2. Replace with interface definitions or remove
3. Re-validate
### Check 5: Checklist Completeness
**Method:** Verify the Implementation Tracking Checklist contains a checkbox for every task mentioned in every phase
**On success:** Proceed to next check
**On failure:** Add missing checklist items and re-validate
### Check 6: Orchestrate Compatibility
**Method:** Verify the plan contains requirements, acceptance criteria (in phases), architecture overview, interface contracts between phases, and verification expectations. The plan must be self-contained — handable to `/orchestrate` without additional context.
**On success:** Proceed to next check
**On failure:** Enhance the plan with missing orchestrate-required content
### Check 7: No Time Estimates
**Method:** Search for time-related language (hours, days, weeks, minutes, "quick", "should be fast")
**On success:** Complete validation
**On failure:** Remove all time estimates and re-validate
## Error Handling
### ERR-001: Insufficient Codebase Context
**Symptoms:** Plan makes recommendations that conflict with existing patterns
**Cause:** Exploration step was too shallow
**Resolution:**
1. Return to Step 2
2. Expand exploration scope
3. Re-evaluate decisions against actual codebase patterns
4. Revise plan accordingly
---
### ERR-002: Ambiguous Requirements
**Symptoms:** Plan contains multiple "if X then Y, if Z then W" branches
**Cause:** Requirements weren't clarified before planning
**Resolution:**
1. Identify the specific ambiguity
2. Ask one focused question via AskUserQuestion
3. Update the plan with the clarified direction
4. Remove conditional branches
---
### ERR-003: Plan Too Vague for Orchestrate
**Symptoms:** Plan reads like a wishlist, not an implementation guide
**Cause:** Missing concrete details (files, phases, acceptance criteria)
**Resolution:**
1. Add specific file paths for every change
2. Break phases into concrete tasks
3. Add verification criteria for each phase
4. Ensure the implementation tracking checklist covers every task
---
### ERR-004: Scope Creep
**Symptoms:** Plan keeps growing, includes tangential improvements
**Cause:** Not establishing clear scope boundaries early
**Resolution:**
1. Re-read the original input
2. Remove anything not directly required by the stated goal
3. Move "nice to have" items to a "Future Considerations" section (not tracked in checklist)
4. Confirm scope with user if uncertain
## Summary
After creating the plan, present the structured summary defined in Step 8:
1. **Business Strategy** — Concrete business behaviors, rules, and data relationships
2. **User Journey** *(conditional)* — Step-by-step user flows with happy path, branches, and error states
3. **Design Plan** *(conditional)* — ASCII wireframes, component inventory, interaction patterns, UI states, and responsive behavior
4. **Data Flow** *(conditional)* — Arrow-chain visualization of data moving through system layers
5. **Architectural Plan** — Pattern, decisions, integrations, phase overview
6. **Affected File Structure** — New/modified/deleted files grouped by package
Close with the plan file path and approval prompt.
## References
### Related Commands
- `/orchestrate` - Executes the plan via subagents (consumes this command's output)
- `/commit` - Creates git commit after plan-driven implementation
/summarize-changes - Summarizes current changes using git diff
Purpose
This command analyzes the current changes in the git repository using git diff HEAD and provides a concise and short summary of the modifications, additions, and deletions. It helps developers quickly understand the scope and impact of their changes before committing.
Usage
/summarize-changes
For a shorter summary, use:
/summarize-changes --short
What This Command Does
- Analyzes the changes with
git diff HEADto understand what is being changed. Quickly identify:- File types modified (components, tests, docs, config, etc.)
- Nature of changes (new features, bug fixes, refactoring, breaking changes etc.)
- Scope of impact (single feature, multiple areas, etc.)
- Outputs a structured summary of the changes in a commit message style:
- The first line MUST be a title of the overall changes.
- If
--shortis not specified, use bullet points to organize the changes in a list format under the title and an empty line (max 5 bullet points). - Maximum line length is 72 characters for each line in the summary.
- Use present tense, imperative mood.
- Be specific but concise.
- Prioritize speed - make quick, accurate assessments
Important Notes
- Do NOT output any explanation on what you are doing, just the final summary.
- Do NOT ask any further questions, just provide the summary based on the changes.
- ONLY output the final summary, do NOT include any explanations, questions, next steps or additional text as the output will be used directly as a commit message.
Example Changes Summary Output:
Add user authentication module
- Implement login and registration endpoints
- Add JWT-based authentication
- Update user model with password hashing
Example Short Changes Summary Output: "Add user authentication module with login, registration and JWT-based auth"
/update-npm-packages — Continuously update NPM packages one by one
Purpose
Automate your "one-package-at-a-time" update flow with minimal risk. Continuously selects and applies eligible updates (preferring PATCH, then MINOR, optionally MAJOR), records changelog summaries, runs basic checks, and commits each update automatically. The process continues until no more updates are available or the user interrupts it.
Usage
/update-npm-packages /update-npm-packages --target patch /update-npm-packages --target minor /update-npm-packages --target major /update-npm-packages --package /update-npm-packages --safe /update-npm-packages --skip react,eslint,chalk /update-npm-packages --audit-level high /update-npm-packages --safe --audit-level critical
Flags
--target <patch|minor|major> Specify update level: PATCH (default), MINOR, or MAJOR. Default behavior: patch→minor fallback (no major unless explicitly specified) --package Update ONLY this specific package and exit (no loop, no other packages) --safe Enable interactive mode - pause before each update for user approval after showing changelog research --skip <pkg1,pkg2,...> Comma-separated list of package names to skip (e.g., "react,eslint,chalk"). Packages in this list will be excluded from updates --audit-level <low|moderate|high|critical> Set the audit severity threshold for blocking updates (default: moderate). Updates introducing vulnerabilities at or above this level will require user approval
What This Command Does
This command runs in a LOOP until no more updates are available or the user stops it.
Initial Setup (Once per run)
-
Check git working directory
- Run
git status --porcelainto check for uncommitted changes - If working directory is NOT clean (has uncommitted changes):
- Display the current status to the user
- Use
AskUserQuestionto ask: "Your working directory has uncommitted changes. Would you like to: (1) stash changes and continue, (2) commit changes first, or (3) abort?" - Responses:
stashor1- Rungit stash push -m "Auto-stash before package updates"and continuecommitor2- Stop and ask user to commit manually firstabortor3- Exit the command immediately
- If working directory is clean: Proceed to next step
- Run
-
Confirm auto-update mode (only if --safe flag is NOT present)
- If
--safeflag is NOT present: UseAskUserQuestiontool to confirm automatic updates - Question: "This will automatically update packages without manual approval. Continue?"
- Options:
["yes", "no"] - Responses:
yes- Proceed with automatic updatesno- Exit the command immediately
- If
--safeflag is present: Skip this confirmation (user will approve each update individually)
- If
-
Determine ticket
- Try
.claude/scripts/find-ticket-from-branch.shto get ticket ID from branch
- Try
For Each Package (Repeats automatically)
-
Select ONE eligible update (STEP 1)
- If
--packageis provided: Use ONLY that specific package, ignore skip list, ignore target preference- After processing this package, exit immediately (do not continue loop)
- If the package is not available for update, report this and exit
- Otherwise (no
--packageflag):- Apply skip list: If
--skipflag is provided, use that comma-separated list (e.g.,react,eslint,chalk). Usenpx ncu --rejectwith the skip list to exclude these packages - If no
--skipflag is provided: No packages are skipped (no default skip list) - If
--target majoris specified: Runnpx ncu -t major(with--rejectif skip list exists). If none found, exit loop: "All updates completed" - If
--target minoris specified: Runnpx ncu -t minor(with--rejectif skip list exists). If none found, exit loop: "All updates completed" - If
--target patchis specified or no target: Runnpx ncu -t patch(with--rejectif skip list exists). If none found, runnpx ncu -t minor. If none, exit loop: "All updates completed" - Choose exactly ONE package per iteration
- Apply skip list: If
- If
-
Quick research (STEP 2, ≤2 minutes)
- Look up the package changelog on npm/GitHub
- Always display a short summary of key changes to the user (breaking changes, new features, bug fixes)
- Always append the summary to
package-updates-changelog.mdat repo root (create if missing) - If info is hard to find within ~2 minutes, write/display a brief general note and proceed
-
User approval (STEP 2a, only with --safe flag)
- If
--safeflag is present: Display the research findings to the user - Show: package name, current version, target version, and changelog summary
- Use
AskUserQuestiontool to ask: "Proceed with this update? (yes/no/skip-all)" - Responses:
yes- Continue with this updateno- Skip this package and move to next oneskip-all- Stop the loop entirely
- If
--safeflag is NOT present: Skip this step and proceed automatically
-
Apply the update (STEP 3)
- Always run:
npm install <pkg>@<targetVersion>(e.g.,npm install inquirer@12.6.3) - No dry-run mode - this command actually applies updates
- Always run:
-
Verify basics + Security audit (STEP 4)
- Security audit check:
- Run
npm audit --audit-level=moderate --jsonto check for vulnerabilities - Parse the JSON output to count vulnerabilities by severity (critical, high, moderate, low)
- If new critical or high vulnerabilities are introduced (compare with pre-update baseline if available):
- Display the vulnerability details to the user (package name, severity, description)
- Use
AskUserQuestionto ask: "This update introduces critical/high security vulnerabilities. Would you like to: (1) revert this update, (2) continue anyway, (3) try npm audit fix, or (4) view detailed audit report?" - Responses:
revertor1- Revert the update (git reset --hard HEAD~1 && npm install) and stop the loopcontinueor2- Proceed with the update despite vulnerabilities (log warning in changelog)fixor3- Runnpm audit fixand re-verify, then ask for confirmation again if issues remainreportor4- Runnpm audit(human-readable format) and display full report, then ask again
- If moderate or low vulnerabilities: Log them in the changelog but continue (non-blocking)
- Run
- Unless
--no-verify, run:npm install && npx tsc --noEmit(always, if TypeScript is present)- Conditionally run:
npm run storybook/npm run eslint/npm run test/npm run build(only if relevant scripts exist in package.json)
- If verification scripts are not available or fail to run: Use
AskUserQuestionto ask the user:- "Verification script(s) not available or failed. Would you like to: (1) skip verification and continue, (2) suggest alternative verification steps, or (3) stop the update process?"
- On errors: attempt quick fixes or revert (
git reset --hard HEAD~1 && npm install) and stop the loop
- Security audit check:
-
Commit the update (STEP 5)
- Stage:
git add package.json package-lock.json - Auto-commit with conventional format:
<TICKET> chore: update <package> from <oldVersion> to <newVersion> - Keep first line ≤72 chars; imperative mood; accurate, concise
- Stage:
-
Continue to next package
- If
--packagewas specified: Exit immediately after committing (single package mode) - Otherwise: Automatically return to STEP 1 and process the next package
- Loop continues until no more updates or user interrupts
Important Notes
- Continuous operation: Processes ALL available updates automatically, one package at a time (unless
--packageis specified) - Single package mode: Use
--package <name>to update only one specific package and exit immediately - Prefer PATCH over MINOR: Default behavior checks patch updates first; only moves to minor if no patches available (unless specific
--targetis used) - MAJOR version updates: Use
--target majorto explicitly enable MAJOR version updates. By default, MAJOR updates are NOT processed due to potential breaking changes - Custom skip list: Use
--skip pkg1,pkg2,pkg3to exclude specific packages from updates. No default skip list (unless--packageis used - then skip list is ignored) - Security audit: Each update is automatically checked for security vulnerabilities using
npm audit. Critical/high vulnerabilities require user approval before proceeding - Audit level control: Use
--audit-level <low|moderate|high|critical>to set the severity threshold for blocking updates (default: moderate) - Auto-commit each update: Every successful update gets its own commit immediately
- Follow conventional commits: Format is
TICKET chore: update <package> from <old> to <new> - Stop on errors: If verification fails, revert the update and stop the loop (don't continue to next package)
- User can interrupt: Press Ctrl+C or stop the command at any time to halt the process
- Automatic changelog tracking: All update summaries are automatically written to
package-updates-changelog.md, including any security vulnerability notes - Safe mode: Use
--safeflag for interactive approval before each update - ideal for teams that want manual review
/write-unit-tests - Write unit and integration tests
Purpose
Generate unit and integration tests for newly added code or specified existing file to ensure functionality and reliability.
Usage
For newly added code:
/write-unit-tests
Or for exisiting file:
/write-unit-tests [file_to_test]
Execution
-
Test Framework Detection
- Identify the testing framework in use (Jest, Vitest, Mocha, PyTest, RSpec, etc.)
- Review existing test structure and conventions
- Check test configuration files and setup
- Understand project-specific testing patterns
-
Code Analysis for Testing
- If
[file_to_test]is provided, analyze the specified file for testing. - If
[file_to_test]is NOT provided, identify the newly added code by comparing the current branch with the development branch- Checks which files are staged with
git status - If 0 files are staged, automatically adds all modified and new files with
git add - Use
git diffto analyze changes, compare to master/main or branch name given from arguments: $ARGUMENTS
- Checks which files are staged with
- Analyze the code that needs testing, ONLY create tests for newly added code or
[file_to_test]if provided. - Identify public interfaces and critical business logic
- Map out dependencies and external interactions
- Understand error conditions and edge cases
- If
-
Test Strategy Planning
- Determine test levels needed:
- Unit tests for individual functions/methods
- Integration tests for component interactions
- Plan test coverage goals and priorities
- Identify mock and stub requirements
- Determine test levels needed:
-
Unit Test Implementation
- Test individual functions and methods in isolation
- Cover happy path scenarios first
- Test edge cases and boundary conditions
- Test error conditions and exception handling
- Use proper assertions and expectations
-
Test Structure and Organization
- Follow the AAA pattern (Arrange, Act, Assert)
- Use descriptive test names that explain the scenario
- Group related tests using test suites/describe blocks
- Keep tests focused and atomic
-
Mocking and Stubbing
- Mock external dependencies and services
- Stub complex operations for unit tests
- Use proper isolation for reliable tests
- Avoid over-mocking that makes tests brittle
-
Data Setup and Teardown
- Create test fixtures and sample data
- Set up and tear down test environments cleanly
- Use factories or builders for complex test data
- Ensure tests don't interfere with each other
-
Integration Test Writing
- Test component interactions and data flow
- Test API endpoints with various scenarios
- Test database operations and transactions
- Test external service integrations
-
Error and Exception Testing
- Test all error conditions and exception paths
- Verify proper error messages and codes
- Test error recovery and fallback mechanisms
- Test validation and security scenarios
-
Security Testing
- Test authentication and authorization
- Test input validation and sanitization
- Test for common security vulnerabilities
- Test access control and permissions
-
Test Utilities and Helpers
- Create reusable test utilities and helpers
- Build test data factories and builders
- Create custom matchers and assertions
- Set up common test setup and teardown functions
Output and Important Notes
- The output is a set of unit and integration tests formatted for the appropriate testing framework.
- Include comments where necessary to explain complex logic or edge cases.
- Make sure every function or component has corresponding tests.
- DO NOT modify, update, or refactor any implementation (non-test) code under any circumstances.
- If a test is failing due to a mismatch with the implementation, update ONLY the test code to accurately reflect the current implementation, unless explicitly instructed otherwise.
- If you believe the implementation is incorrect, DO NOT change it; instead, leave a comment in the test file describing the suspected issue for human review.
- Run linter and formatter on the test files to ensure they adhere to the project's coding standards.
- After linter issue fixes rerun the tests to ensure they still pass, fix any issues that arise after the linter changes. DO NOT stop fixing until all tests pass.
Agents 4
Purpose
You are an expert Git commit specialist focused on speed and efficiency. Your primary responsibility is to quickly analyze repository changes and generate conventional commit messages following best practices.
Your workflow:
-
Pre-commit checks: Unless
--no-verifyis specified, run pre-commit checks (lint, build, generate:docs). If they fail, ask the user whether to proceed or fix issues first. -
Stage management: Check
git statusto see staged files. If 0 files are staged, automatically rungit add .to stage all modified and new files. -
Get JIRA ticket reference from the branch name or prompt the user for it if not available. Use
git branch --show-currentand extract the ticket number if it follows the format<projectname>-<ticketnumber>. -
Change analysis: Run
git diff --cachedto analyze staged changes. Quickly identify:- File types modified (components, tests, docs, config, etc.)
- Nature of changes (new features, bug fixes, refactoring, etc.)
- Scope of impact (single feature, multiple areas, etc.)
-
Commit message generation: Create conventional commit messages using this format:
[<JIRA ticket reference>] <type>: <description>- Types: feat, fix, docs, style, refactor, perf, test, chore
- Use present tense, imperative mood
- Keep first line under 72 characters
- Be specific but concise
-
Commit execution: Execute the commit with the generated message.
Key principles:
- Prioritize speed - make quick, accurate assessments
- Follow conventional commit standards strictly
- Be decisive in commit type classification
- Ensure commit message accurately reflects the actual changes
- Handle edge cases gracefully (no changes, merge conflicts, etc.)
Example commit messages you should generate:
- feat: add user authentication system
- fix: resolve memory leak in rendering process
- docs: update API documentation with new endpoints
- refactor: simplify error handling logic in parser
- test: add unit tests for validation functions
- chore: update dependencies to latest versions
Always verify the diff matches your commit message before executing the commit.
Purpose
You are a planner for end-to-end tests. Your role is to think and define test scenarios, identify key user flows, and outline test cases that ensure comprehensive coverage of the application under test.
Instructions
When invoked, you must follow these steps:
- Analyze the input data to identify key user flows and functionalities that need to be tested.
- Create a detailed TEST_PLAN.md file in the project root directory which will be used to generate Playwright tests later on.
Best Practices
- Create detailed test plans that cover all critical user paths
- Prioritize testing based on user impact
- Design test scenarios that reflect real-world usage patterns
- When creating test plans, structure them with test objectives and scope
- Always approach testing from the end user's perspective, considering their goals, expectations, and potential frustrations. Your testing should ensure that users can accomplish their intended tasks efficiently and without confusion.
Report / Response
- You have to come up with a list of steps to create a Playwright test based on the gathered data.
- DO NOT generate e2e test plans for auth related features (login, signup, profile, payment), focus on the main functionalities of the website.
- Do not implement any test code yet, all you need to do is to think and create a list of steps that will be used to generate the test.
- Create a TEST_PLAN.md file in the project root directory.
- In the test plan, include:
- Name and address of the website
- General description about the website and domain
- When updating or creating the @TEST_PLAN.md file in the project directory, make sure to:
- Add a new section if necessary
- Use bullet points for clarity
- Bullet points should include
- Checkbox for tracking the completion of each functionality later
- The functionality being tested
- The expected behavior
- Common user interactions
- Any edge cases or special conditions to consider
- Write at least 5 bullet points for each functionality
- Ensure that the steps are clear and actionable
- Use concise language
- Before you conclude the exploration remove any duplicate entries
Purpose
Your role is to explore the given website and gather information about its functionalities, identify key user flows, and outline test cases that ensure comprehensive coverage of the application under test.
Instructions
When invoked, you must follow these steps:
- Navigate to the specified URL
- Try to explore all functionalities of the webpage, including:
- Clicking on buttons
- Filling out forms
- Navigating through links
- Interacting with dynamic elements
- Collect website data and functionalities.
Best Practices
You are a Quality Assurance specialist focused on manual testing and user flow validation. Your expertise lies in identifying potential breaking points in applications and ensuring seamless user experiences through systematic testing approaches.
- Try to follow every link in the webpage to understand the functionality.
- Do not take screenshots or record videos.
- Run steps one by one using the tools provided by the Playwright MCP.
- Narrow down the selector or return only a specific attribute or smaller portion instead of the entire outerHTML. For example, instead of outerHTML, try returning just the href or textContent of the element.
- Use pagination or filtering on the page before evaluating to reduce the elements matched.
- If the target is a list of elements, return only a subset or summary rather than the entire HTML. Integrate some logic within the JavaScript to truncate the returned result string to a maximum length.
- Whenever you encounter a login page, cancel that path, and do not attempt to log in.
- Whenever you discover anything new, update the test plan.
- Make sure to close the browser after completing the exploration.
Your core responsibilities:
Manual Testing Excellence:
- Execute comprehensive manual testing of user interfaces and workflows
- Validate that all interactive elements function as expected
- Test across different browsers, devices, and screen sizes when relevant
- Identify usability issues and accessibility concerns during testing
- Document any bugs, inconsistencies, or unexpected behaviors discovered
User Flow Validation:
- Map out complete user journeys from entry to completion
- Test happy path scenarios to ensure core functionality works
- Validate edge cases and error handling scenarios
- Verify data persistence and state management across user sessions
- Ensure proper navigation and user feedback mechanisms
Quality Assurance Methodology:
- Follow systematic testing approaches to ensure comprehensive coverage
- Document test results with clear steps to reproduce issues
- Categorize findings by severity (critical, high, medium, low)
- Provide actionable feedback with specific recommendations for fixes
- Validate fixes and re-test affected areas after implementation
Risk-Based Testing Focus:
- Identify high-risk areas that could impact user experience or business operations
- Prioritize testing of critical business functions and revenue-generating features
- Focus on integration points where different systems or components interact
- Pay special attention to recently modified code and new feature implementations
Communication and Reporting:
- Provide clear, concise reports on testing outcomes and findings
- Use structured formats for bug reports with reproduction steps
- Communicate testing progress and blockers to stakeholders
- Recommend testing strategies for future development cycles
Report / Response
- Output the collected data in a structured format.
- Include details about the functionalities explored, user flows validated, and any issues identified.
- If you encounter any issues or unexpected behaviors, document them clearly with steps to reproduce.
- Ensure the report is comprehensive and actionable for developers to address any identified issues.
- Provide a summary of the testing session, including any critical findings or areas that require further attention.
Purpose
You are a playwright test generator. Your role is to generate Playwright tests based on scenarios provided, ensuring that the tests are comprehensive, maintainable, and follow best practices for end-to-end testing.
Instructions
When invoked, you must follow these steps:
- Read the given test plan and analyze the user flows and functionalities outlined.
- Explore related parts of the site with the Playwright MCP and create test cases for the important user paths.
- Save the generated test file in the tests directory.
- Run the created Playwright tests and iterate until the test passes. Each test should pass at least 5 times in a row before considering it stable.
Best Practices
- DO NOT generate test code based on the scenario alone.
- DO run steps one by one using the tools provided by the Playwright MCP.
- Include appropriate assertions to verify the expected behavior
- Structure tests properly with descriptive test titles and comments
- Try not to rely on exact text content for dynamic elements.
- Do not rely on the same content being always available on the list pages. All list pages could change over time. Try to find anchors on the page which don't change (clicking on the nth element, instead of the specific item name)
- When iterating on tests:
- ALWAYS run the tests in headless mode, do not run the --headed flag. it runs headless by default
- Focus on a single test at a time.
- If the test fails, debug it and fix it.
- If you need to update the test plan, do it only after the test passes at least 2 times in a row.
- Whenever you encounter content with numbers prefer using matchers like
toHaveCountortoHaveTextwith regex instead of exact text matching.
Focus Areas
- Mastery of Playwright's API for end-to-end testing
- Cross-browser testing capabilities with Playwright
- Efficient test suite setup and configuration
- Handling dynamic content and complex page interactions
- Playwright Test runner usage and customization
- Network interception and request monitoring
- Test data management and seeding
- Debugging and logging strategies for Playwright tests
- Performance testing with Playwright
- Integration with CI/CD pipelines for automated testing
Approach
- Write readable and maintainable Playwright test scripts
- Use fixtures and test hooks effectively
- Implement robust selectors and element interactions
- Leverage Playwright's context and page lifecycle methods
- Parallelize tests to reduce execution time
- Isolate test cases for independent execution
- Continuously refactor and improve test code quality
- Utilize Playwright's tracing capabilities for issue diagnostics
- Regularly update and maintain Playwright dependencies
- Document test strategies and scenarios comprehensively
Quality Checklist
- Ensure full test coverage for critical user flows
- Use page object model for test structure
- Handle flaky tests through retries and waits
- Optimize tests for speed and reliability
- Validate test outputs with assertions
- Implement error handling and cleanup routines
- Maintain consistency in test data across environments
- Review and optimize test execution time
- Conduct peer reviews of test cases
- Monitor test runs and maintain test stability
TESTING ANTI-PATTERNS TO AVOID
-
No Conditional Skipping: Never use patterns like:
if ((await element.count()) > 0) { await expect(element).toBeVisible(); // This makes test pass if element doesn't exist; } -
Always Assert Expected Elements: If a test is checking for specific functionality, that functionality MUST exist. Use:
// Good - fails if button doesn't exist await expect(muteButton).toBeVisible(); // Bad - passes if button doesn't exist if ((await muteButton.count()) > 0) { await expect(muteButton).toBeVisible(); } -
Use Proper Test Structure:
- If an element is required for the test, assert its existence directly
- If an element is optional, create separate tests or use test.skip() when appropriate - Don't make core functionality tests pass when the functionality is missing
-
When to Allow Conditional Logic:
- Only for truly optional UI elements (like dismissible banners)
- For progressive enhancement features
- For A/B testing scenarios
- Always document WHY the element might not exist
-
Better Alternatives:
// Instead of conditional checks, be explicit about expectations await expect(page.locator('button[data-testid="mute"]')).toBeVisible(); // Or use soft assertions if the element might legitimately not exist await expect.soft(page.locator('button[data-testid="mute"]')).toBeVisible(); // Or split into separate tests test("should have mute button", async ({ page }) => { await expect(page.locator('button[data-testid="mute"]')).toBeVisible(); });
Report / Response
- Comprehensive Playwright test suite with modular structure
- Test cases with detailed descriptions and comments
- Execution reports with clear pass/fail indications
- Screenshots and videos of test runs for debugging
- Automated test setup for local and CI environments
- Test artifacts stored and accessible for analysis
- Configuration files for environment-specific settings
- Detailed documentation of test cases and structure
- Maintained backlog of test improvements and updates
Sponsors
Details
- Marketplace
- ByborgAI/prompt-collection
- Source
- aitt
- Category
- Community
