Skill: smokealot420/ftw (version 1.0.3)

--- name: piv description: "PIV workflow orchestrator - Plan, Implement, Validate loop for systematic multi-phase software development. Use when building features phase-by-phase with PRPs, automated validation loops, or multi-agent orchestration. Supports PRD creation, PRP generation, codebase analysis, and iterative execution with validation." user-invocable: true disable-model-invocation: true metadata: {"openclaw":{"emoji":"gear","homepage":"https://github.com/SmokeAlot420/ftw","requires":{"bins":["git"]},"os":["darwin","linux"]}} --- # PIV Ralph Orchestrator ## Arguments: $ARGUMENTS Parse arguments using this logic: ### PRD Path Mode (first argument ends with `.md`) If the first argument ends with `.md`, it's a direct path to a PRD file: - `PRD_PATH` - Direct path to the PRD file - `PROJECT_PATH` - Derived by going up from PRDs/ folder - `START_PHASE` - Second argument (default: 1) - `END_PHASE` - Third argument (default: auto-detect from PRD) ### Project Path Mode If the first argument does NOT end with `.md`: - `PROJECT_PATH` - Absolute path to project (default: current working directory) - `START_PHASE` - Second argument (default: 1) - `END_PHASE` - Third argument (default: 4) - `PRD_PATH` - Auto-discover from `PROJECT_PATH/PRDs/` folder ### Detection Logic ``` If $ARGUMENTS[0] ends with ".md": PRD_PATH = $ARGUMENTS[0] PROJECT_PATH = dirname(dirname(PRD_PATH)) START_PHASE = $ARGUMENTS[1] or 1 END_PHASE = $ARGUMENTS[2] or auto-detect from PRD PRD_NAME = basename without extension Else: PROJECT_PATH = $ARGUMENTS[0] or current working directory START_PHASE = $ARGUMENTS[1] or 1 END_PHASE = $ARGUMENTS[2] or 4 PRD_PATH = auto-discover from PROJECT_PATH/PRDs/ PRD_NAME = discovered PRD basename ``` ### Mode Detection After parsing arguments: - If PRD_PATH was provided or auto-discovered → **MODE = "execute"** (normal flow) - If no PRD found and no PRD_PATH provided → **MODE = "discovery"** --- ## Required Reading by Role **CRITICAL: Each role MUST read their instruction files before acting.** | Role | Instructions | |------|-------------| | Discovery (no PRD) | Read {baseDir}/references/piv-discovery.md | | PRD Creation | Read {baseDir}/references/create-prd.md | | PRP Generation | Read {baseDir}/references/generate-prp.md | | Codebase Analysis | Read {baseDir}/references/codebase-analysis.md | | Executor | Read {baseDir}/references/piv-executor.md + {baseDir}/references/execute-prp.md | | Validator | Read {baseDir}/references/piv-validator.md | | Debugger | Read {baseDir}/references/piv-debugger.md | **Prerequisite:** A PRD must exist before entering the Phase Workflow. If no PRD exists, the orchestrator enters Discovery Mode (see below). --- ## Discovery Mode (No PRD Found) When MODE = "discovery": 1. Read {baseDir}/references/piv-discovery.md for the discovery process 2. Present discovery questions to the user in a friendly, conversational tone (single message) - Target audience is vibe coders, not senior engineers — keep it approachable - Skip questions the user already answered in their initial message 3. Wait for user answers 4. Fill gaps with your own expertise: - If user doesn't know tech stack → research (web search, codebase scan) and PROPOSE one - If user can't define phases → propose 3-4 phases based on scope - Always propose-and-confirm: "Here's what I'd suggest — does this sound right?" 5. Run project setup (create PRDs/, PRPs/templates/, PRPs/planning/) 6. Generate PRD: Read {baseDir}/references/create-prd.md, use discovery answers + your proposals to write PRD to PROJECT_PATH/PRDs/PRD-{project-name}.md 7. Set PRD_PATH to the generated PRD, auto-detect phases → continue to Phase Workflow The orchestrator handles discovery and PRD generation directly (no sub-agent needed — interactive Q&A requires staying in the same session, and answers are already in context for PRD generation). --- ## Orchestrator Philosophy > "Context budget: ~15% orchestrator, 100% fresh per subagent" You are the **orchestrator**. You stay lean and manage workflow. You DO NOT execute PRPs yourself - you spawn specialized sub-agents with fresh context for each task. **Sub-agent spawning:** Use the `sessions_spawn` tool to create fresh sub-agent sessions. Each spawn is non-blocking — you'll receive results via an announce step. Wait for each agent's results before proceeding to the next step. --- ## Project Setup (piv-init) If the project doesn't have PIV directories, create them: ```bash mkdir -p PROJECT_PATH/PRDs PROJECT_PATH/PRPs/templates PROJECT_PATH/PRPs/planning ``` Copy `{baseDir}/assets/prp_base.md` to `PROJECT_PATH/PRPs/templates/prp_base.md` if it doesn't exist. Create `PROJECT_PATH/WORKFLOW.md` from `{baseDir}/assets/workflow-template.md` if it doesn't exist. --- ## Phase Workflow For each phase from START_PHASE to END_PHASE: ### Step 1: Check/Generate PRP Check for existing PRP: ```bash ls -la PROJECT_PATH/PRPs/ 2>/dev/null | grep -i "phase.*N\|pN\|p-N" ``` If no PRP exists, spawn a **fresh sub-agent** using `sessions_spawn` to do both codebase analysis and PRP generation in sequence: ``` RESEARCH & PRP GENERATION MISSION - Phase {N} ============================================== Project root: {PROJECT_PATH} PRD Path: {PRD_PATH} ## Phase {N} Scope (from PRD) {paste phase scope} ## Step 1: Codebase Analysis Read {baseDir}/references/codebase-analysis.md for the process. Save to: {PROJECT_PATH}/PRPs/planning/{PRD_NAME}-phase-{N}-analysis.md ## Step 2: Generate PRP (analysis context still loaded) Read {baseDir}/references/generate-prp.md for the process. Use template: PRPs/templates/prp_base.md Output to: {PROJECT_PATH}/PRPs/PRP-{PRD_NAME}-phase-{N}.md Do BOTH steps yourself. DO NOT spawn sub-agents. ``` ### Step 2: Spawn EXECUTOR Spawn a fresh sub-agent using `sessions_spawn`: ``` EXECUTOR MISSION - Phase {N} ============================ Read {baseDir}/references/piv-executor.md for your role definition. Read {baseDir}/references/execute-prp.md for the execution process. PRP Path: {PRP_PATH} Project: {PROJECT_PATH} Follow: Load PRP → Plan Thoroughly → Execute → Validate → Verify Output EXECUTION SUMMARY with Status, Files, Tests, Issues. ``` ### Step 3: Spawn VALIDATOR Spawn a fresh sub-agent using `sessions_spawn`: ``` VALIDATOR MISSION - Phase {N} ============================= Read {baseDir}/references/piv-validator.md for your validation process. PRP Path: {PRP_PATH} Project: {PROJECT_PATH} Executor Summary: {SUMMARY} Verify ALL requirements independently. Output VERIFICATION REPORT with Grade, Checks, Gaps. ``` **Process result:** PASS → commit | GAPS_FOUND → debugger | HUMAN_NEEDED → ask user ### Step 4: Debug Loop (Max 3 iterations) Spawn a fresh sub-agent using `sessions_spawn`: ``` DEBUGGER MISSION - Phase {N} - Iteration {I} ============================================ Read {baseDir}/references/piv-debugger.md for your debugging methodology. Project: {PROJECT_PATH} PRP Path: {PRP_PATH} Gaps: {GAPS} Errors: {ERRORS} Fix root causes, not symptoms. Run tests after each fix. Output FIX REPORT with Status, Fixes Applied, Test Results. ``` After debugger: re-validate → PASS (commit) or loop (max 3) or escalate. ### Step 5: Smart Commit ```bash cd PROJECT_PATH && git status && git diff --stat ``` Create semantic commit with `Built with FTW (First Try Works) - https://github.com/SmokeAlot420/ftw`. ### Step 6: Update WORKFLOW.md Mark phase complete, note validation results. ### Step 7: Next Phase Loop back to Step 1 for next phase. --- ## Error Handling - **No PRD**: Enter Discovery Mode (see Discovery Mode section above) - **Executor BLOCKED**: Ask user for guidance - **Validator HUMAN_NEEDED**: Ask user for guidance - **3 debug cycles exhausted**: Escalate to user ### Sub-Agent Timeout/Failure When a sub-agent times out or fails: 1. Check for partial work (files created, tests written) 2. Retry once with a simplified, shorter prompt 3. If retry fails, escalate to user with what was accomplished --- ## Completion ``` ## PIV RALPH COMPLETE Phases Completed: START to END Total Commits: N Validation Cycles: M ### Phase Summary: - Phase 1: [feature] - validated in N cycles ... All phases successfully implemented and validated. ```

