From dff2d358f66bc8691e5f22a037a2a395cb9c0876 Mon Sep 17 00:00:00 2001 From: Test User Date: Thu, 29 Jan 2026 13:51:10 -0700 Subject: [PATCH] docs: add user guide and example projects (#139) New users were confused about which files they write vs. which Ralph manages, and how PROMPT.md, specs/, and fix_plan.md relate to each other. Added: - docs/user-guide/ with quick start tutorial, file reference, and requirements writing guide - examples/simple-cli-tool/ showing minimal Ralph configuration - examples/rest-api/ demonstrating when to use specs/ - README section explaining Ralph files and their relationships Also documents specs/stdlib/ purpose for reusable patterns. --- README.md | 33 ++ docs/user-guide/01-quick-start.md | 190 +++++++++++ .../02-understanding-ralph-files.md | 245 +++++++++++++ docs/user-guide/03-writing-requirements.md | 323 ++++++++++++++++++ docs/user-guide/README.md | 37 ++ examples/.gitkeep | 2 - examples/rest-api/.ralph/PROMPT.md | 32 ++ examples/rest-api/.ralph/fix_plan.md | 33 ++ examples/rest-api/.ralph/specs/api.md | 246 +++++++++++++ examples/rest-api/README.md | 100 ++++++ examples/simple-cli-tool/.ralph/PROMPT.md | 57 ++++ examples/simple-cli-tool/.ralph/fix_plan.md | 22 ++ examples/simple-cli-tool/README.md | 68 ++++ 13 files changed, 1386 insertions(+), 2 deletions(-) create mode 100644 docs/user-guide/01-quick-start.md create mode 100644 docs/user-guide/02-understanding-ralph-files.md create mode 100644 docs/user-guide/03-writing-requirements.md create mode 100644 docs/user-guide/README.md delete mode 100644 examples/.gitkeep create mode 100644 examples/rest-api/.ralph/PROMPT.md create mode 100644 examples/rest-api/.ralph/fix_plan.md create mode 100644 examples/rest-api/.ralph/specs/api.md create mode 100644 examples/rest-api/README.md create mode 100644 examples/simple-cli-tool/.ralph/PROMPT.md create mode 100644 examples/simple-cli-tool/.ralph/fix_plan.md create mode 100644 examples/simple-cli-tool/README.md diff --git a/README.md b/README.md index 8374466..7e658ec 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,39 @@ To completely remove Ralph from your system: curl -sL https://raw.githubusercontent.com/frankbria/ralph-claude-code/main/uninstall.sh | bash ``` +## Understanding Ralph Files + +After running `ralph-enable` or `ralph-import`, you'll have a `.ralph/` directory with several files. Here's what each file does and whether you need to edit it: + +| File | Auto-Generated? | You Should... | +|------|-----------------|---------------| +| `.ralph/PROMPT.md` | Yes (smart defaults) | **Review & customize** project goals and principles | +| `.ralph/fix_plan.md` | Yes (can import tasks) | **Add/modify** specific implementation tasks | +| `.ralph/AGENT.md` | Yes (detects build commands) | Rarely edit (auto-maintained by Ralph) | +| `.ralph/specs/` | Empty directory | Add files when PROMPT.md isn't detailed enough | +| `.ralph/specs/stdlib/` | Empty directory | Add reusable patterns and conventions | +| `.ralphrc` | Yes (project-aware) | Rarely edit (sensible defaults) | + +### Key File Relationships + +``` +PROMPT.md (high-level goals) + ↓ +specs/ (detailed requirements when needed) + ↓ +fix_plan.md (specific tasks Ralph executes) + ↓ +AGENT.md (build/test commands - auto-maintained) +``` + +### When to Use specs/ + +- **Simple projects**: PROMPT.md + fix_plan.md is usually enough +- **Complex features**: Add specs/feature-name.md for detailed requirements +- **Team conventions**: Add specs/stdlib/convention-name.md for reusable patterns + +See the [User Guide](docs/user-guide/) for detailed explanations and the [examples/](examples/) directory for realistic project configurations. + ## How It Works Ralph operates on a simple but powerful cycle: diff --git a/docs/user-guide/01-quick-start.md b/docs/user-guide/01-quick-start.md new file mode 100644 index 0000000..54f7dec --- /dev/null +++ b/docs/user-guide/01-quick-start.md @@ -0,0 +1,190 @@ +# Quick Start: Your First Ralph Project + +This tutorial walks you through enabling Ralph on an existing project and running your first autonomous development loop. By the end, you'll have Ralph building a simple CLI todo app. + +## Prerequisites + +- Ralph installed globally (`./install.sh` from the ralph-claude-code repo) +- Claude Code CLI installed (`npm install -g @anthropic-ai/claude-code`) +- A project directory (we'll create one) + +## Step 1: Create Your Project + +Let's create a simple Node.js project: + +```bash +mkdir todo-cli +cd todo-cli +npm init -y +git init +``` + +## Step 2: Enable Ralph + +Run the interactive wizard: + +```bash +ralph-enable +``` + +The wizard will: +1. Detect your project type (Node.js/TypeScript) +2. Ask about task sources (you can skip for now) +3. Create the `.ralph/` directory with starter files + +You'll see output like: + +``` +Ralph Enable Wizard +================== + +Phase 1: Environment Detection +------------------------------ +Detected project type: javascript +Detected package manager: npm +Git repository: yes + +Phase 2: Task Source Selection +------------------------------ +No task sources selected. You can add tasks manually. + +Phase 3: Configuration +------------------------------ +Creating .ralph/ directory structure... + +Phase 4: File Generation +------------------------------ +Created: .ralph/PROMPT.md +Created: .ralph/fix_plan.md +Created: .ralph/AGENT.md +Created: .ralphrc + +Ralph is now enabled for this project. +``` + +## Step 3: Customize Your Requirements + +After `ralph-enable`, you have starter files that need customization. Open `.ralph/PROMPT.md` and replace the placeholder content: + +```markdown +# Ralph Development Instructions + +## Context +You are Ralph, an autonomous AI development agent building a CLI todo application in Node.js. + +## Current Objectives +1. Create a command-line todo app with add, list, complete, and delete commands +2. Store todos in a JSON file (~/.todos.json) +3. Use commander.js for argument parsing +4. Include helpful --help output +5. Write unit tests with Jest + +## Key Principles +- Keep the code simple and readable +- Use async/await for file operations +- Provide clear error messages +- Follow Node.js best practices +``` + +## Step 4: Define Your Tasks + +Edit `.ralph/fix_plan.md` to list specific tasks: + +```markdown +# Fix Plan - Todo CLI + +## Priority 1: Core Structure +- [ ] Set up package.json with dependencies (commander, jest) +- [ ] Create src/index.js entry point with commander setup +- [ ] Create src/storage.js for JSON file operations + +## Priority 2: Commands +- [ ] Implement `todo add "task description"` command +- [ ] Implement `todo list` command with status indicators +- [ ] Implement `todo complete ` command +- [ ] Implement `todo delete ` command + +## Priority 3: Polish +- [ ] Add --help documentation for all commands +- [ ] Handle edge cases (empty list, invalid IDs) +- [ ] Write unit tests for storage module +``` + +## Step 5: Start Ralph + +Now let Ralph build your project: + +```bash +ralph --monitor +``` + +This opens a tmux session with: +- **Left pane**: Ralph loop output (what Claude is doing) +- **Right pane**: Live monitoring dashboard + +### What You'll See + +Ralph will: +1. Read your PROMPT.md and fix_plan.md +2. Start implementing tasks in priority order +3. Create files, run tests, update fix_plan.md +4. Continue until all tasks are complete + +### Monitoring Tips + +- **Ctrl+B, then D** - Detach from tmux (Ralph keeps running) +- **tmux attach -t todo-cli** - Reattach to watch progress +- **ralph --status** - Check current loop status + +## Step 6: Review the Results + +When Ralph finishes (or you want to check progress), look at: + +```bash +# See what files were created +ls -la src/ + +# Check the updated fix_plan.md +cat .ralph/fix_plan.md + +# Run the tests Ralph wrote +npm test + +# Try your new CLI +node src/index.js add "Buy groceries" +node src/index.js list +``` + +## What Just Happened? + +Ralph followed this cycle: +1. **Read** - Loaded PROMPT.md for context and fix_plan.md for tasks +2. **Implement** - Wrote code for the highest priority unchecked task +3. **Test** - Ran any tests and fixed failures +4. **Update** - Marked completed tasks in fix_plan.md +5. **Repeat** - Continued until EXIT_SIGNAL was set + +## Next Steps + +- Read [Understanding Ralph Files](02-understanding-ralph-files.md) to learn what each file does +- Check [Writing Effective Requirements](03-writing-requirements.md) for best practices +- Explore the [examples/](../../examples/) directory for more complex projects + +## Common Questions + +### Ralph stopped early - why? + +Check `.ralph/logs/` for the latest log. Common reasons: +- Rate limit reached (waits for reset) +- Circuit breaker opened (detected stuck loop) +- All tasks marked complete + +### Ralph keeps running tests without implementing anything + +Your fix_plan.md might be too vague. Make tasks specific and actionable: +- Bad: "Improve the code" +- Good: "Add error handling for missing ~/.todos.json file" + +### How do I add more features later? + +Just add new tasks to `.ralph/fix_plan.md` and run `ralph --monitor` again. Ralph will pick up where it left off. diff --git a/docs/user-guide/02-understanding-ralph-files.md b/docs/user-guide/02-understanding-ralph-files.md new file mode 100644 index 0000000..3e637d1 --- /dev/null +++ b/docs/user-guide/02-understanding-ralph-files.md @@ -0,0 +1,245 @@ +# Understanding Ralph Files + +After running `ralph-enable`, `ralph-import`, or `ralph-setup`, you'll have a `.ralph/` directory with several files. This guide explains what each file does and whether you need to edit it. + +## File Reference Table + +| File | Auto-Generated? | Who Writes It | Who Reads It | You Should... | +|------|-----------------|---------------|--------------|---------------| +| `.ralph/PROMPT.md` | Yes (with smart defaults) | **You** customize it | Ralph reads every loop | Review and customize project goals | +| `.ralph/fix_plan.md` | Yes (can import tasks) | **You** + Ralph updates | Ralph reads and updates | Add/modify specific tasks | +| `.ralph/AGENT.md` | Yes (detects build commands) | Ralph maintains | Ralph reads for build/test | Rarely edit (auto-maintained) | +| `.ralph/specs/` | Empty directory created | **You** add files when needed | Ralph reads for context | Add when PROMPT.md isn't detailed enough | +| `.ralph/specs/stdlib/` | Empty directory created | **You** add reusable patterns | Ralph reads for conventions | Add shared patterns and conventions | +| `.ralphrc` | Yes (project-aware) | Usually leave as-is | Ralph reads at startup | Rarely edit (sensible defaults) | +| `.ralph/logs/` | Created automatically | Ralph writes logs | You review for debugging | Don't edit (read-only) | +| `.ralph/status.json` | Created at runtime | Ralph updates | Monitoring tools | Don't edit (read-only) | + +## The Core Files + +### PROMPT.md - Your Project Vision + +**Purpose**: High-level instructions that Ralph reads at the start of every loop. + +**What to include**: +- Project description and goals +- Key principles or constraints +- Technology stack and frameworks +- Quality standards + +**What NOT to include**: +- Step-by-step implementation tasks (use fix_plan.md) +- Detailed API specifications (use specs/) +- Build commands (use AGENT.md) + +**Example**: +```markdown +## Context +You are Ralph, building a REST API for a bookstore inventory system. + +## Key Principles +- Use FastAPI with async database operations +- Follow REST conventions strictly +- Every endpoint needs tests +- Document all API endpoints with OpenAPI +``` + +### fix_plan.md - Your Task List + +**Purpose**: Prioritized checklist of tasks Ralph works through. + +**Key characteristics**: +- Ralph checks off `[x]` items as it completes them +- Ralph may add new tasks it discovers +- You can add, reorder, or remove tasks anytime +- More specific tasks = better results + +**Good task structure**: +```markdown +## Priority 1: Foundation +- [ ] Create database models for Book and Author +- [ ] Set up SQLAlchemy with async support +- [ ] Create Alembic migration for initial schema + +## Priority 2: API Endpoints +- [ ] POST /books - create a new book +- [ ] GET /books - list all books with pagination +- [ ] GET /books/{id} - get single book with author details +``` + +**Bad task structure**: +```markdown +- [ ] Make the API work +- [ ] Add features +- [ ] Fix bugs +``` + +### specs/ - Detailed Specifications + +**Purpose**: When PROMPT.md isn't enough detail for a feature. + +**When to use specs/**: +- Complex features needing detailed requirements +- API contracts that must be followed exactly +- Data models with specific validation rules +- External system integrations + +**When NOT to use specs/**: +- Simple CRUD operations +- Features already well-explained in PROMPT.md +- General coding standards (put in PROMPT.md) + +**Example structure**: +``` +.ralph/specs/ +├── api-contracts.md # OpenAPI-style endpoint definitions +├── data-models.md # Entity relationships and validations +└── third-party-auth.md # OAuth integration requirements +``` + +### specs/stdlib/ - Standard Library Patterns + +**Purpose**: Reusable patterns and conventions for your project. + +**What belongs here**: +- Error handling patterns +- Logging conventions +- Common utility functions specifications +- Testing patterns +- Code style decisions + +**Example**: +```markdown +# Error Handling Standard + +All API errors must return: +{ + "error": { + "code": "BOOK_NOT_FOUND", + "message": "No book with ID 123 exists", + "details": {} + } +} + +Use HTTPException with these codes: +- 400: Validation errors +- 404: Resource not found +- 409: Conflict (duplicate) +- 500: Internal errors (log full trace) +``` + +### AGENT.md - Build Instructions + +**Purpose**: How to build, test, and run the project. + +**Who maintains it**: Primarily Ralph, as it discovers build commands. + +**When you might edit**: +- Setting initial build commands for a complex project +- Adding environment setup steps +- Documenting deployment commands + +### .ralphrc - Project Configuration + +**Purpose**: Project-specific Ralph settings. + +**Default contents** (usually fine as-is): +```bash +PROJECT_NAME="my-project" +PROJECT_TYPE="typescript" +MAX_CALLS_PER_HOUR=100 +ALLOWED_TOOLS="Write,Read,Edit,Bash(git *),Bash(npm *),Bash(pytest)" +``` + +**When to edit**: +- Restricting tool permissions for security +- Adjusting rate limits +- Changing session timeout + +## File Relationships + +``` +┌─────────────────────────────────────────────────────────────┐ +│ PROMPT.md │ +│ (High-level goals and principles) │ +│ │ │ +│ ▼ │ +│ ┌─────────────────────────────────────────────────────┐ │ +│ │ specs/ │ │ +│ │ (Detailed requirements when needed) │ │ +│ │ │ │ +│ │ specs/api.md ──────▶ Informs fix_plan.md tasks │ │ +│ │ specs/stdlib/ ─────▶ Conventions Ralph follows │ │ +│ └─────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────────────────────────────────────────┐ │ +│ │ fix_plan.md │ │ +│ │ (Concrete tasks Ralph executes) │ │ +│ │ │ │ +│ │ [ ] Task 1 ◄────── Ralph checks off when done │ │ +│ │ [x] Task 2 │ │ +│ │ [ ] Task 3 ◄────── Ralph adds discovered tasks │ │ +│ └─────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────────────────────────────────────────┐ │ +│ │ AGENT.md │ │ +│ │ (How to build/test - auto-maintained) │ │ +│ └─────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────┘ +``` + +## Common Scenarios + +### Scenario 1: Simple feature addition + +Just edit fix_plan.md: +```markdown +- [ ] Add a /health endpoint that returns {"status": "ok"} +``` + +### Scenario 2: Complex feature with specific requirements + +Add a spec file first, then tasks: + +1. Create `.ralph/specs/search-feature.md`: +```markdown +# Search Feature Specification + +## Requirements +- Full-text search on book titles and descriptions +- Must support: + - Exact phrase matching: "lord of the rings" + - Boolean operators: fantasy AND epic + - Fuzzy matching for typos +``` + +2. Then add to fix_plan.md: +```markdown +- [ ] Implement search per specs/search-feature.md +``` + +### Scenario 3: Establishing team conventions + +Add to specs/stdlib/: +```markdown +# Logging Conventions + +All service methods must log: +- Entry with parameters (DEBUG level) +- Exit with result summary (DEBUG level) +- Errors with full context (ERROR level) +``` + +## Tips for Success + +1. **Start simple** - Begin with just PROMPT.md and fix_plan.md. Add specs/ only when needed. + +2. **Be specific** - Vague requirements produce vague results. "Add user auth" is worse than "Add JWT authentication with /login and /logout endpoints". + +3. **Let fix_plan.md evolve** - Ralph will add tasks it discovers. Review periodically and reprioritize. + +4. **Don't over-specify** - If Claude can figure it out from context, you don't need to specify it. + +5. **Review logs** - When something goes wrong, `.ralph/logs/` tells you what Ralph was thinking. diff --git a/docs/user-guide/03-writing-requirements.md b/docs/user-guide/03-writing-requirements.md new file mode 100644 index 0000000..5f9496b --- /dev/null +++ b/docs/user-guide/03-writing-requirements.md @@ -0,0 +1,323 @@ +# Writing Effective Requirements + +Ralph works best when it understands what you want. This guide shows you how to write clear requirements in PROMPT.md, when to use specs/, and how fix_plan.md evolves during development. + +## PROMPT.md: Good vs Bad Examples + +### Bad Example + +```markdown +# Project + +Make a good API for managing stuff. Use best practices. +Should be fast and work well. +``` + +**Problems**: +- What "stuff"? Too vague. +- What are "best practices"? Claude will guess. +- "Fast" and "work well" aren't measurable. + +### Good Example + +```markdown +# Ralph Development Instructions + +## Context +You are Ralph, building a REST API for a pet adoption shelter. +The API manages animals, adopters, and adoption records. + +## Technology Stack +- Python 3.11+ with FastAPI +- PostgreSQL with SQLAlchemy (async) +- pytest for testing +- Pydantic for validation + +## Key Principles +- RESTful endpoints following standard conventions +- All endpoints require authentication except GET /animals +- Soft delete for all entities (is_deleted flag, not actual deletion) +- Pagination on all list endpoints (default 20, max 100) + +## Data Entities +- Animal: name, species, breed, age, status (available/adopted/pending) +- Adopter: name, email, phone, approved (boolean) +- Adoption: animal_id, adopter_id, date, status + +## Quality Standards +- Every endpoint needs at least one happy-path test +- Input validation with clear error messages +- OpenAPI documentation for all endpoints +``` + +**Why this works**: +- Clear domain (pet adoption shelter) +- Specific technology choices +- Measurable constraints (pagination limits) +- Concrete data model +- Defined quality bar + +## fix_plan.md: Task Writing + +### The Goldilocks Principle + +Tasks should be **not too big, not too small**. + +**Too big** (Ralph doesn't know where to start): +```markdown +- [ ] Build the entire authentication system +``` + +**Too small** (wastes loop iterations): +```markdown +- [ ] Create the auth folder +- [ ] Create the auth/__init__.py file +- [ ] Create the auth/routes.py file +``` + +**Just right** (one loop of meaningful work): +```markdown +- [ ] Create auth routes with POST /login and POST /logout endpoints +- [ ] Add JWT token generation and validation middleware +- [ ] Create refresh token endpoint POST /auth/refresh +``` + +### Task Structure Template + +```markdown +# Fix Plan - [Project Name] + +## Priority 1: [Foundation/Critical Path] +- [ ] [Specific, actionable task] +- [ ] [Another specific task] + +## Priority 2: [Core Features] +- [ ] [Feature task] +- [ ] [Feature task] + +## Priority 3: [Polish/Nice-to-have] +- [ ] [Enhancement] +- [ ] [Documentation] + +## Discovered + +``` + +### How fix_plan.md Evolves + +**Initial state** (you write this): +```markdown +## Priority 1: Database +- [ ] Set up database models for Animal, Adopter, Adoption + +## Priority 2: API +- [ ] Create CRUD endpoints for animals +``` + +**After Loop 1** (Ralph updates): +```markdown +## Priority 1: Database +- [x] Set up database models for Animal, Adopter, Adoption + +## Priority 2: API +- [ ] Create CRUD endpoints for animals + +## Discovered +- [ ] Add database migration with Alembic +- [ ] Create pytest fixtures for test database +``` + +**After Loop 3**: +```markdown +## Priority 1: Database +- [x] Set up database models for Animal, Adopter, Adoption + +## Priority 2: API +- [x] Create CRUD endpoints for animals +- [ ] Create CRUD endpoints for adopters + +## Discovered +- [x] Add database migration with Alembic +- [x] Create pytest fixtures for test database +- [ ] Add pagination to GET /animals endpoint +``` + +Ralph adds tasks it discovers and checks them off as it works. You can: +- Reorder tasks by moving them to different priority sections +- Delete tasks that are no longer relevant +- Add new tasks anytime + +## When to Use specs/ + +### Use specs/ for complex features + +**PROMPT.md says**: +```markdown +Add a matching algorithm that suggests animals to adopters. +``` + +**This is too vague.** Create `.ralph/specs/matching-algorithm.md`: +```markdown +# Animal Matching Algorithm + +## Inputs +- Adopter preferences: species, max_age, size_preference +- Available animals list + +## Algorithm +1. Filter by species (required match) +2. Score by age preference (0-100 points) + - Within range: 100 points + - Within 2 years: 50 points + - Outside: 0 points +3. Score by size preference (0-50 points) +4. Return top 5 by total score + +## Output Format +```json +[ + {"animal_id": 1, "score": 145, "reasons": ["species match", "age within preference"]}, + {"animal_id": 3, "score": 120, "reasons": ["species match"]} +] +``` + +## Edge Cases +- No matches: return empty array +- Tie scores: sort by animal.created_at (oldest first) +``` + +**Then in fix_plan.md**: +```markdown +- [ ] Implement matching algorithm per specs/matching-algorithm.md +``` + +### Use specs/stdlib/ for conventions + +When you want consistency across the project, document it: + +`.ralph/specs/stdlib/error-responses.md`: +```markdown +# Error Response Standard + +All API errors return this structure: + +```json +{ + "error": { + "code": "ANIMAL_NOT_FOUND", + "message": "No animal with ID 42 exists", + "field": null, + "details": {} + } +} +``` + +## Error Codes +| Code | HTTP Status | When | +|------|-------------|------| +| VALIDATION_ERROR | 400 | Invalid input | +| NOT_FOUND | 404 | Resource doesn't exist | +| ALREADY_ADOPTED | 409 | Animal not available | +| UNAUTHORIZED | 401 | Missing/invalid token | +``` + +### Don't use specs/ for everything + +**Overkill** - You don't need specs/ for: +```markdown +# User Password Requirements + +Passwords must be at least 8 characters. +``` + +**Just put it in PROMPT.md**: +```markdown +## Authentication +- Passwords: minimum 8 characters, at least one number +- JWT tokens expire after 1 hour +``` + +## Common Mistakes + +### Mistake 1: Assuming Claude knows your preferences + +**Bad**: +```markdown +Use standard authentication. +``` + +**Good**: +```markdown +Use JWT authentication with 1-hour token expiry. +Refresh tokens last 7 days and rotate on use. +``` + +### Mistake 2: Mixing implementation with requirements + +**Bad** (in PROMPT.md): +```markdown +Create a file called auth.py and add these imports: +import jwt +from datetime import datetime +``` + +**Good** (in PROMPT.md): +```markdown +Use JWT for authentication. Tokens should expire after 1 hour. +``` + +Let Ralph figure out the implementation details. + +### Mistake 3: Over-specifying tests + +**Bad**: +```markdown +- [ ] Write test_create_animal_success +- [ ] Write test_create_animal_invalid_species +- [ ] Write test_create_animal_missing_name +- [ ] Write test_create_animal_negative_age +``` + +**Good**: +```markdown +- [ ] Write tests for animal creation (success and validation errors) +``` + +Ralph knows how to write tests. Tell it what to test, not how. + +### Mistake 4: Forgetting the "why" + +**Bad**: +```markdown +Add a 100ms delay to all API responses. +``` + +**Good**: +```markdown +Add a 100ms delay to all API responses (required for rate limiting compliance with external payment API). +``` + +When Ralph understands *why*, it makes better decisions. + +## Checklist: Before Running Ralph + +Before `ralph --monitor`, verify: + +- [ ] **PROMPT.md has clear context** - Does Ralph know what it's building? +- [ ] **Technology stack is specified** - Did you pick the frameworks? +- [ ] **Key constraints are documented** - Auth approach? API conventions? +- [ ] **fix_plan.md has specific tasks** - Can Ralph start on task 1 immediately? +- [ ] **Complex features have specs/** - Is anything too vague for PROMPT.md? + +If you can answer "yes" to these, Ralph will do good work. + +## Quick Reference + +| Need to... | Put it in... | +|------------|--------------| +| Set project vision and principles | PROMPT.md | +| Define technology stack | PROMPT.md | +| List specific implementation tasks | fix_plan.md | +| Document complex feature requirements | specs/feature-name.md | +| Establish coding conventions | specs/stdlib/convention-name.md | +| Configure Ralph behavior | .ralphrc | diff --git a/docs/user-guide/README.md b/docs/user-guide/README.md new file mode 100644 index 0000000..86354e9 --- /dev/null +++ b/docs/user-guide/README.md @@ -0,0 +1,37 @@ +# Ralph User Guide + +This guide helps you get started with Ralph and understand how to configure it effectively for your projects. + +## Guides + +### [Quick Start: Your First Ralph Project](01-quick-start.md) +A hands-on tutorial that walks you through enabling Ralph on an existing project and running your first autonomous development loop. You'll build a simple CLI todo app from scratch. + +### [Understanding Ralph Files](02-understanding-ralph-files.md) +Learn which files Ralph creates, which ones you should customize, and how they work together. Includes a complete reference table and explanations of file relationships. + +### [Writing Effective Requirements](03-writing-requirements.md) +Best practices for writing PROMPT.md, when to use specs/, and how fix_plan.md evolves during development. Includes good and bad examples. + +## Example Projects + +Check out the [examples/](../../examples/) directory for complete, realistic project configurations: + +- **[simple-cli-tool](../../examples/simple-cli-tool/)** - Minimal example showing core Ralph files +- **[rest-api](../../examples/rest-api/)** - Medium complexity with specs/ directory usage + +## Quick Reference + +| I want to... | Do this | +|-------------|---------| +| Enable Ralph on an existing project | `ralph-enable` | +| Import a PRD/requirements doc | `ralph-import requirements.md project-name` | +| Create a new project from scratch | `ralph-setup my-project` | +| Start Ralph with monitoring | `ralph --monitor` | +| Check what Ralph is doing | `ralph --status` | + +## Need Help? + +- **[Main README](../../README.md)** - Full documentation and configuration options +- **[CONTRIBUTING.md](../../CONTRIBUTING.md)** - How to contribute to Ralph +- **[GitHub Issues](https://github.com/frankbria/ralph-claude-code/issues)** - Report bugs or request features diff --git a/examples/.gitkeep b/examples/.gitkeep deleted file mode 100644 index ddb08c6..0000000 --- a/examples/.gitkeep +++ /dev/null @@ -1,2 +0,0 @@ -# This file ensures the examples/ directory is tracked by git -# Remove this file when you add actual example files \ No newline at end of file diff --git a/examples/rest-api/.ralph/PROMPT.md b/examples/rest-api/.ralph/PROMPT.md new file mode 100644 index 0000000..65def79 --- /dev/null +++ b/examples/rest-api/.ralph/PROMPT.md @@ -0,0 +1,32 @@ +# Ralph Development Instructions + +## Context +You are Ralph, building a REST API for a bookstore inventory management system. The API allows staff to manage books, authors, and inventory levels. + +## Technology Stack +- Python 3.11+ with FastAPI +- PostgreSQL with SQLAlchemy (async) +- Pydantic for request/response validation +- pytest with pytest-asyncio for testing +- JWT authentication + +## Key Principles +- Follow REST conventions strictly (proper HTTP methods, status codes) +- All endpoints except GET require authentication +- Use async/await throughout for database operations +- Every endpoint should have at least one test +- Return consistent error responses (see specs/api.md) + +## Data Entities +- **Book**: title, isbn, author_id, price, quantity_in_stock +- **Author**: name, bio, born_date + +## Quality Standards +- OpenAPI documentation auto-generated +- Input validation with descriptive error messages +- Database transactions for multi-step operations +- Pagination on list endpoints + +## Files to Reference +- See specs/api.md for detailed endpoint specifications +- Follow fix_plan.md for task priorities diff --git a/examples/rest-api/.ralph/fix_plan.md b/examples/rest-api/.ralph/fix_plan.md new file mode 100644 index 0000000..e3dc53c --- /dev/null +++ b/examples/rest-api/.ralph/fix_plan.md @@ -0,0 +1,33 @@ +# Fix Plan - Bookstore API + +## Priority 1: Foundation +- [ ] Set up FastAPI application structure with proper folder organization +- [ ] Configure SQLAlchemy with async PostgreSQL connection +- [ ] Create database models for Book and Author entities +- [ ] Set up Alembic for database migrations + +## Priority 2: Author Endpoints +- [ ] Implement author CRUD endpoints per specs/api.md +- [ ] Write tests for author endpoints +- [ ] Add pagination to GET /authors + +## Priority 3: Book Endpoints +- [ ] Implement book CRUD endpoints per specs/api.md +- [ ] Add author relationship and nested response format +- [ ] Write tests for book endpoints +- [ ] Add filtering (by author, price range, in_stock) + +## Priority 4: Authentication +- [ ] Add JWT authentication middleware +- [ ] Create POST /auth/login endpoint +- [ ] Protect write endpoints (POST, PUT, DELETE) +- [ ] Write authentication tests + +## Priority 5: Polish +- [ ] Add OpenAPI documentation customization +- [ ] Implement inventory adjustment endpoint +- [ ] Add search functionality (title, author name) +- [ ] Performance optimization (eager loading for relationships) + +## Discovered + diff --git a/examples/rest-api/.ralph/specs/api.md b/examples/rest-api/.ralph/specs/api.md new file mode 100644 index 0000000..9fbce4a --- /dev/null +++ b/examples/rest-api/.ralph/specs/api.md @@ -0,0 +1,246 @@ +# API Specification + +## Base URL +All endpoints are prefixed with `/api/v1` + +## Authentication +- POST, PUT, DELETE endpoints require JWT in Authorization header +- Format: `Authorization: Bearer ` +- GET endpoints are public + +## Standard Response Format + +### Success (single item) +```json +{ + "data": { ... }, + "meta": { + "timestamp": "2024-01-15T10:30:00Z" + } +} +``` + +### Success (list) +```json +{ + "data": [ ... ], + "meta": { + "total": 100, + "page": 1, + "per_page": 20, + "total_pages": 5 + } +} +``` + +### Error +```json +{ + "error": { + "code": "VALIDATION_ERROR", + "message": "Invalid input", + "details": { + "field": "isbn", + "issue": "ISBN must be 13 characters" + } + } +} +``` + +## Error Codes +| Code | HTTP Status | Description | +|------|-------------|-------------| +| VALIDATION_ERROR | 400 | Invalid input data | +| UNAUTHORIZED | 401 | Missing or invalid token | +| NOT_FOUND | 404 | Resource doesn't exist | +| CONFLICT | 409 | Duplicate ISBN or constraint violation | +| INTERNAL_ERROR | 500 | Unexpected server error | + +--- + +## Author Endpoints + +### GET /authors +List all authors with pagination. + +**Query Parameters:** +- `page` (int, default: 1) +- `per_page` (int, default: 20, max: 100) + +**Response:** 200 OK +```json +{ + "data": [ + { + "id": 1, + "name": "Jane Austen", + "bio": "English novelist...", + "born_date": "1775-12-16", + "book_count": 6 + } + ], + "meta": { "total": 50, "page": 1, "per_page": 20, "total_pages": 3 } +} +``` + +### GET /authors/{id} +Get single author with their books. + +**Response:** 200 OK +```json +{ + "data": { + "id": 1, + "name": "Jane Austen", + "bio": "English novelist...", + "born_date": "1775-12-16", + "books": [ + { "id": 1, "title": "Pride and Prejudice", "isbn": "9780141439518" } + ] + } +} +``` + +### POST /authors +Create new author. Requires authentication. + +**Request Body:** +```json +{ + "name": "Jane Austen", + "bio": "English novelist known for...", + "born_date": "1775-12-16" +} +``` + +**Validation:** +- `name`: required, 1-200 characters +- `bio`: optional, max 2000 characters +- `born_date`: optional, ISO date format + +**Response:** 201 Created + +### PUT /authors/{id} +Update author. Requires authentication. + +**Response:** 200 OK + +### DELETE /authors/{id} +Delete author. Requires authentication. +Fails if author has books (CONFLICT error). + +**Response:** 204 No Content + +--- + +## Book Endpoints + +### GET /books +List all books with pagination and filtering. + +**Query Parameters:** +- `page`, `per_page` - pagination +- `author_id` (int) - filter by author +- `min_price`, `max_price` (decimal) - price range +- `in_stock` (bool) - only books with quantity > 0 + +**Response:** 200 OK +```json +{ + "data": [ + { + "id": 1, + "title": "Pride and Prejudice", + "isbn": "9780141439518", + "price": 12.99, + "quantity_in_stock": 25, + "author": { + "id": 1, + "name": "Jane Austen" + } + } + ], + "meta": { ... } +} +``` + +### GET /books/{id} +Get single book with full author details. + +### POST /books +Create new book. Requires authentication. + +**Request Body:** +```json +{ + "title": "Pride and Prejudice", + "isbn": "9780141439518", + "author_id": 1, + "price": 12.99, + "quantity_in_stock": 25 +} +``` + +**Validation:** +- `title`: required, 1-500 characters +- `isbn`: required, exactly 13 characters, unique +- `author_id`: required, must exist +- `price`: required, positive decimal, max 2 decimal places +- `quantity_in_stock`: required, non-negative integer + +**Response:** 201 Created + +### PUT /books/{id} +Update book. Requires authentication. + +### DELETE /books/{id} +Delete book. Requires authentication. + +**Response:** 204 No Content + +### PATCH /books/{id}/inventory +Adjust inventory level. Requires authentication. + +**Request Body:** +```json +{ + "adjustment": -5, + "reason": "Sold at event" +} +``` + +**Validation:** +- `adjustment`: required, integer (positive or negative) +- `reason`: required, 1-200 characters +- Final quantity cannot be negative (400 error) + +**Response:** 200 OK with updated book + +--- + +## Authentication Endpoints + +### POST /auth/login +Authenticate and receive JWT. + +**Request Body:** +```json +{ + "username": "admin", + "password": "secret" +} +``` + +**Response:** 200 OK +```json +{ + "data": { + "access_token": "eyJ...", + "token_type": "bearer", + "expires_in": 3600 + } +} +``` + +**Errors:** +- 401 UNAUTHORIZED: Invalid credentials diff --git a/examples/rest-api/README.md b/examples/rest-api/README.md new file mode 100644 index 0000000..b2986e2 --- /dev/null +++ b/examples/rest-api/README.md @@ -0,0 +1,100 @@ +# Example: REST API with Specifications + +This example shows a medium-complexity Ralph configuration for a bookstore REST API. It demonstrates when and how to use the specs/ directory. + +## What This Example Demonstrates + +- **Focused PROMPT.md** - High-level goals and principles +- **Detailed specs/api.md** - Endpoint specifications that are too detailed for PROMPT.md +- **Structured fix_plan.md** - Tasks organized by feature area + +## Project Structure + +``` +rest-api/ +├── .ralph/ +│ ├── PROMPT.md # Project vision and principles +│ ├── fix_plan.md # Implementation tasks +│ └── specs/ +│ └── api.md # Detailed API specifications +├── .ralphrc # Configuration (auto-generated) +└── README.md # This file +``` + +## Why This Example Uses specs/ + +The PROMPT.md keeps things high-level: +- What the API is for (bookstore inventory) +- Technology stack (FastAPI, PostgreSQL) +- Key principles (REST conventions, authentication) + +But the API needs detailed specifications that would clutter PROMPT.md: +- Exact request/response formats +- Validation rules +- Error codes +- Pagination behavior + +That's what `specs/api.md` is for. + +## How to Use This Example + +1. Copy this directory to a new location: + ```bash + cp -r examples/rest-api ~/my-bookstore-api + cd ~/my-bookstore-api + ``` + +2. Initialize git and Python environment: + ```bash + git init + python -m venv venv + source venv/bin/activate + pip install fastapi uvicorn sqlalchemy pytest + ``` + +3. Run Ralph: + ```bash + ralph --monitor + ``` + +## Key Points + +### PROMPT.md Sets Direction + +PROMPT.md answers "what are we building and how?" without getting into implementation details. + +### specs/api.md Provides Details + +When you need to specify: +- Exact endpoint paths and methods +- Request/response schemas +- Business rules and constraints +- Error handling behavior + +These details help Ralph implement correctly on the first try. + +### fix_plan.md References specs/ + +Notice how tasks reference the specification: +```markdown +- [ ] Implement book endpoints per specs/api.md +``` + +This tells Ralph where to find the detailed requirements. + +## When to Add More Specs + +Consider adding additional spec files for: +- **specs/database.md** - Schema details, relationships, indexes +- **specs/auth.md** - Token formats, permission rules, session handling +- **specs/stdlib/errors.md** - Standard error response format +- **specs/stdlib/pagination.md** - Pagination conventions + +## Comparison with Simple Example + +| Aspect | Simple CLI | REST API | +|--------|-----------|----------| +| Complexity | Low | Medium | +| Uses specs/ | No | Yes | +| PROMPT.md length | ~40 lines | ~30 lines | +| Why | Self-contained | API contracts need detail | diff --git a/examples/simple-cli-tool/.ralph/PROMPT.md b/examples/simple-cli-tool/.ralph/PROMPT.md new file mode 100644 index 0000000..4d7d982 --- /dev/null +++ b/examples/simple-cli-tool/.ralph/PROMPT.md @@ -0,0 +1,57 @@ +# Ralph Development Instructions + +## Context +You are Ralph, building a command-line todo application in Node.js. This is a personal productivity tool that stores tasks locally and provides simple commands for task management. + +## Current Objectives +1. Create a CLI that supports add, list, complete, and delete commands +2. Store todos in ~/.todos.json with automatic file creation +3. Provide clear, helpful output for all operations +4. Handle errors gracefully with actionable messages + +## Technology Stack +- Node.js 18+ +- commander.js for CLI argument parsing +- Native fs/promises for file operations +- Jest for testing + +## Key Principles +- Single responsibility: each command does one thing well +- Fail gracefully: missing file = empty list, not an error +- Clear output: users should always know what happened +- Testable: core logic separated from CLI layer + +## Command Specifications + +### `todo add "task description"` +- Adds a new task with auto-incrementing ID +- Outputs: "Added task #3: Buy groceries" + +### `todo list` +- Shows all tasks with status indicators +- [ ] for pending, [x] for completed +- Outputs: "No tasks yet" if empty + +### `todo complete ` +- Marks task as done +- Errors if ID doesn't exist + +### `todo delete ` +- Removes task permanently +- Errors if ID doesn't exist + +## Data Format +```json +{ + "nextId": 4, + "tasks": [ + {"id": 1, "text": "Buy groceries", "completed": false}, + {"id": 2, "text": "Call mom", "completed": true} + ] +} +``` + +## Quality Standards +- All commands have --help documentation +- Unit tests for storage module +- Integration tests for CLI commands diff --git a/examples/simple-cli-tool/.ralph/fix_plan.md b/examples/simple-cli-tool/.ralph/fix_plan.md new file mode 100644 index 0000000..5adbe44 --- /dev/null +++ b/examples/simple-cli-tool/.ralph/fix_plan.md @@ -0,0 +1,22 @@ +# Fix Plan - Todo CLI + +## Priority 1: Foundation +- [ ] Set up package.json with commander and jest dependencies +- [ ] Create src/storage.js with load/save functions for ~/.todos.json +- [ ] Create src/index.js entry point with commander setup + +## Priority 2: Core Commands +- [ ] Implement `todo add "description"` command +- [ ] Implement `todo list` command with status indicators +- [ ] Implement `todo complete ` command +- [ ] Implement `todo delete ` command + +## Priority 3: Polish +- [ ] Add comprehensive --help text for each command +- [ ] Handle edge cases (empty list, invalid ID, negative ID) +- [ ] Write unit tests for storage.js module +- [ ] Write integration tests for CLI commands +- [ ] Add a `todo clear` command to remove all completed tasks + +## Discovered + diff --git a/examples/simple-cli-tool/README.md b/examples/simple-cli-tool/README.md new file mode 100644 index 0000000..add2eba --- /dev/null +++ b/examples/simple-cli-tool/README.md @@ -0,0 +1,68 @@ +# Example: Simple CLI Tool + +This example shows a minimal Ralph configuration for a command-line todo application built with Node.js. + +## What This Example Demonstrates + +- **Minimal PROMPT.md** - Just enough context for a focused project +- **Specific fix_plan.md** - Concrete, actionable tasks +- **No specs/ needed** - Simple enough that PROMPT.md covers everything + +## Project Structure + +``` +simple-cli-tool/ +├── .ralph/ +│ ├── PROMPT.md # Project goals and principles +│ └── fix_plan.md # Task list +├── .ralphrc # Configuration (auto-generated) +└── README.md # This file +``` + +## How to Use This Example + +1. Copy this directory to a new location: + ```bash + cp -r examples/simple-cli-tool ~/my-todo-app + cd ~/my-todo-app + ``` + +2. Initialize git and npm: + ```bash + git init + npm init -y + ``` + +3. Run Ralph: + ```bash + ralph --monitor + ``` + +## Key Points + +### PROMPT.md is Focused + +Notice how PROMPT.md: +- States exactly what the tool should do +- Specifies the technology (Node.js, commander.js) +- Defines key behaviors (where data is stored, error handling) + +### fix_plan.md Uses Priorities + +Tasks are grouped by priority: +- Priority 1: Foundation (must work before anything else) +- Priority 2: Core features (the main functionality) +- Priority 3: Polish (nice-to-have improvements) + +### No specs/ Directory + +This project is simple enough that PROMPT.md provides all necessary context. specs/ would be overkill here. + +## When to Add More Files + +Consider adding specs/ if you need: +- Complex command behavior documentation +- Data format specifications +- External service integration details + +For this simple example, PROMPT.md is sufficient.