path: assets/prp_base.md
content: name: "Base PRP Template v2 - Context-Rich with Validation Loops"
description: |

## Purpose
Template optimized for AI agents to implement features with sufficient context and self-validation capabilities to achieve working code through iterative refinement.

## Core Principles
1. **Context is King**: Include ALL necessary documentation, examples, and caveats
2. **Validation Loops**: Provide executable tests/lints the AI can run and fix
3. **Information Dense**: Use keywords and patterns from the codebase
4. **Progressive Success**: Start simple, validate, then enhance
5. **Global rules**: Follow any project-level configuration files (CLAUDE.md, AGENTS.md, .cursorrules, etc.)

---

## Goal
[What needs to be built - be specific about the end state and desires]

## Why
- [Business value and user impact]
- [Integration with existing features]
- [Problems this solves and for whom]

## What
[User-visible behavior and technical requirements]

### Success Criteria
- [ ] [Specific measurable outcomes]

## All Needed Context

### Documentation & References (list all context needed to implement the feature)
```yaml
# MUST READ - Include these in your context window
- url: [Official API docs URL]
  why: [Specific sections/methods you'll need]

- file: [path/to/example-file]
  why: [Pattern to follow, gotchas to avoid]

- doc: [Library documentation URL]
  section: [Specific section about common pitfalls]
  critical: [Key insight that prevents common errors]

- docfile: [PRPs/ai_docs/file.md]
  why: [docs that the user has pasted in to the project]

```

### Environment Check
```yaml
# Verify these tools exist before planning validation
model: [model name and context window, e.g., "Kimi K2.5 (131K)" or "Claude Opus (200K)"]
project_type: [detected from config files]
test_command: [verified working, e.g., "pytest", "pnpm test", "forge test"]
lint_command: [verified working, e.g., "ruff check", "eslint", "forge fmt --check"]
type_check: [if applicable, e.g., "mypy", "tsc --noEmit"]
build_command: [if applicable, e.g., "pnpm build", "forge build"]
```

### Current Codebase tree (run `tree` in the root of the project) to get an overview of the codebase
```bash

```

### Desired Codebase tree with files to be added and responsibility of file
```bash

```

### Known Gotchas of our codebase & Library Quirks
```
# CRITICAL: [Library name] requires [specific setup]
# Example: This framework requires specific initialization before use
# Example: This ORM doesn't support batch inserts over 1000 records
# Example: We use version X of this library which has breaking changes from version Y
```

## Implementation Blueprint

### Data models and structure

Create the core data models, we ensure type safety and consistency.
```
Examples:
 - Database models / ORM models
 - Type definitions / schemas
 - Validation rules
 - API request/response types
```

### list of tasks to be completed to fullfill the PRP in the order they should be completed

```yaml
Task 1:
MODIFY src/existing_module:
  - FIND pattern: "class OldImplementation"
  - INJECT after line containing "def __init__"
  - PRESERVE existing method signatures

CREATE src/new_feature:
  - MIRROR pattern from: src/similar_feature
  - MODIFY class name and core logic
  - KEEP error handling pattern identical

...(...)

Task N:
...

```


### Per task pseudocode as needed added to each task
```
# Task 1
# Pseudocode with CRITICAL details - don't write entire code
function new_feature(param):
    # PATTERN: Always validate input first (see src/validators)
    validated = validate_input(param)  # raises ValidationError

    # GOTCHA: This library requires connection pooling
    with get_connection() as conn:  # see src/db/pool
        # PATTERN: Use existing retry decorator
        @retry(attempts=3, backoff=exponential)
        function _inner():
            # CRITICAL: API returns 429 if >10 req/sec
            rate_limiter.acquire()
            return external_api.call(validated)

        result = _inner()

    # PATTERN: Standardized response format
    return format_response(result)  # see src/utils/responses
```

### Integration Points
```yaml
DATABASE:
  - migration: "Add column 'feature_enabled' to users table"
  - index: "CREATE INDEX idx_feature_lookup ON users(feature_id)"

CONFIG:
  - add to: config/settings
  - pattern: "FEATURE_TIMEOUT = env('FEATURE_TIMEOUT', default='30')"

ROUTES:
  - add to: src/api/routes
  - pattern: "router.include_router(feature_router, prefix='/feature')"
```

## Validation Loop

### Level 1: Syntax & Style
```bash
# Pre-flight: Verify commands exist before running
# command -v <tool> or which <tool> — report missing tools, don't fail silently

# Run these FIRST - fix any errors before proceeding
# Run your project's linter: e.g., ruff check, eslint, golangci-lint
# Run your project's type checker: e.g., mypy, tsc --noEmit, go vet

# Expected: No errors. If errors, READ the error and fix.
```

### Level 2: Unit Tests - each new feature/file/function use existing test patterns
```
# CREATE test files with these test case patterns:
# 1. Happy path - basic functionality works
# 2. Validation error - invalid input is rejected
# 3. Error handling - external failures handled gracefully
```

```bash
# Run your project's test suite: e.g., pytest, vitest, forge test, go test
# If failing: Read error, understand root cause, fix code, re-run (never mock to pass)
```

### Level 3: Integration Test
```bash
# Start the service (if applicable)
# Test the endpoint or integration point
# Verify expected behavior end-to-end
# If error: Check logs for stack trace
```

## Final validation Checklist
- [ ] All tests pass: [run your project's test command]
- [ ] No linting errors: [run your project's lint command]
- [ ] No type errors: [run your project's type check command]
- [ ] Manual test successful: [specific test command]
- [ ] Error cases handled gracefully
- [ ] Logs are informative but not verbose
- [ ] Documentation updated if needed

---

## Anti-Patterns to Avoid
- Don't create new patterns when existing ones work
- Don't skip validation because "it should work"
- Don't ignore failing tests - fix them
- Don't hardcode values that should be config
- Don't catch all exceptions - be specific


path: assets/workflow-template.md
content: # Project Workflow Tracker

**Project:** [PROJECT_NAME]
**Created:** [DATE]
**Generated by:** PIV Workflow

---

## Phase Progress

| Phase | Status | PRP File | Started | Completed | Notes |
|-------|--------|----------|---------|-----------|-------|
| 1 | Pending | - | - | - | - |
| 2 | Pending | - | - | - | - |
| 3 | Pending | - | - | - | - |
| 4 | Pending | - | - | - | - |

## Notes

- Add phase-specific observations, blockers, and decisions here.

---

*Updated by PIV workflow orchestrator*


path: references/codebase-analysis.md
content: # Codebase Analysis for Feature Planning

**Feature:** $ARGUMENTS

## Mission

Perform comprehensive codebase analysis to support PRP creation. This analysis provides the foundation for creating high-quality PRPs by understanding existing patterns, architecture, and potential gotchas.

## Analysis Process

### Phase 1: Structure Discovery

**Objective:** Map the project layout and understand the overall architecture.

1. **Project Layout Analysis**
   - Run `tree -L 3 -I 'node_modules|.git|dist|build|__pycache__|.next'` if available, otherwise use `ls -la` or equivalent directory listing
   - Identify entry points (main files, index files, app entry points)
   - Locate configuration files (package.json, pyproject.toml, tsconfig.json, foundry.toml, etc.)
   - Map the directory organization pattern (feature-based, layer-based, etc.)

2. **Configuration Review**
   - Read CLAUDE.md if it exists for project context
   - Review README.md for project documentation
   - Check environment configuration patterns (.env.example, config files)

3. **Dependency Analysis**
   - Identify key dependencies and their versions
   - Note any version constraints or compatibility requirements
   - Document external service integrations

### Phase 2: Feature-Specific Research

**Objective:** Find existing patterns and implementations relevant to the requested feature.

1. **Pattern Search**
   - Search for similar features or patterns by searching the codebase
   - Identify 2-3 reference implementations to follow
   - Note naming conventions used throughout the project

2. **Code Pattern Documentation**
   ```yaml
   patterns_found:
     - pattern_name: [name]
       location: [file:line]
       description: [how it works]
       relevance: [why it matters for this feature]
   ```

3. **Existing Conventions**
   - File naming conventions
   - Function/method naming patterns
   - Import/export patterns
   - Error handling approaches
   - Testing patterns

### Phase 3: Architecture Analysis

**Objective:** Understand how components interact and where new code should fit.

1. **Component Structure**
   - Map component/module relationships
   - Identify shared utilities and where they live
   - Document the data flow patterns

2. **API/Interface Patterns**
   - Internal API conventions
   - External API integrations
   - Data validation approaches

3. **State Management**
   - How state is managed (context, stores, hooks, etc.)
   - Data persistence patterns
   - Caching strategies

### Phase 4: Gotchas & Recommendations

**Objective:** Identify potential pitfalls and provide actionable guidance.

1. **Known Pitfalls**
   - Areas of technical debt
   - Non-obvious configurations
   - Environment-specific behaviors
   - Performance bottlenecks

2. **Best Practices to Follow**
   - Project-specific coding standards
   - Required testing approaches
   - Documentation requirements

3. **Implementation Recommendations**
   ```yaml
   recommendations:
     must_follow:
       - [critical patterns/conventions]
     should_follow:
       - [recommended approaches]
     avoid:
       - [anti-patterns in this codebase]
   ```

## Output

Create the analysis file at: `PRPs/planning/{feature-name}-analysis.md`

### Output Structure

```markdown
# Codebase Analysis: {Feature Name}

## Executive Summary
[2-3 sentences summarizing key findings for PRP creation]

## Project Structure
[Directory tree and key file locations]

## Relevant Patterns Found
[Existing implementations to reference]

## Architecture Insights
[Component relationships and data flow]

## Implementation Guidance
### Must Follow
- [Critical requirements]

### Recommended Approach
- [Suggested patterns]

### Avoid
- [Anti-patterns and pitfalls]

## Files to Reference
[Specific files the PRP should reference with line numbers]

## Validation Commands
[Project-specific commands for testing]
```

## Quality Gates

Before completing, verify:
- [ ] Project structure is fully mapped
- [ ] At least 2 reference implementations identified
- [ ] Naming conventions documented
- [ ] Error handling patterns noted
- [ ] Testing patterns identified
- [ ] Validation commands are project-specific and verified working
- [ ] Output saved to PRPs/planning/{feature-name}-analysis.md

## Usage

This process can be invoked:
1. **Directly**: As a standalone codebase analysis task
2. **Via generate-prp**: Referenced during PRP generation
3. **As a sub-agent**: Spawned for parallel research by the orchestrator

The analysis output feeds directly into PRP creation, providing the context needed for one-pass implementation success.


path: references/create-prd.md
content: # Create PRD: Generate Product Requirements Document

## Overview

Generate a comprehensive Product Requirements Document (PRD) based on the current conversation context and requirements discussed. Use the structure and sections defined below to create a thorough, professional PRD.

## Output File

Write the PRD to: `$ARGUMENTS` (default: `PRD.md`)

## PRD Structure

Create a well-structured PRD with the following sections. Adapt depth and detail based on discovery answers and available information:

### Required Sections

**1. Executive Summary**
- Concise product overview (2-3 paragraphs)
- Core value proposition
- MVP goal statement

**2. Mission**
- Product mission statement
- Core principles (3-5 key principles)

**3. Target Users**
- Primary user personas
- Technical comfort level
- Key user needs and pain points

**4. MVP Scope**
- **In Scope:** Core functionality for MVP
- **Out of Scope:** Features deferred to future phases
- Group by categories (Core Functionality, Technical, Integration, Deployment)

**5. User Stories**
- Primary user stories (5-8 stories) in format: "As a [user], I want to [action], so that [benefit]"
- Include concrete examples for each story
- Add technical user stories if relevant

**6. Core Architecture & Patterns**
- High-level architecture approach
- Directory structure (if applicable)
- Key design patterns and principles
- Technology-specific patterns

**7. Tools/Features**
- Detailed feature specifications
- If building an agent: Tool designs with purpose, operations, and key features
- If building an app: Core feature breakdown

**8. Technology Stack**
- Backend/Frontend technologies with versions
- Dependencies and libraries
- Optional dependencies
- Third-party integrations

**9. Security & Configuration**
- Authentication/authorization approach
- Configuration management (environment variables, settings)
- Security scope (in-scope and out-of-scope)
- Deployment considerations

**10. API Specification** (if applicable)
- Endpoint definitions
- Request/response formats
- Authentication requirements
- Example payloads

**11. Success Criteria**
- MVP success definition
- Functional requirements
- Quality indicators
- User experience goals

**12. Implementation Phases**
- Break down into 3-4 phases
- Each phase includes: Goal, Deliverables, Validation criteria
- Realistic timeline estimates

**13. Future Considerations**
- Post-MVP enhancements
- Integration opportunities
- Advanced features for later phases

**14. Risks & Mitigations**
- 3-5 key risks with specific mitigation strategies

**15. Appendix** (if applicable)
- Related documents
- Key dependencies with links
- Repository/project structure

## Discovery Phase (Before Writing)

Before generating the PRD, gather key information through quick discovery questions.
If the user hasn't provided enough context, ask:

### Required Discovery
1. **What are you building?** Quick description of the product/feature.
2. **What model/platform are you using?** (e.g., Kimi K2.5, Claude Opus, OpenAI o3, GPT-5.2, local model)
   - This determines context window limits and sub-agent sizing
3. **What's the target tech stack?** Languages, frameworks, key libraries.
4. **Any existing codebase?** If yes, what's the repo/path?

### Optional Discovery (ask if unclear)
5. **Who are the users?** Target audience description.
6. **What does "done" look like?** 1-3 success criteria.
7. **What's explicitly OUT of scope?** Features to defer.

### Model Context Awareness
Record the model and its context window in the PRD metadata:
- Kimi K2.5: 131K tokens
- Claude Opus/Sonnet: 200K tokens
- OpenAI o3/GPT-5.2: varies
- Local models: check config

This info propagates to PRP generation and sub-agent prompt sizing.

## Instructions

### 1. Extract Requirements
- Review the entire conversation history
- Identify explicit requirements and implicit needs
- Note technical constraints and preferences
- Capture user goals and success criteria

### 2. Synthesize Information
- Organize requirements into appropriate sections
- Fill in reasonable assumptions where details are missing
- Maintain consistency across sections
- Ensure technical feasibility

### 3. Write the PRD
- Use clear, professional language
- Include concrete examples and specifics
- Use markdown formatting (headings, lists, code blocks, checkboxes)
- Add code snippets for technical sections where helpful
- Keep Executive Summary concise but comprehensive

### 4. Quality Checks
- All required sections present
- User stories have clear benefits
- MVP scope is realistic and well-defined
- Technology choices are justified
- Implementation phases are actionable
- Success criteria are measurable
- Consistent terminology throughout

## Style Guidelines

- **Tone:** Professional, clear, action-oriented
- **Format:** Use markdown extensively (headings, lists, code blocks, tables)
- **Specificity:** Prefer concrete examples over abstract descriptions
- **Length:** Comprehensive but scannable

## Output Confirmation

After creating the PRD:
1. Confirm the file path where it was written
2. Provide a brief summary of the PRD contents
3. Highlight any assumptions made due to missing information
4. Suggest next steps (e.g., review, refinement, planning)

## Notes

- Ask discovery questions if the user starts with minimal context — don't assume
- If critical information is missing, ask clarifying questions before generating
- Adapt section depth based on available details
- For highly technical products, emphasize architecture and technical stack
- For user-facing products, emphasize user stories and experience
- This command contains the complete PRD template structure - no external references needed


path: references/execute-prp.md
content: # Execute BASE PRP

## PRP File: $ARGUMENTS

## Mission: One-Pass Implementation Success

PRPs enable working code on the first attempt through:

- **Context Completeness**: Everything needed, nothing guessed
- **Progressive Validation**: 4-level gates catch errors early
- **Pattern Consistency**: Follow existing codebase approaches

**Your Goal**: Transform the PRP into working code that passes all validation gates.

## Execution Process

1. **Load PRP**
   - Read the specified PRP file completely
   - Absorb all context, patterns, requirements and gather codebase intelligence
   - Use the provided documentation references and file patterns, consume the right documentation before the appropriate task
   - Trust the PRP's context and guidance - it's designed for one-pass success
   - If needed do additional codebase exploration and research as needed

   ### Research Tools (If Stuck or Need More Context)
   Use whatever research tools your platform provides:
   - **Web search** — for documentation, tutorials, examples
   - **Shell/command runner** — use `gh` CLI for GitHub code search, repo exploration
   - **File search** — search the codebase for patterns, similar implementations

   **If specific tools are unavailable**, rely on PRP context and your training knowledge. Do not block on missing tools.

   **Priority:** Codebase search for patterns > GitHub CLI for code examples > Web search for concepts

2. **Think Deeply & Plan**
   - Create comprehensive implementation plan following the PRP's task order
   - Break down into clear tasks and track your progress systematically
   - Follow the patterns referenced in the PRP
   - Work through each task systematically, verifying as you go
   - Use specific file paths, class names, and method signatures from PRP context
   - Never guess - always verify the codebase patterns and examples referenced in the PRP yourself

3. **Execute Implementation**
   - Follow the PRP's Implementation Tasks sequence, add more detail as needed, especially when using subagents
   - Use the patterns and examples referenced in the PRP
   - Create files in locations specified by the desired codebase tree
   - Apply naming conventions from the task specifications and CLAUDE.md

4. **Progressive Validation**

   **Execute the level validation system from the PRP:**
   - **Level 1**: Run syntax & style validation commands from PRP
   - **Level 2**: Execute unit test validation from PRP
   - **Level 3**: Run integration testing commands from PRP
   - **Level 4**: Execute specified validation from PRP

   **Each level must pass before proceeding to the next.**

5. **Completion Verification**
   - Work through the Final Validation Checklist in the PRP
   - Verify all Success Criteria from the "What" section are met
   - Confirm all Anti-Patterns were avoided
   - Implementation is ready and working

**Failure Protocol**: When validation fails, use the patterns and gotchas from the PRP to fix issues, then re-run validation until passing.


path: references/generate-prp.md
content: # Create BASE PRP

## Feature: $ARGUMENTS

## PRP Creation Mission

Create a comprehensive PRP that enables **one-pass implementation success** through systematic research and context curation.

**Critical Understanding**: The executing AI agent only receives:

- The PRP content you create
- Its training data knowledge
- Access to codebase files (but needs guidance on which ones)

**Therefore**: Your research and context curation directly determines implementation success. Incomplete context = implementation failure.

## Research Process

- Start by invoking the codebase-analysis subagent if this is a new feature or bugfix in an existing project, then read the markdown file it produces in the PRPs/planning folder.
- When invoking the codebase analysis subagent, prompt it to research the codebase for the specific feature being implemented.

> During the research process, work through all analysis steps yourself within this session. Do NOT spawn sub-agents. The deeper research we do here the better the PRP will be. We optimize for chance of success and not for speed.

1. **Codebase Analysis in depth**
   - Search the codebase thoroughly for similar features/patterns. Think hard and plan your approach
   - Identify all the necessary files to reference in the PRP
   - Note all existing conventions to follow
   - Check existing test patterns for validation approach

2. **External Research at scale**
   - Do deep research for similar features/patterns online and include urls to documentation and examples
   - Library documentation (include specific URLs)
   - For critical pieces of documentation add a .md file to PRPs/ai_docs and reference it in the PRP with clear reasoning and instructions
   - Implementation examples (GitHub/StackOverflow/blogs)
   - Best practices and common pitfalls found during research

   ### Research Tools (If Available)
   Use whatever research tools your platform provides:
   - **Web search** — for documentation, tutorials, examples
   - **Shell/command runner** — use `gh` CLI for GitHub code search, repo exploration
   - **File search** — search the codebase for patterns, similar implementations

   **If specific tools are unavailable**, rely on PRP context and your training knowledge. Do not block on missing tools.

   **Priority:** Codebase search for patterns > GitHub CLI for code examples > Web search for concepts

3. **User Clarification**
   - Ask for clarification if you need it

## PRP Generation Process

### Step 1: Choose Template

Use the PRP template (`prp_base.md`) as your template structure - it contains all necessary sections and formatting.

### Step 2: Context Completeness Validation

Before writing, apply the **"No Prior Knowledge" test** from the template:
_"If someone knew nothing about this codebase, would they have everything needed to implement this successfully?"_

### Step 3: Research Integration

Transform your research findings into the template sections:

**Goal Section**: Use research to define specific, measurable Feature Goal and concrete Deliverable
**Context Section**: Populate YAML structure with your research findings - specific URLs, file patterns, gotchas
**Implementation Tasks**: Create dependency-ordered tasks using information-dense keywords from codebase analysis
**Validation Gates**: Use project-specific validation commands that you've verified work in this codebase

### Step 4: Information Density Standards

Ensure every reference is **specific and actionable**:

- URLs include section anchors, not just domain names
- File references include specific patterns to follow, not generic mentions
- Task specifications include exact naming conventions and placement
- Validation commands are project-specific and executable

### Step 5: Plan Thoroughly Before Writing

After research completion, create a comprehensive PRP writing plan:

- Plan how to structure each template section with your research findings
- Identify gaps that need additional research
- Create systematic approach to filling template with actionable context

## Output

Save as: `PRPs/{feature-name}.md` (avoid calling it INITIAL.md)

## PRP Quality Gates

### Context Completeness Check

- [ ] Passes "No Prior Knowledge" test from template
- [ ] All YAML references are specific and accessible
- [ ] Implementation tasks include exact naming and placement guidance
- [ ] Validation commands are project-specific and verified working

### Template Structure Compliance

- [ ] All required template sections completed
- [ ] Goal section has specific Feature Goal, Deliverable, Success Definition
- [ ] Implementation Tasks follow dependency ordering
- [ ] Final Validation Checklist is comprehensive

### Information Density Standards

- [ ] No generic references - all are specific and actionable
- [ ] File patterns point at specific examples to follow
- [ ] URLs include section anchors for exact guidance
- [ ] Task specifications use information-dense keywords from codebase

## Success Metrics

**Confidence Score**: Rate 1-10 for one-pass implementation success likelihood

**Validation**: The completed PRP should enable an AI agent unfamiliar with the codebase to implement the feature successfully using only the PRP content and codebase access.


path: references/piv-debugger.md
content: # PIV Debugger Agent

You are the **Debugger** sub-agent in the PIV (Plan-Implement-Validate) workflow.

## Your Mission

Fix specific gaps identified by the Validator. You receive a precise list of what's wrong - your job is targeted fixes, not broad refactoring.

## Input Format

You will receive:
- `PROJECT_PATH` - Absolute path to the project root
- `GAPS` - List of specific gaps from validator
- `ERROR_DETAILS` - Build/test error messages if any

## Debugging Process

### 1. Root Cause Analysis

For each gap, determine the **root cause**, not just symptoms:

```
Gap: "buy() function doesn't check minimum amount"

WRONG approach: Just add the check
RIGHT approach:
1. Why was it missing? (Forgot? Misunderstood spec? Copy-paste error?)
2. Are there similar issues in other functions?
3. What's the correct fix per the PRP?
```

### 2. Apply Targeted Fixes

For each gap:
1. Read the relevant file(s)
2. Understand the existing code
3. Apply minimal fix that addresses the gap
4. Don't refactor unrelated code

### 3. Re-run Validation Commands

After fixes, verify they work:

```bash
# Run whatever validation commands the project uses
# e.g., build, lint, test, type-check
```

### 4. Output Fix Report

```
## FIX REPORT

### Status: [FIXED|STUCK]

### Gaps Addressed:

#### Gap 1: [description from validator]
- **Root Cause**: Why this gap existed
- **Fix Applied**: What you changed
- **File(s) Modified**: path/to/file:line
- **Verification**: Test/build that confirms fix

#### Gap 2: ...

### Test Results (after fixes):
- [test command]: [PASS|FAIL]

### Remaining Issues:
- Any gaps you couldn't fix
- Why they're stuck

### Notes:
- Related issues discovered
- Recommendations for future
```

## Key Rules

1. **Fix the root cause, not the symptom** - Understand why before fixing
2. **Minimal changes** - Fix only what's broken, don't refactor
3. **One gap at a time** - Address gaps systematically
4. **Verify each fix** - Run relevant tests after each change
5. **Be honest about stuck items** - If you can't fix something, say so

## What Constitutes Each Status

### FIXED
- All gaps from validator addressed
- Tests now pass
- Build succeeds
- Ready for re-validation

### STUCK
- One or more gaps cannot be fixed because:
  - Unclear what the fix should be
  - Fix requires changes outside your scope
  - Dependency or tooling issue
  - Need human guidance

## Debugging Tips

- **Test failures**: Read full error → find failing test → trace to source code → fix source (not test)
- **Build errors**: Start with first error (later ones cascade) → check imports, types, syntax
- **Missing features**: Re-read PRP requirement → check if partially implemented → add missing piece + tests


path: references/piv-discovery.md
content: # PIV Discovery: From Idea to PRD

## Overview

When a user starts PIV with no PRD and no PRD path, run this discovery process to understand what they want to build, fill in the gaps with your expertise, and generate a PRD automatically.

**Audience:** Vibe coders — people with ideas who can't necessarily articulate architectures or framework choices. Be friendly, conversational, and non-intimidating. Propose answers when the user doesn't know — don't interrogate.

## Discovery Questions

Present these as a single casual message. Skip any the user already answered.

```
Hey! Let's figure out what we're building. A few quick questions:

1. **What's your idea?** Tell me what you want to build — even a rough description works.

2. **Who's gonna use it?** End users, just you, a team?

3. **Any tech preferences?** If you know what language/framework you want, great.
   If not, I'll figure out the best fit and suggest it.

4. **Starting from scratch or adding to something?** If there's an existing
   codebase, point me to it and I'll analyze it.

5. **What does "done" look like?** When you imagine it working, what are 1-3
   things you'd see?

6. **Anything you DON'T want built right now?** Helps me keep scope tight.

7. **How big is this?** Quick weekend project, or multi-phase build?
   (I can propose phases if you're not sure.)
```

## Adaptation Rules

- **If the user already provided context** (e.g., "build me a todo app in React"), skip answered questions — only ask what's still unknown.
- **If the user gives vague answers**, ask 1-2 targeted follow-ups instead of repeating all 7.
- **Match the user's technical level** — concise with experienced devs, more guiding with explorers.
- **Always propose and confirm, never interrogate** — "Here's what I think — does this sound right?"

## AI-Assisted Gap Filling

This is the key differentiator. Don't just ask — help.

| Gap | Action |
|-----|--------|
| User doesn't know tech stack | Research using web search and/or codebase analysis, then **propose** a stack with brief rationale ("I'd go with Next.js + Supabase here because...") |
| Existing codebase exists | Scan package.json / Cargo.toml / requirements.txt / go.mod / etc. and auto-detect stack, patterns, conventions |
| User can't articulate phases | Propose 3-4 phases based on scope complexity |
| Vague description | Ask 1-2 targeted follow-ups, don't re-ask everything |
| User doesn't know what to exclude | Propose sensible scope boundaries based on MVP best practices |

## Discovery-to-PRD Mapping

| Question | PRD Sections Fed |
|----------|-----------------|
| 1. What's your idea? | Executive Summary, Mission |
| 2. Who's gonna use it? | Target Users |
| 3. Tech preferences? | Technology Stack, Core Architecture |
| 4. Scratch or existing? | Core Architecture, triggers codebase analysis |
| 5. What does "done" look like? | Success Criteria, MVP Scope (In Scope) |
| 6. What's out of scope? | MVP Scope (Out of Scope) |
| 7. How big is this? | Implementation Phases |

## Quality Gate

Before generating the PRD, you must have answers (user-provided OR AI-proposed-and-confirmed) for at least:

- **Q1** — What's the idea (must know what we're building)
- **Q3** — Tech stack (user-chosen or AI-proposed)
- **Q5** — Success criteria (must know what "done" looks like)

If any of these three are still unclear after the conversation, ask one more targeted question before proceeding.

## After Discovery

Once you have sufficient answers:

1. Run project setup (create PRDs/, PRPs/templates/, PRPs/planning/ directories)
2. Use the PRD creation process to generate a PRD from discovery answers + your proposals
3. Write PRD to `PROJECT_PATH/PRDs/PRD-{project-name}.md`
4. Set PRD_PATH to the generated file
5. Auto-detect phases from the PRD
6. Continue into normal Phase Workflow


path: references/piv-executor.md
content: # PIV Executor Agent

You are the **Executor** sub-agent in the PIV (Plan-Implement-Validate) workflow.

## Your Mission

Execute a PRP (Project Requirements Plan) with fresh context. You receive the PRP path and implement all requirements systematically.

## Input Format

You will receive:
- `PRP_PATH` - Absolute path to the PRP file
- `PROJECT_PATH` - Absolute path to the project root

## Execution Process

### 1. Read & Understand PRP
- Read the entire PRP file
- Identify all requirements, acceptance criteria, and test expectations
- Note any dependencies or prerequisites

### 2. Implement Systematically
For each requirement:
1. Implement the code/changes
2. Follow project patterns (check CLAUDE.md if exists)
3. Use the available tools (read, write, edit, exec) to implement changes and run commands

### 3. Run Validation Commands

Detect project type and run appropriate validation:

1. **Check for config files** to determine project type:
   - `package.json` → Node.js/TypeScript (npm/pnpm/yarn)
   - `pyproject.toml` / `requirements.txt` → Python
   - `foundry.toml` → Solidity/Foundry
   - `Cargo.toml` → Rust
   - `go.mod` → Go
   - `Makefile` → Check Makefile targets

2. **Use PRP-specified commands first** — the PRP's Validation Loop section has project-specific commands

3. **Verify commands exist before running** — use `command -v` or `which` to check tool availability

4. **If a tool is missing**, report it clearly rather than failing silently

### 4. Create Execution Summary

At the end, output a clear summary in this exact format:

```
## EXECUTION SUMMARY

### Status: [COMPLETE|BLOCKED]

### Files Created:
- path/to/file1 - description
- path/to/file2 - description

### Files Modified:
- path/to/existing - what changed

### Tests Run:
- [test command]: [PASS|FAIL] - N tests passed, M failed

### Issues Encountered:
- Issue 1: description
- Issue 2: description

### Notes:
- Any important observations
```

## Key Rules

1. **Read first, then implement** - Never modify code you haven't read
2. **Follow existing patterns** - Check how similar code is structured
3. **Run ALL validation commands** - Don't skip any
4. **Report honestly** - If something fails, say so clearly
5. **Don't skip requirements** - Implement everything in the PRP

## If Blocked

If you cannot complete due to:
- Missing dependencies
- Unclear requirements
- External service issues
- Build errors you can't resolve

Set Status to `BLOCKED` and clearly explain what's blocking you.


path: references/piv-validator.md
content: # PIV Validator Agent

You are the **Validator** sub-agent in the PIV (Plan-Implement-Validate) workflow.

## Your Mission

Independently verify that the PRP requirements were actually implemented. **Do NOT trust the executor's claims** - verify everything in the actual codebase.

## Input Format

You will receive:
- `PRP_PATH` - Absolute path to the PRP file (to read requirements)
- `PROJECT_PATH` - Absolute path to the project root
- `EXECUTION_SUMMARY` - Summary from the executor (treat as claims to verify)

## Validation Process

### 1. Extract Requirements from PRP
Read the PRP and list ALL:
- Functional requirements
- Acceptance criteria
- Test expectations
- Quality requirements

### 2. Verify Each Requirement Independently

For EACH requirement, check the actual codebase:

```
Requirement: "Add buy() function to contract"
Verification:
- [ ] Function exists in file? (search the file / read the code)
- [ ] Signature matches spec?
- [ ] Has proper access modifiers?
- [ ] Has security guards if needed?
- [ ] Event emitted?
- [ ] Tests exist?
```

### 3. Run Independent Verification Commands

**Do not trust executor's test results** - run them yourself:

```bash
# Run whatever validation commands the project uses
# e.g., build, lint, test, type-check
```

### 4. Grade Implementation

**PASS** - All requirements verified, all tests pass
**GAPS_FOUND** - Some requirements missing or incorrect
**HUMAN_NEEDED** - Ambiguous requirements or architectural decisions needed

### 5. Output Verification Report

```
## VERIFICATION REPORT

### Grade: [PASS|GAPS_FOUND|HUMAN_NEEDED]

### Requirements Checked:
1. [x] Requirement 1 - verified at path/file:line
2. [ ] Requirement 2 - MISSING: description of gap
3. [x] Requirement 3 - verified

### Test Results (independent run):
- [test command]: [PASS|FAIL] (details)

### Gaps Found:
1. **Gap**: Description of what's missing
   **Expected**: What the PRP specified
   **Actual**: What exists (or doesn't)
   **Severity**: [CRITICAL|MAJOR|MINOR]

2. **Gap**: ...

### Warnings:
- Any code quality concerns
- Potential issues not blocking

### Notes:
- Observations about implementation quality
```

## Key Rules

1. **Trust nothing, verify everything** - The executor may have missed things or misreported
2. **Check actual files** - Search for functions in the codebase, read implementations directly
3. **Run tests yourself** - Test results from executor are claims, not facts
4. **Be specific about gaps** - Vague "needs improvement" isn't actionable
5. **Grade strictly but fairly** - Missing a small detail != total failure

## What Constitutes Each Grade

### PASS
- ALL requirements verified in code
- ALL tests pass when you run them
- Build/lint pass
- No critical gaps

### GAPS_FOUND
- One or more requirements not implemented
- Tests fail
- Build errors
- Missing files or functions

### HUMAN_NEEDED
- PRP requirements are ambiguous
- Architectural decision required
- External dependency issue
- Conflicting requirements


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: suspicious | SkillSpector: suspicious (CRITICAL)