[
  {
    "path": ".claude-plugin/marketplace.json",
    "content": "{\n  \"name\": \"ralph-marketplace\",\n  \"owner\": {\n    \"name\": \"snarktank\"\n  },\n  \"metadata\": {\n    \"description\": \"Skills for the Ralph autonomous agent system - Generate PRDs and convert them to prd.json format for autonomous execution\",\n    \"version\": \"1.0.0\"\n  },\n  \"plugins\": [\n    {\n      \"name\": \"ralph-skills\",\n      \"source\": \"./\",\n      \"description\": \"PRD generation and conversion skills for the Ralph autonomous agent loop\",\n      \"version\": \"1.0.0\",\n      \"keywords\": [\"ralph\", \"prd\", \"automation\", \"agent\", \"planning\"],\n      \"category\": \"productivity\",\n      \"skills\": \"./skills/\"\n    }\n  ]\n}\n"
  },
  {
    "path": ".claude-plugin/plugin.json",
    "content": "{\n  \"name\": \"ralph-skills\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Skills for the Ralph autonomous agent system - Generate PRDs and convert them to prd.json format for autonomous execution\",\n  \"author\": {\n    \"name\": \"snarktank\"\n  },\n  \"skills\": \"./skills/\",\n  \"keywords\": [\"ralph\", \"prd\", \"automation\", \"agent\", \"planning\", \"requirements\"]\n}\n"
  },
  {
    "path": ".github/workflows/deploy.yml",
    "content": "name: Deploy Flowchart to GitHub Pages\n\non:\n  push:\n    branches: [main]\n  workflow_dispatch:\n\npermissions:\n  contents: read\n  pages: write\n  id-token: write\n\nconcurrency:\n  group: pages\n  cancel-in-progress: false\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v4\n\n      - name: Setup Node\n        uses: actions/setup-node@v4\n        with:\n          node-version: 20\n          cache: npm\n          cache-dependency-path: flowchart/package-lock.json\n\n      - name: Install dependencies\n        run: npm ci\n        working-directory: flowchart\n\n      - name: Build\n        run: npm run build\n        working-directory: flowchart\n\n      - name: Setup Pages\n        uses: actions/configure-pages@v4\n\n      - name: Upload artifact\n        uses: actions/upload-pages-artifact@v3\n        with:\n          path: flowchart/dist\n\n  deploy:\n    environment:\n      name: github-pages\n      url: ${{ steps.deployment.outputs.page_url }}\n    runs-on: ubuntu-latest\n    needs: build\n    steps:\n      - name: Deploy to GitHub Pages\n        id: deployment\n        uses: actions/deploy-pages@v4\n"
  },
  {
    "path": ".gitignore",
    "content": "# Ralph working files (generated during runs)\nprd.json\nprogress.txt\n.last-branch\n\n# Archive is optional to commit\n# archive/\n\n# OS files\n.DS_Store\n\n#Claude\n.claude/\n"
  },
  {
    "path": "AGENTS.md",
    "content": "# Ralph Agent Instructions\n\n## Overview\n\nRalph is an autonomous AI agent loop that runs AI coding tools (Amp or Claude Code) repeatedly until all PRD items are complete. Each iteration is a fresh instance with clean context.\n\n## Commands\n\n```bash\n# Run the flowchart dev server\ncd flowchart && npm run dev\n\n# Build the flowchart\ncd flowchart && npm run build\n\n# Run Ralph with Amp (default)\n./ralph.sh [max_iterations]\n\n# Run Ralph with Claude Code\n./ralph.sh --tool claude [max_iterations]\n```\n\n## Key Files\n\n- `ralph.sh` - The bash loop that spawns fresh AI instances (supports `--tool amp` or `--tool claude`)\n- `prompt.md` - Instructions given to each AMP instance\n-  `CLAUDE.md` - Instructions given to each Claude Code instance\n- `prd.json.example` - Example PRD format\n- `flowchart/` - Interactive React Flow diagram explaining how Ralph works\n\n## Flowchart\n\nThe `flowchart/` directory contains an interactive visualization built with React Flow. It's designed for presentations - click through to reveal each step with animations.\n\nTo run locally:\n```bash\ncd flowchart\nnpm install\nnpm run dev\n```\n\n## Patterns\n\n- Each iteration spawns a fresh AI instance (Amp or Claude Code) with clean context\n- Memory persists via git history, `progress.txt`, and `prd.json`\n- Stories should be small enough to complete in one context window\n- Always update AGENTS.md with discovered patterns for future iterations\n"
  },
  {
    "path": "CLAUDE.md",
    "content": "# Ralph Agent Instructions\n\nYou are an autonomous coding agent working on a software project.\n\n## Your Task\n\n1. Read the PRD at `prd.json` (in the same directory as this file)\n2. Read the progress log at `progress.txt` (check Codebase Patterns section first)\n3. Check you're on the correct branch from PRD `branchName`. If not, check it out or create from main.\n4. Pick the **highest priority** user story where `passes: false`\n5. Implement that single user story\n6. Run quality checks (e.g., typecheck, lint, test - use whatever your project requires)\n7. Update CLAUDE.md files if you discover reusable patterns (see below)\n8. If checks pass, commit ALL changes with message: `feat: [Story ID] - [Story Title]`\n9. Update the PRD to set `passes: true` for the completed story\n10. Append your progress to `progress.txt`\n\n## Progress Report Format\n\nAPPEND to progress.txt (never replace, always append):\n```\n## [Date/Time] - [Story ID]\n- What was implemented\n- Files changed\n- **Learnings for future iterations:**\n  - Patterns discovered (e.g., \"this codebase uses X for Y\")\n  - Gotchas encountered (e.g., \"don't forget to update Z when changing W\")\n  - Useful context (e.g., \"the evaluation panel is in component X\")\n---\n```\n\nThe learnings section is critical - it helps future iterations avoid repeating mistakes and understand the codebase better.\n\n## Consolidate Patterns\n\nIf you discover a **reusable pattern** that future iterations should know, add it to the `## Codebase Patterns` section at the TOP of progress.txt (create it if it doesn't exist). This section should consolidate the most important learnings:\n\n```\n## Codebase Patterns\n- Example: Use `sql<number>` template for aggregations\n- Example: Always use `IF NOT EXISTS` for migrations\n- Example: Export types from actions.ts for UI components\n```\n\nOnly add patterns that are **general and reusable**, not story-specific details.\n\n## Update CLAUDE.md Files\n\nBefore committing, check if any edited files have learnings worth preserving in nearby CLAUDE.md files:\n\n1. **Identify directories with edited files** - Look at which directories you modified\n2. **Check for existing CLAUDE.md** - Look for CLAUDE.md in those directories or parent directories\n3. **Add valuable learnings** - If you discovered something future developers/agents should know:\n   - API patterns or conventions specific to that module\n   - Gotchas or non-obvious requirements\n   - Dependencies between files\n   - Testing approaches for that area\n   - Configuration or environment requirements\n\n**Examples of good CLAUDE.md additions:**\n- \"When modifying X, also update Y to keep them in sync\"\n- \"This module uses pattern Z for all API calls\"\n- \"Tests require the dev server running on PORT 3000\"\n- \"Field names must match the template exactly\"\n\n**Do NOT add:**\n- Story-specific implementation details\n- Temporary debugging notes\n- Information already in progress.txt\n\nOnly update CLAUDE.md if you have **genuinely reusable knowledge** that would help future work in that directory.\n\n## Quality Requirements\n\n- ALL commits must pass your project's quality checks (typecheck, lint, test)\n- Do NOT commit broken code\n- Keep changes focused and minimal\n- Follow existing code patterns\n\n## Browser Testing (If Available)\n\nFor any story that changes UI, verify it works in the browser if you have browser testing tools configured (e.g., via MCP):\n\n1. Navigate to the relevant page\n2. Verify the UI changes work as expected\n3. Take a screenshot if helpful for the progress log\n\nIf no browser tools are available, note in your progress report that manual browser verification is needed.\n\n## Stop Condition\n\nAfter completing a user story, check if ALL stories have `passes: true`.\n\nIf ALL stories are complete and passing, reply with:\n<promise>COMPLETE</promise>\n\nIf there are still stories with `passes: false`, end your response normally (another iteration will pick up the next story).\n\n## Important\n\n- Work on ONE story per iteration\n- Commit frequently\n- Keep CI green\n- Read the Codebase Patterns section in progress.txt before starting\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2026 snarktank\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Ralph\n\n![Ralph](ralph.webp)\n\nRalph is an autonomous AI agent loop that runs AI coding tools ([Amp](https://ampcode.com) or [Claude Code](https://docs.anthropic.com/en/docs/claude-code)) repeatedly until all PRD items are complete. Each iteration is a fresh instance with clean context. Memory persists via git history, `progress.txt`, and `prd.json`.\n\nBased on [Geoffrey Huntley's Ralph pattern](https://ghuntley.com/ralph/).\n\n[Read my in-depth article on how I use Ralph](https://x.com/ryancarson/status/2008548371712135632)\n\n## Prerequisites\n\n- One of the following AI coding tools installed and authenticated:\n  - [Amp CLI](https://ampcode.com) (default)\n  - [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (`npm install -g @anthropic-ai/claude-code`)\n- `jq` installed (`brew install jq` on macOS)\n- A git repository for your project\n\n## Setup\n\n### Option 1: Copy to your project\n\nCopy the ralph files into your project:\n\n```bash\n# From your project root\nmkdir -p scripts/ralph\ncp /path/to/ralph/ralph.sh scripts/ralph/\n\n# Copy the prompt template for your AI tool of choice:\ncp /path/to/ralph/prompt.md scripts/ralph/prompt.md    # For Amp\n# OR\ncp /path/to/ralph/CLAUDE.md scripts/ralph/CLAUDE.md    # For Claude Code\n\nchmod +x scripts/ralph/ralph.sh\n```\n\n### Option 2: Install skills globally (Amp)\n\nCopy the skills to your Amp or Claude config for use across all projects:\n\nFor AMP\n```bash\ncp -r skills/prd ~/.config/amp/skills/\ncp -r skills/ralph ~/.config/amp/skills/\n```\n\nFor Claude Code (manual)\n```bash\ncp -r skills/prd ~/.claude/skills/\ncp -r skills/ralph ~/.claude/skills/\n```\n\n### Option 3: Use as Claude Code Marketplace\n\nAdd the Ralph marketplace to Claude Code:\n\n```bash\n/plugin marketplace add snarktank/ralph\n```\n\nThen install the skills:\n\n```bash\n/plugin install ralph-skills@ralph-marketplace\n```\n\nAvailable skills after installation:\n- `/prd` - Generate Product Requirements Documents\n- `/ralph` - Convert PRDs to prd.json format\n\nSkills are automatically invoked when you ask Claude to:\n- \"create a prd\", \"write prd for\", \"plan this feature\"\n- \"convert this prd\", \"turn into ralph format\", \"create prd.json\"\n\n### Configure Amp auto-handoff (recommended)\n\nAdd to `~/.config/amp/settings.json`:\n\n```json\n{\n  \"amp.experimental.autoHandoff\": { \"context\": 90 }\n}\n```\n\nThis enables automatic handoff when context fills up, allowing Ralph to handle large stories that exceed a single context window.\n\n## Workflow\n\n### 1. Create a PRD\n\nUse the PRD skill to generate a detailed requirements document:\n\n```\nLoad the prd skill and create a PRD for [your feature description]\n```\n\nAnswer the clarifying questions. The skill saves output to `tasks/prd-[feature-name].md`.\n\n### 2. Convert PRD to Ralph format\n\nUse the Ralph skill to convert the markdown PRD to JSON:\n\n```\nLoad the ralph skill and convert tasks/prd-[feature-name].md to prd.json\n```\n\nThis creates `prd.json` with user stories structured for autonomous execution.\n\n### 3. Run Ralph\n\n```bash\n# Using Amp (default)\n./scripts/ralph/ralph.sh [max_iterations]\n\n# Using Claude Code\n./scripts/ralph/ralph.sh --tool claude [max_iterations]\n```\n\nDefault is 10 iterations. Use `--tool amp` or `--tool claude` to select your AI coding tool.\n\nRalph will:\n1. Create a feature branch (from PRD `branchName`)\n2. Pick the highest priority story where `passes: false`\n3. Implement that single story\n4. Run quality checks (typecheck, tests)\n5. Commit if checks pass\n6. Update `prd.json` to mark story as `passes: true`\n7. Append learnings to `progress.txt`\n8. Repeat until all stories pass or max iterations reached\n\n## Key Files\n\n| File | Purpose |\n|------|---------|\n| `ralph.sh` | The bash loop that spawns fresh AI instances (supports `--tool amp` or `--tool claude`) |\n| `prompt.md` | Prompt template for Amp |\n| `CLAUDE.md` | Prompt template for Claude Code |\n| `prd.json` | User stories with `passes` status (the task list) |\n| `prd.json.example` | Example PRD format for reference |\n| `progress.txt` | Append-only learnings for future iterations |\n| `skills/prd/` | Skill for generating PRDs (works with Amp and Claude Code) |\n| `skills/ralph/` | Skill for converting PRDs to JSON (works with Amp and Claude Code) |\n| `.claude-plugin/` | Plugin manifest for Claude Code marketplace discovery |\n| `flowchart/` | Interactive visualization of how Ralph works |\n\n## Flowchart\n\n[![Ralph Flowchart](ralph-flowchart.png)](https://snarktank.github.io/ralph/)\n\n**[View Interactive Flowchart](https://snarktank.github.io/ralph/)** - Click through to see each step with animations.\n\nThe `flowchart/` directory contains the source code. To run locally:\n\n```bash\ncd flowchart\nnpm install\nnpm run dev\n```\n\n## Critical Concepts\n\n### Each Iteration = Fresh Context\n\nEach iteration spawns a **new AI instance** (Amp or Claude Code) with clean context. The only memory between iterations is:\n- Git history (commits from previous iterations)\n- `progress.txt` (learnings and context)\n- `prd.json` (which stories are done)\n\n### Small Tasks\n\nEach PRD item should be small enough to complete in one context window. If a task is too big, the LLM runs out of context before finishing and produces poor code.\n\nRight-sized stories:\n- Add a database column and migration\n- Add a UI component to an existing page\n- Update a server action with new logic\n- Add a filter dropdown to a list\n\nToo big (split these):\n- \"Build the entire dashboard\"\n- \"Add authentication\"\n- \"Refactor the API\"\n\n### AGENTS.md Updates Are Critical\n\nAfter each iteration, Ralph updates the relevant `AGENTS.md` files with learnings. This is key because AI coding tools automatically read these files, so future iterations (and future human developers) benefit from discovered patterns, gotchas, and conventions.\n\nExamples of what to add to AGENTS.md:\n- Patterns discovered (\"this codebase uses X for Y\")\n- Gotchas (\"do not forget to update Z when changing W\")\n- Useful context (\"the settings panel is in component X\")\n\n### Feedback Loops\n\nRalph only works if there are feedback loops:\n- Typecheck catches type errors\n- Tests verify behavior\n- CI must stay green (broken code compounds across iterations)\n\n### Browser Verification for UI Stories\n\nFrontend stories must include \"Verify in browser using dev-browser skill\" in acceptance criteria. Ralph will use the dev-browser skill to navigate to the page, interact with the UI, and confirm changes work.\n\n### Stop Condition\n\nWhen all stories have `passes: true`, Ralph outputs `<promise>COMPLETE</promise>` and the loop exits.\n\n## Debugging\n\nCheck current state:\n\n```bash\n# See which stories are done\ncat prd.json | jq '.userStories[] | {id, title, passes}'\n\n# See learnings from previous iterations\ncat progress.txt\n\n# Check git history\ngit log --oneline -10\n```\n\n## Customizing the Prompt\n\nAfter copying `prompt.md` (for Amp) or `CLAUDE.md` (for Claude Code) to your project, customize it for your project:\n- Add project-specific quality check commands\n- Include codebase conventions\n- Add common gotchas for your stack\n\n## Archiving\n\nRalph automatically archives previous runs when you start a new feature (different `branchName`). Archives are saved to `archive/YYYY-MM-DD-feature-name/`.\n\n## References\n\n- [Geoffrey Huntley's Ralph article](https://ghuntley.com/ralph/)\n- [Amp documentation](https://ampcode.com/manual)\n- [Claude Code documentation](https://docs.anthropic.com/en/docs/claude-code)\n"
  },
  {
    "path": "flowchart/.gitignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndist-ssr\n*.local\n\n# Editor directories and files\n.vscode/*\n!.vscode/extensions.json\n.idea\n.DS_Store\n*.suo\n*.ntvs*\n*.njsproj\n*.sln\n*.sw?\n"
  },
  {
    "path": "flowchart/README.md",
    "content": "# React + TypeScript + Vite\n\nThis template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.\n\nCurrently, two official plugins are available:\n\n- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh\n- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh\n\n## React Compiler\n\nThe React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).\n\n## Expanding the ESLint configuration\n\nIf you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:\n\n```js\nexport default defineConfig([\n  globalIgnores(['dist']),\n  {\n    files: ['**/*.{ts,tsx}'],\n    extends: [\n      // Other configs...\n\n      // Remove tseslint.configs.recommended and replace with this\n      tseslint.configs.recommendedTypeChecked,\n      // Alternatively, use this for stricter rules\n      tseslint.configs.strictTypeChecked,\n      // Optionally, add this for stylistic rules\n      tseslint.configs.stylisticTypeChecked,\n\n      // Other configs...\n    ],\n    languageOptions: {\n      parserOptions: {\n        project: ['./tsconfig.node.json', './tsconfig.app.json'],\n        tsconfigRootDir: import.meta.dirname,\n      },\n      // other options...\n    },\n  },\n])\n```\n\nYou can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:\n\n```js\n// eslint.config.js\nimport reactX from 'eslint-plugin-react-x'\nimport reactDom from 'eslint-plugin-react-dom'\n\nexport default defineConfig([\n  globalIgnores(['dist']),\n  {\n    files: ['**/*.{ts,tsx}'],\n    extends: [\n      // Other configs...\n      // Enable lint rules for React\n      reactX.configs['recommended-typescript'],\n      // Enable lint rules for React DOM\n      reactDom.configs.recommended,\n    ],\n    languageOptions: {\n      parserOptions: {\n        project: ['./tsconfig.node.json', './tsconfig.app.json'],\n        tsconfigRootDir: import.meta.dirname,\n      },\n      // other options...\n    },\n  },\n])\n```\n"
  },
  {
    "path": "flowchart/eslint.config.js",
    "content": "import js from '@eslint/js'\nimport globals from 'globals'\nimport reactHooks from 'eslint-plugin-react-hooks'\nimport reactRefresh from 'eslint-plugin-react-refresh'\nimport tseslint from 'typescript-eslint'\nimport { defineConfig, globalIgnores } from 'eslint/config'\n\nexport default defineConfig([\n  globalIgnores(['dist']),\n  {\n    files: ['**/*.{ts,tsx}'],\n    extends: [\n      js.configs.recommended,\n      tseslint.configs.recommended,\n      reactHooks.configs.flat.recommended,\n      reactRefresh.configs.vite,\n    ],\n    languageOptions: {\n      ecmaVersion: 2020,\n      globals: globals.browser,\n    },\n  },\n])\n"
  },
  {
    "path": "flowchart/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/vite.svg\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>How Ralph Works</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "flowchart/package.json",
    "content": "{\n  \"name\": \"flowchart\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc -b && vite build\",\n    \"lint\": \"eslint .\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"@xyflow/react\": \"^12.10.0\",\n    \"react\": \"^19.2.0\",\n    \"react-dom\": \"^19.2.0\"\n  },\n  \"devDependencies\": {\n    \"@eslint/js\": \"^9.39.1\",\n    \"@types/node\": \"^24.10.1\",\n    \"@types/react\": \"^19.2.5\",\n    \"@types/react-dom\": \"^19.2.3\",\n    \"@vitejs/plugin-react\": \"^5.1.1\",\n    \"eslint\": \"^9.39.1\",\n    \"eslint-plugin-react-hooks\": \"^7.0.1\",\n    \"eslint-plugin-react-refresh\": \"^0.4.24\",\n    \"globals\": \"^16.5.0\",\n    \"typescript\": \"~5.9.3\",\n    \"typescript-eslint\": \"^8.46.4\",\n    \"vite\": \"^7.2.4\"\n  }\n}\n"
  },
  {
    "path": "flowchart/src/App.css",
    "content": "* {\n  margin: 0;\n  padding: 0;\n  box-sizing: border-box;\n}\n\n.app-container {\n  width: 100vw;\n  height: 100vh;\n  display: flex;\n  flex-direction: column;\n  background: #ffffff;\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n}\n\n.header {\n  text-align: center;\n  padding: 24px 20px 16px;\n  border-bottom: 1px solid #eee;\n}\n\n.header h1 {\n  font-size: 32px;\n  font-weight: 600;\n  color: #111;\n  margin-bottom: 6px;\n}\n\n.header p {\n  font-size: 16px;\n  color: #666;\n}\n\n.flow-container {\n  flex: 1;\n  width: 100%;\n}\n\n.controls {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  gap: 16px;\n  padding: 20px;\n  border-top: 1px solid #eee;\n}\n\n.controls button {\n  padding: 12px 28px;\n  font-size: 16px;\n  font-weight: 500;\n  border: 2px solid #222;\n  background: #fff;\n  color: #222;\n  border-radius: 6px;\n  cursor: pointer;\n  transition: all 0.2s;\n}\n\n.controls button:hover:not(:disabled) {\n  background: #222;\n  color: #fff;\n}\n\n.controls button:disabled {\n  opacity: 0.3;\n  cursor: not-allowed;\n}\n\n.controls .reset-btn {\n  border-color: #888;\n  color: #888;\n}\n\n.controls .reset-btn:hover:not(:disabled) {\n  background: #888;\n  color: #fff;\n}\n\n.step-counter {\n  font-size: 16px;\n  color: #666;\n  min-width: 120px;\n  text-align: center;\n}\n\n.instructions {\n  text-align: center;\n  padding: 12px;\n  font-size: 14px;\n  color: #999;\n}\n\n.node-content {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  height: 100%;\n  padding: 8px;\n}\n\n.node-title {\n  font-weight: 600;\n  font-size: 15px;\n  color: #111;\n  margin-bottom: 4px;\n  text-align: center;\n}\n\n.node-description {\n  font-size: 12px;\n  color: #666;\n  text-align: center;\n}\n\n.react-flow__node-default {\n  padding: 0;\n}\n\n.custom-node {\n  width: 240px;\n  height: 70px;\n  background: #ffffff;\n  border: 2px solid #222;\n  border-radius: 8px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.react-flow__handle {\n  width: 10px;\n  height: 10px;\n  background: #888;\n  border: 2px solid #222;\n}\n\n.react-flow__handle:hover {\n  background: #222;\n}\n\n.note-node {\n  border: 2px dashed #888;\n  border-radius: 6px;\n  padding: 12px 16px;\n  font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Code', monospace;\n  font-size: 11px;\n  line-height: 1.4;\n  color: #333;\n  max-width: 360px;\n}\n\n.note-node pre {\n  margin: 0;\n  white-space: pre-wrap;\n  word-break: break-word;\n}\n\n.react-flow__controls {\n  box-shadow: none;\n  border: 1px solid #ddd;\n}\n\n.react-flow__controls-button {\n  border-bottom: 1px solid #ddd;\n}\n\n.react-flow__controls-button:last-child {\n  border-bottom: none;\n}\n"
  },
  {
    "path": "flowchart/src/App.tsx",
    "content": "import { useCallback, useState, useRef } from 'react';\nimport type { Node, Edge, NodeChange, EdgeChange, Connection } from '@xyflow/react';\nimport {\n  ReactFlow,\n  useNodesState,\n  useEdgesState,\n  Controls,\n  Background,\n  BackgroundVariant,\n  MarkerType,\n  applyNodeChanges,\n  applyEdgeChanges,\n  addEdge,\n  Handle,\n  Position,\n  reconnectEdge,\n} from '@xyflow/react';\nimport '@xyflow/react/dist/style.css';\nimport './App.css';\n\nconst nodeWidth = 240;\nconst nodeHeight = 70;\n\n// Setup phase - horizontal at top\n// Loop phase - circular arrangement below\n// Exit - at bottom center\n\ntype Phase = 'setup' | 'loop' | 'decision' | 'done';\n\nconst phaseColors: Record<Phase, { bg: string; border: string }> = {\n  setup: { bg: '#f0f7ff', border: '#4a90d9' },\n  loop: { bg: '#f5f5f5', border: '#666666' },\n  decision: { bg: '#fff8e6', border: '#c9a227' },\n  done: { bg: '#f0fff4', border: '#38a169' },\n};\n\nconst allSteps: { id: string; label: string; description: string; phase: Phase }[] = [\n  // Setup phase (vertical)\n  { id: '1', label: 'You write a PRD', description: 'Define what you want to build', phase: 'setup' },\n  { id: '2', label: 'Convert to prd.json', description: 'Break into small user stories', phase: 'setup' },\n  { id: '3', label: 'Run ralph.sh', description: 'Starts the autonomous loop', phase: 'setup' },\n  // Loop phase\n  { id: '4', label: 'AI picks a story', description: 'Finds next passes: false', phase: 'loop' },\n  { id: '5', label: 'Implements it', description: 'Writes code, runs tests', phase: 'loop' },\n  { id: '6', label: 'Commits changes', description: 'If tests pass', phase: 'loop' },\n  { id: '7', label: 'Updates prd.json', description: 'Sets passes: true', phase: 'loop' },\n  { id: '8', label: 'Logs to progress.txt', description: 'Saves learnings', phase: 'loop' },\n  { id: '9', label: 'More stories?', description: '', phase: 'decision' },\n  // Exit\n  { id: '10', label: 'Done!', description: 'All stories complete', phase: 'done' },\n];\n\nconst notes = [\n  {\n    id: 'note-1',\n    appearsWithStep: 2,\n    position: { x: 340, y: 100 },\n    color: { bg: '#f5f0ff', border: '#8b5cf6' },\n    content: `{\n  \"id\": \"US-001\",\n  \"title\": \"Add priority field to database\",\n  \"acceptanceCriteria\": [\n    \"Add priority column to tasks table\",\n    \"Generate and run migration\",\n    \"Typecheck passes\"\n  ],\n  \"passes\": false\n}`,\n  },\n  {\n    id: 'note-2',\n    appearsWithStep: 8,\n    position: { x: 480, y: 620 },\n    color: { bg: '#fdf4f0', border: '#c97a50' },\n    content: `Also updates AGENTS.md with\npatterns discovered, so future\niterations learn from this one.`,\n  },\n];\n\nfunction CustomNode({ data }: { data: { title: string; description: string; phase: Phase } }) {\n  const colors = phaseColors[data.phase];\n  return (\n    <div \n      className=\"custom-node\"\n      style={{ \n        backgroundColor: colors.bg, \n        borderColor: colors.border \n      }}\n    >\n      <Handle type=\"target\" position={Position.Top} id=\"top\" />\n      <Handle type=\"target\" position={Position.Left} id=\"left\" />\n      <Handle type=\"source\" position={Position.Right} id=\"right\" />\n      <Handle type=\"source\" position={Position.Bottom} id=\"bottom\" />\n      <Handle type=\"target\" position={Position.Right} id=\"right-target\" style={{ right: 0 }} />\n      <Handle type=\"target\" position={Position.Bottom} id=\"bottom-target\" style={{ bottom: 0 }} />\n      <Handle type=\"source\" position={Position.Top} id=\"top-source\" />\n      <Handle type=\"source\" position={Position.Left} id=\"left-source\" />\n      <div className=\"node-content\">\n        <div className=\"node-title\">{data.title}</div>\n        {data.description && <div className=\"node-description\">{data.description}</div>}\n      </div>\n    </div>\n  );\n}\n\nfunction NoteNode({ data }: { data: { content: string; color: { bg: string; border: string } } }) {\n  return (\n    <div \n      className=\"note-node\"\n      style={{\n        backgroundColor: data.color.bg,\n        borderColor: data.color.border,\n      }}\n    >\n      <pre>{data.content}</pre>\n    </div>\n  );\n}\n\nconst nodeTypes = { custom: CustomNode, note: NoteNode };\n\nconst positions: { [key: string]: { x: number; y: number } } = {\n  // Vertical setup flow on the left\n  '1': { x: 20, y: 20 },\n  '2': { x: 80, y: 130 },\n  '3': { x: 60, y: 250 },\n  // Loop\n  '4': { x: 40, y: 420 },\n  '5': { x: 450, y: 300 },\n  '6': { x: 750, y: 450 },\n  '7': { x: 470, y: 520 },\n  '8': { x: 200, y: 620 },\n  '9': { x: 40, y: 720 },\n  // Exit\n  '10': { x: 350, y: 880 },\n  // Notes\n  ...Object.fromEntries(notes.map(n => [n.id, n.position])),\n};\n\nconst edgeConnections: { source: string; target: string; sourceHandle?: string; targetHandle?: string; label?: string }[] = [\n  // Setup phase (vertical) - bottom to top connections\n  { source: '1', target: '2', sourceHandle: 'bottom', targetHandle: 'top' },\n  { source: '2', target: '3', sourceHandle: 'bottom', targetHandle: 'top' },\n  { source: '3', target: '4', sourceHandle: 'bottom', targetHandle: 'top' },\n  // Loop phase\n  { source: '4', target: '5', sourceHandle: 'right', targetHandle: 'left' },\n  { source: '5', target: '6', sourceHandle: 'right', targetHandle: 'top' },\n  { source: '6', target: '7', sourceHandle: 'left-source', targetHandle: 'right-target' },\n  { source: '7', target: '8', sourceHandle: 'left-source', targetHandle: 'right-target' },\n  { source: '8', target: '9', sourceHandle: 'left-source', targetHandle: 'right-target' },\n  { source: '9', target: '4', sourceHandle: 'top-source', targetHandle: 'bottom-target', label: 'Yes' },\n  // Exit\n  { source: '9', target: '10', sourceHandle: 'bottom', targetHandle: 'top', label: 'No' },\n];\n\nfunction createNode(step: typeof allSteps[0], visible: boolean, position?: { x: number; y: number }): Node {\n  return {\n    id: step.id,\n    type: 'custom',\n    position: position || positions[step.id],\n    data: {\n      title: step.label,\n      description: step.description,\n      phase: step.phase,\n    },\n    style: {\n      width: nodeWidth,\n      height: nodeHeight,\n      opacity: visible ? 1 : 0,\n      transition: 'opacity 0.5s ease-in-out',\n      pointerEvents: visible ? 'auto' : 'none',\n    },\n  };\n}\n\nfunction createEdge(conn: typeof edgeConnections[0], visible: boolean): Edge {\n  return {\n    id: `e${conn.source}-${conn.target}`,\n    source: conn.source,\n    target: conn.target,\n    sourceHandle: conn.sourceHandle,\n    targetHandle: conn.targetHandle,\n    label: visible ? conn.label : undefined,\n    animated: visible,\n    style: {\n      stroke: '#222',\n      strokeWidth: 2,\n      opacity: visible ? 1 : 0,\n      transition: 'opacity 0.5s ease-in-out',\n    },\n    labelStyle: {\n      fill: '#222',\n      fontWeight: 600,\n      fontSize: 14,\n    },\n    labelShowBg: true,\n    labelBgPadding: [8, 4] as [number, number],\n    labelBgStyle: {\n      fill: '#fff',\n      stroke: '#222',\n      strokeWidth: 1,\n    },\n    markerEnd: {\n      type: MarkerType.ArrowClosed,\n      color: '#222',\n    },\n  };\n}\n\nfunction createNoteNode(note: typeof notes[0], visible: boolean, position?: { x: number; y: number }): Node {\n  return {\n    id: note.id,\n    type: 'note',\n    position: position || positions[note.id],\n    data: { content: note.content, color: note.color },\n    style: {\n      opacity: visible ? 1 : 0,\n      transition: 'opacity 0.5s ease-in-out',\n      pointerEvents: visible ? 'auto' : 'none',\n    },\n    draggable: true,\n    selectable: false,\n    connectable: false,\n  };\n}\n\nfunction App() {\n  const [visibleCount, setVisibleCount] = useState(1);\n  const nodePositions = useRef<{ [key: string]: { x: number; y: number } }>({ ...positions });\n\n  const getNodes = (count: number) => {\n    const stepNodes = allSteps.map((step, index) =>\n      createNode(step, index < count, nodePositions.current[step.id])\n    );\n    const noteNodes = notes.map(note => {\n      const noteVisible = count >= note.appearsWithStep;\n      return createNoteNode(note, noteVisible, nodePositions.current[note.id]);\n    });\n    return [...stepNodes, ...noteNodes];\n  };\n\n  const initialNodes = getNodes(1);\n  const initialEdges = edgeConnections.map((conn, index) =>\n    createEdge(conn, index < 0)\n  );\n\n  const [nodes, setNodes] = useNodesState(initialNodes);\n  const [edges, setEdges] = useEdgesState(initialEdges);\n\n  const onNodesChange = useCallback(\n    (changes: NodeChange[]) => {\n      changes.forEach((change) => {\n        if (change.type === 'position' && change.position) {\n          nodePositions.current[change.id] = change.position;\n        }\n      });\n      setNodes((nds) => applyNodeChanges(changes, nds));\n    },\n    [setNodes]\n  );\n\n  const onEdgesChange = useCallback(\n    (changes: EdgeChange[]) => {\n      setEdges((eds) => applyEdgeChanges(changes, eds));\n    },\n    [setEdges]\n  );\n\n  const onConnect = useCallback(\n    (connection: Connection) => {\n      setEdges((eds) => addEdge({ ...connection, animated: true, style: { stroke: '#222', strokeWidth: 2 }, markerEnd: { type: MarkerType.ArrowClosed, color: '#222' } }, eds));\n    },\n    [setEdges]\n  );\n\n  const onReconnect = useCallback(\n    (oldEdge: Edge, newConnection: Connection) => {\n      setEdges((eds) => reconnectEdge(oldEdge, newConnection, eds));\n    },\n    [setEdges]\n  );\n\n  const getEdgeVisibility = (conn: typeof edgeConnections[0], visibleStepCount: number) => {\n    const sourceIndex = allSteps.findIndex(s => s.id === conn.source);\n    const targetIndex = allSteps.findIndex(s => s.id === conn.target);\n    return sourceIndex < visibleStepCount && targetIndex < visibleStepCount;\n  };\n\n  const handleNext = useCallback(() => {\n    if (visibleCount < allSteps.length) {\n      const newCount = visibleCount + 1;\n      setVisibleCount(newCount);\n\n      setNodes(getNodes(newCount));\n      setEdges(\n        edgeConnections.map((conn) =>\n          createEdge(conn, getEdgeVisibility(conn, newCount))\n        )\n      );\n    }\n  }, [visibleCount, setNodes, setEdges]);\n\n  const handlePrev = useCallback(() => {\n    if (visibleCount > 1) {\n      const newCount = visibleCount - 1;\n      setVisibleCount(newCount);\n\n      setNodes(getNodes(newCount));\n      setEdges(\n        edgeConnections.map((conn) =>\n          createEdge(conn, getEdgeVisibility(conn, newCount))\n        )\n      );\n    }\n  }, [visibleCount, setNodes, setEdges]);\n\n  const handleReset = useCallback(() => {\n    setVisibleCount(1);\n    nodePositions.current = { ...positions };\n    setNodes(getNodes(1));\n    setEdges(edgeConnections.map((conn, index) => createEdge(conn, index < 0)));\n  }, [setNodes, setEdges]);\n\n  return (\n    <div className=\"app-container\">\n      <div className=\"header\">\n        <h1>How Ralph Works</h1>\n        <p>Autonomous AI agent loop for completing PRDs</p>\n      </div>\n      <div className=\"flow-container\">\n        <ReactFlow\n          nodes={nodes}\n          edges={edges}\n          nodeTypes={nodeTypes}\n          onNodesChange={onNodesChange}\n          onEdgesChange={onEdgesChange}\n          onConnect={onConnect}\n          onReconnect={onReconnect}\n          fitView\n          fitViewOptions={{ padding: 0.2 }}\n          nodesDraggable={true}\n          nodesConnectable={true}\n          edgesReconnectable={true}\n          elementsSelectable={true}\n          deleteKeyCode={['Backspace', 'Delete']}\n          panOnDrag={true}\n          panOnScroll={true}\n          zoomOnScroll={true}\n          zoomOnPinch={true}\n          zoomOnDoubleClick={true}\n          selectNodesOnDrag={false}\n        >\n          <Background variant={BackgroundVariant.Dots} gap={20} size={1} color=\"#ddd\" />\n          <Controls showInteractive={false} />\n        </ReactFlow>\n      </div>\n      <div className=\"controls\">\n        <button onClick={handlePrev} disabled={visibleCount <= 1}>\n          Previous\n        </button>\n        <span className=\"step-counter\">\n          Step {visibleCount} of {allSteps.length}\n        </span>\n        <button onClick={handleNext} disabled={visibleCount >= allSteps.length}>\n          Next\n        </button>\n        <button onClick={handleReset} className=\"reset-btn\">\n          Reset\n        </button>\n      </div>\n      <div className=\"instructions\">\n        Click Next to reveal each step\n      </div>\n    </div>\n  );\n}\n\nexport default App;\n"
  },
  {
    "path": "flowchart/src/index.css",
    "content": ":root {\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n  font-synthesis: none;\n  text-rendering: optimizeLegibility;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\nbody {\n  margin: 0;\n  padding: 0;\n  background: #ffffff;\n}\n"
  },
  {
    "path": "flowchart/src/main.tsx",
    "content": "import { StrictMode } from 'react'\nimport { createRoot } from 'react-dom/client'\nimport './index.css'\nimport App from './App.tsx'\n\ncreateRoot(document.getElementById('root')!).render(\n  <StrictMode>\n    <App />\n  </StrictMode>,\n)\n"
  },
  {
    "path": "flowchart/tsconfig.app.json",
    "content": "{\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \"./node_modules/.tmp/tsconfig.app.tsbuildinfo\",\n    \"target\": \"ES2022\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"ESNext\",\n    \"types\": [\"vite/client\"],\n    \"skipLibCheck\": true,\n\n    /* Bundler mode */\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"verbatimModuleSyntax\": true,\n    \"moduleDetection\": \"force\",\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n\n    /* Linting */\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"erasableSyntaxOnly\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"noUncheckedSideEffectImports\": true\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "flowchart/tsconfig.json",
    "content": "{\n  \"files\": [],\n  \"references\": [\n    { \"path\": \"./tsconfig.app.json\" },\n    { \"path\": \"./tsconfig.node.json\" }\n  ]\n}\n"
  },
  {
    "path": "flowchart/tsconfig.node.json",
    "content": "{\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \"./node_modules/.tmp/tsconfig.node.tsbuildinfo\",\n    \"target\": \"ES2023\",\n    \"lib\": [\"ES2023\"],\n    \"module\": \"ESNext\",\n    \"types\": [\"node\"],\n    \"skipLibCheck\": true,\n\n    /* Bundler mode */\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"verbatimModuleSyntax\": true,\n    \"moduleDetection\": \"force\",\n    \"noEmit\": true,\n\n    /* Linting */\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"erasableSyntaxOnly\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"noUncheckedSideEffectImports\": true\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n"
  },
  {
    "path": "flowchart/vite.config.ts",
    "content": "import { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vite.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  base: '/ralph/',\n})\n"
  },
  {
    "path": "prd.json.example",
    "content": "{\n  \"project\": \"MyApp\",\n  \"branchName\": \"ralph/task-priority\",\n  \"description\": \"Task Priority System - Add priority levels to tasks\",\n  \"userStories\": [\n    {\n      \"id\": \"US-001\",\n      \"title\": \"Add priority field to database\",\n      \"description\": \"As a developer, I need to store task priority so it persists across sessions.\",\n      \"acceptanceCriteria\": [\n        \"Add priority column to tasks table: 'high' | 'medium' | 'low' (default 'medium')\",\n        \"Generate and run migration successfully\",\n        \"Typecheck passes\"\n      ],\n      \"priority\": 1,\n      \"passes\": false,\n      \"notes\": \"\"\n    },\n    {\n      \"id\": \"US-002\",\n      \"title\": \"Display priority indicator on task cards\",\n      \"description\": \"As a user, I want to see task priority at a glance.\",\n      \"acceptanceCriteria\": [\n        \"Each task card shows colored priority badge (red=high, yellow=medium, gray=low)\",\n        \"Priority visible without hovering or clicking\",\n        \"Typecheck passes\",\n        \"Verify in browser using dev-browser skill\"\n      ],\n      \"priority\": 2,\n      \"passes\": false,\n      \"notes\": \"\"\n    },\n    {\n      \"id\": \"US-003\",\n      \"title\": \"Add priority selector to task edit\",\n      \"description\": \"As a user, I want to change a task's priority when editing it.\",\n      \"acceptanceCriteria\": [\n        \"Priority dropdown in task edit modal\",\n        \"Shows current priority as selected\",\n        \"Saves immediately on selection change\",\n        \"Typecheck passes\",\n        \"Verify in browser using dev-browser skill\"\n      ],\n      \"priority\": 3,\n      \"passes\": false,\n      \"notes\": \"\"\n    },\n    {\n      \"id\": \"US-004\",\n      \"title\": \"Filter tasks by priority\",\n      \"description\": \"As a user, I want to filter the task list to see only high-priority items.\",\n      \"acceptanceCriteria\": [\n        \"Filter dropdown with options: All | High | Medium | Low\",\n        \"Filter persists in URL params\",\n        \"Empty state message when no tasks match filter\",\n        \"Typecheck passes\",\n        \"Verify in browser using dev-browser skill\"\n      ],\n      \"priority\": 4,\n      \"passes\": false,\n      \"notes\": \"\"\n    }\n  ]\n}\n"
  },
  {
    "path": "prompt.md",
    "content": "# Ralph Agent Instructions\n\nYou are an autonomous coding agent working on a software project.\n\n## Your Task\n\n1. Read the PRD at `prd.json` (in the same directory as this file)\n2. Read the progress log at `progress.txt` (check Codebase Patterns section first)\n3. Check you're on the correct branch from PRD `branchName`. If not, check it out or create from main.\n4. Pick the **highest priority** user story where `passes: false`\n5. Implement that single user story\n6. Run quality checks (e.g., typecheck, lint, test - use whatever your project requires)\n7. Update AGENTS.md files if you discover reusable patterns (see below)\n8. If checks pass, commit ALL changes with message: `feat: [Story ID] - [Story Title]`\n9. Update the PRD to set `passes: true` for the completed story\n10. Append your progress to `progress.txt`\n\n## Progress Report Format\n\nAPPEND to progress.txt (never replace, always append):\n```\n## [Date/Time] - [Story ID]\nThread: https://ampcode.com/threads/$AMP_CURRENT_THREAD_ID\n- What was implemented\n- Files changed\n- **Learnings for future iterations:**\n  - Patterns discovered (e.g., \"this codebase uses X for Y\")\n  - Gotchas encountered (e.g., \"don't forget to update Z when changing W\")\n  - Useful context (e.g., \"the evaluation panel is in component X\")\n---\n```\n\nInclude the thread URL so future iterations can use the `read_thread` tool to reference previous work if needed.\n\nThe learnings section is critical - it helps future iterations avoid repeating mistakes and understand the codebase better.\n\n## Consolidate Patterns\n\nIf you discover a **reusable pattern** that future iterations should know, add it to the `## Codebase Patterns` section at the TOP of progress.txt (create it if it doesn't exist). This section should consolidate the most important learnings:\n\n```\n## Codebase Patterns\n- Example: Use `sql<number>` template for aggregations\n- Example: Always use `IF NOT EXISTS` for migrations\n- Example: Export types from actions.ts for UI components\n```\n\nOnly add patterns that are **general and reusable**, not story-specific details.\n\n## Update AGENTS.md Files\n\nBefore committing, check if any edited files have learnings worth preserving in nearby AGENTS.md files:\n\n1. **Identify directories with edited files** - Look at which directories you modified\n2. **Check for existing AGENTS.md** - Look for AGENTS.md in those directories or parent directories\n3. **Add valuable learnings** - If you discovered something future developers/agents should know:\n   - API patterns or conventions specific to that module\n   - Gotchas or non-obvious requirements\n   - Dependencies between files\n   - Testing approaches for that area\n   - Configuration or environment requirements\n\n**Examples of good AGENTS.md additions:**\n- \"When modifying X, also update Y to keep them in sync\"\n- \"This module uses pattern Z for all API calls\"\n- \"Tests require the dev server running on PORT 3000\"\n- \"Field names must match the template exactly\"\n\n**Do NOT add:**\n- Story-specific implementation details\n- Temporary debugging notes\n- Information already in progress.txt\n\nOnly update AGENTS.md if you have **genuinely reusable knowledge** that would help future work in that directory.\n\n## Quality Requirements\n\n- ALL commits must pass your project's quality checks (typecheck, lint, test)\n- Do NOT commit broken code\n- Keep changes focused and minimal\n- Follow existing code patterns\n\n## Browser Testing (Required for Frontend Stories)\n\nFor any story that changes UI, you MUST verify it works in the browser:\n\n1. Load the `dev-browser` skill\n2. Navigate to the relevant page\n3. Verify the UI changes work as expected\n4. Take a screenshot if helpful for the progress log\n\nA frontend story is NOT complete until browser verification passes.\n\n## Stop Condition\n\nAfter completing a user story, check if ALL stories have `passes: true`.\n\nIf ALL stories are complete and passing, reply with:\n<promise>COMPLETE</promise>\n\nIf there are still stories with `passes: false`, end your response normally (another iteration will pick up the next story).\n\n## Important\n\n- Work on ONE story per iteration\n- Commit frequently\n- Keep CI green\n- Read the Codebase Patterns section in progress.txt before starting\n"
  },
  {
    "path": "ralph.sh",
    "content": "#!/bin/bash\n# Ralph Wiggum - Long-running AI agent loop\n# Usage: ./ralph.sh [--tool amp|claude] [max_iterations]\n\nset -e\n\n# Parse arguments\nTOOL=\"amp\"  # Default to amp for backwards compatibility\nMAX_ITERATIONS=10\n\nwhile [[ $# -gt 0 ]]; do\n  case $1 in\n    --tool)\n      TOOL=\"$2\"\n      shift 2\n      ;;\n    --tool=*)\n      TOOL=\"${1#*=}\"\n      shift\n      ;;\n    *)\n      # Assume it's max_iterations if it's a number\n      if [[ \"$1\" =~ ^[0-9]+$ ]]; then\n        MAX_ITERATIONS=\"$1\"\n      fi\n      shift\n      ;;\n  esac\ndone\n\n# Validate tool choice\nif [[ \"$TOOL\" != \"amp\" && \"$TOOL\" != \"claude\" ]]; then\n  echo \"Error: Invalid tool '$TOOL'. Must be 'amp' or 'claude'.\"\n  exit 1\nfi\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nPRD_FILE=\"$SCRIPT_DIR/prd.json\"\nPROGRESS_FILE=\"$SCRIPT_DIR/progress.txt\"\nARCHIVE_DIR=\"$SCRIPT_DIR/archive\"\nLAST_BRANCH_FILE=\"$SCRIPT_DIR/.last-branch\"\n\n# Archive previous run if branch changed\nif [ -f \"$PRD_FILE\" ] && [ -f \"$LAST_BRANCH_FILE\" ]; then\n  CURRENT_BRANCH=$(jq -r '.branchName // empty' \"$PRD_FILE\" 2>/dev/null || echo \"\")\n  LAST_BRANCH=$(cat \"$LAST_BRANCH_FILE\" 2>/dev/null || echo \"\")\n  \n  if [ -n \"$CURRENT_BRANCH\" ] && [ -n \"$LAST_BRANCH\" ] && [ \"$CURRENT_BRANCH\" != \"$LAST_BRANCH\" ]; then\n    # Archive the previous run\n    DATE=$(date +%Y-%m-%d)\n    # Strip \"ralph/\" prefix from branch name for folder\n    FOLDER_NAME=$(echo \"$LAST_BRANCH\" | sed 's|^ralph/||')\n    ARCHIVE_FOLDER=\"$ARCHIVE_DIR/$DATE-$FOLDER_NAME\"\n    \n    echo \"Archiving previous run: $LAST_BRANCH\"\n    mkdir -p \"$ARCHIVE_FOLDER\"\n    [ -f \"$PRD_FILE\" ] && cp \"$PRD_FILE\" \"$ARCHIVE_FOLDER/\"\n    [ -f \"$PROGRESS_FILE\" ] && cp \"$PROGRESS_FILE\" \"$ARCHIVE_FOLDER/\"\n    echo \"   Archived to: $ARCHIVE_FOLDER\"\n    \n    # Reset progress file for new run\n    echo \"# Ralph Progress Log\" > \"$PROGRESS_FILE\"\n    echo \"Started: $(date)\" >> \"$PROGRESS_FILE\"\n    echo \"---\" >> \"$PROGRESS_FILE\"\n  fi\nfi\n\n# Track current branch\nif [ -f \"$PRD_FILE\" ]; then\n  CURRENT_BRANCH=$(jq -r '.branchName // empty' \"$PRD_FILE\" 2>/dev/null || echo \"\")\n  if [ -n \"$CURRENT_BRANCH\" ]; then\n    echo \"$CURRENT_BRANCH\" > \"$LAST_BRANCH_FILE\"\n  fi\nfi\n\n# Initialize progress file if it doesn't exist\nif [ ! -f \"$PROGRESS_FILE\" ]; then\n  echo \"# Ralph Progress Log\" > \"$PROGRESS_FILE\"\n  echo \"Started: $(date)\" >> \"$PROGRESS_FILE\"\n  echo \"---\" >> \"$PROGRESS_FILE\"\nfi\n\necho \"Starting Ralph - Tool: $TOOL - Max iterations: $MAX_ITERATIONS\"\n\nfor i in $(seq 1 $MAX_ITERATIONS); do\n  echo \"\"\n  echo \"===============================================================\"\n  echo \"  Ralph Iteration $i of $MAX_ITERATIONS ($TOOL)\"\n  echo \"===============================================================\"\n\n  # Run the selected tool with the ralph prompt\n  if [[ \"$TOOL\" == \"amp\" ]]; then\n    OUTPUT=$(cat \"$SCRIPT_DIR/prompt.md\" | amp --dangerously-allow-all 2>&1 | tee /dev/stderr) || true\n  else\n    # Claude Code: use --dangerously-skip-permissions for autonomous operation, --print for output\n    OUTPUT=$(claude --dangerously-skip-permissions --print < \"$SCRIPT_DIR/CLAUDE.md\" 2>&1 | tee /dev/stderr) || true\n  fi\n  \n  # Check for completion signal\n  if echo \"$OUTPUT\" | grep -q \"<promise>COMPLETE</promise>\"; then\n    echo \"\"\n    echo \"Ralph completed all tasks!\"\n    echo \"Completed at iteration $i of $MAX_ITERATIONS\"\n    exit 0\n  fi\n  \n  echo \"Iteration $i complete. Continuing...\"\n  sleep 2\ndone\n\necho \"\"\necho \"Ralph reached max iterations ($MAX_ITERATIONS) without completing all tasks.\"\necho \"Check $PROGRESS_FILE for status.\"\nexit 1\n"
  },
  {
    "path": "skills/prd/SKILL.md",
    "content": "---\nname: prd\ndescription: \"Generate a Product Requirements Document (PRD) for a new feature. Use when planning a feature, starting a new project, or when asked to create a PRD. Triggers on: create a prd, write prd for, plan this feature, requirements for, spec out.\"\nuser-invocable: true\n---\n\n# PRD Generator\n\nCreate detailed Product Requirements Documents that are clear, actionable, and suitable for implementation.\n\n---\n\n## The Job\n\n1. Receive a feature description from the user\n2. Ask 3-5 essential clarifying questions (with lettered options)\n3. Generate a structured PRD based on answers\n4. Save to `tasks/prd-[feature-name].md`\n\n**Important:** Do NOT start implementing. Just create the PRD.\n\n---\n\n## Step 1: Clarifying Questions\n\nAsk only critical questions where the initial prompt is ambiguous. Focus on:\n\n- **Problem/Goal:** What problem does this solve?\n- **Core Functionality:** What are the key actions?\n- **Scope/Boundaries:** What should it NOT do?\n- **Success Criteria:** How do we know it's done?\n\n### Format Questions Like This:\n\n```\n1. What is the primary goal of this feature?\n   A. Improve user onboarding experience\n   B. Increase user retention\n   C. Reduce support burden\n   D. Other: [please specify]\n\n2. Who is the target user?\n   A. New users only\n   B. Existing users only\n   C. All users\n   D. Admin users only\n\n3. What is the scope?\n   A. Minimal viable version\n   B. Full-featured implementation\n   C. Just the backend/API\n   D. Just the UI\n```\n\nThis lets users respond with \"1A, 2C, 3B\" for quick iteration. Remember to indent the options.\n\n---\n\n## Step 2: PRD Structure\n\nGenerate the PRD with these sections:\n\n### 1. Introduction/Overview\nBrief description of the feature and the problem it solves.\n\n### 2. Goals\nSpecific, measurable objectives (bullet list).\n\n### 3. User Stories\nEach story needs:\n- **Title:** Short descriptive name\n- **Description:** \"As a [user], I want [feature] so that [benefit]\"\n- **Acceptance Criteria:** Verifiable checklist of what \"done\" means\n\nEach story should be small enough to implement in one focused session.\n\n**Format:**\n```markdown\n### US-001: [Title]\n**Description:** As a [user], I want [feature] so that [benefit].\n\n**Acceptance Criteria:**\n- [ ] Specific verifiable criterion\n- [ ] Another criterion\n- [ ] Typecheck/lint passes\n- [ ] **[UI stories only]** Verify in browser using dev-browser skill\n```\n\n**Important:** \n- Acceptance criteria must be verifiable, not vague. \"Works correctly\" is bad. \"Button shows confirmation dialog before deleting\" is good.\n- **For any story with UI changes:** Always include \"Verify in browser using dev-browser skill\" as acceptance criteria. This ensures visual verification of frontend work.\n\n### 4. Functional Requirements\nNumbered list of specific functionalities:\n- \"FR-1: The system must allow users to...\"\n- \"FR-2: When a user clicks X, the system must...\"\n\nBe explicit and unambiguous.\n\n### 5. Non-Goals (Out of Scope)\nWhat this feature will NOT include. Critical for managing scope.\n\n### 6. Design Considerations (Optional)\n- UI/UX requirements\n- Link to mockups if available\n- Relevant existing components to reuse\n\n### 7. Technical Considerations (Optional)\n- Known constraints or dependencies\n- Integration points with existing systems\n- Performance requirements\n\n### 8. Success Metrics\nHow will success be measured?\n- \"Reduce time to complete X by 50%\"\n- \"Increase conversion rate by 10%\"\n\n### 9. Open Questions\nRemaining questions or areas needing clarification.\n\n---\n\n## Writing for Junior Developers\n\nThe PRD reader may be a junior developer or AI agent. Therefore:\n\n- Be explicit and unambiguous\n- Avoid jargon or explain it\n- Provide enough detail to understand purpose and core logic\n- Number requirements for easy reference\n- Use concrete examples where helpful\n\n---\n\n## Output\n\n- **Format:** Markdown (`.md`)\n- **Location:** `tasks/`\n- **Filename:** `prd-[feature-name].md` (kebab-case)\n\n---\n\n## Example PRD\n\n```markdown\n# PRD: Task Priority System\n\n## Introduction\n\nAdd priority levels to tasks so users can focus on what matters most. Tasks can be marked as high, medium, or low priority, with visual indicators and filtering to help users manage their workload effectively.\n\n## Goals\n\n- Allow assigning priority (high/medium/low) to any task\n- Provide clear visual differentiation between priority levels\n- Enable filtering and sorting by priority\n- Default new tasks to medium priority\n\n## User Stories\n\n### US-001: Add priority field to database\n**Description:** As a developer, I need to store task priority so it persists across sessions.\n\n**Acceptance Criteria:**\n- [ ] Add priority column to tasks table: 'high' | 'medium' | 'low' (default 'medium')\n- [ ] Generate and run migration successfully\n- [ ] Typecheck passes\n\n### US-002: Display priority indicator on task cards\n**Description:** As a user, I want to see task priority at a glance so I know what needs attention first.\n\n**Acceptance Criteria:**\n- [ ] Each task card shows colored priority badge (red=high, yellow=medium, gray=low)\n- [ ] Priority visible without hovering or clicking\n- [ ] Typecheck passes\n- [ ] Verify in browser using dev-browser skill\n\n### US-003: Add priority selector to task edit\n**Description:** As a user, I want to change a task's priority when editing it.\n\n**Acceptance Criteria:**\n- [ ] Priority dropdown in task edit modal\n- [ ] Shows current priority as selected\n- [ ] Saves immediately on selection change\n- [ ] Typecheck passes\n- [ ] Verify in browser using dev-browser skill\n\n### US-004: Filter tasks by priority\n**Description:** As a user, I want to filter the task list to see only high-priority items when I'm focused.\n\n**Acceptance Criteria:**\n- [ ] Filter dropdown with options: All | High | Medium | Low\n- [ ] Filter persists in URL params\n- [ ] Empty state message when no tasks match filter\n- [ ] Typecheck passes\n- [ ] Verify in browser using dev-browser skill\n\n## Functional Requirements\n\n- FR-1: Add `priority` field to tasks table ('high' | 'medium' | 'low', default 'medium')\n- FR-2: Display colored priority badge on each task card\n- FR-3: Include priority selector in task edit modal\n- FR-4: Add priority filter dropdown to task list header\n- FR-5: Sort by priority within each status column (high to medium to low)\n\n## Non-Goals\n\n- No priority-based notifications or reminders\n- No automatic priority assignment based on due date\n- No priority inheritance for subtasks\n\n## Technical Considerations\n\n- Reuse existing badge component with color variants\n- Filter state managed via URL search params\n- Priority stored in database, not computed\n\n## Success Metrics\n\n- Users can change priority in under 2 clicks\n- High-priority tasks immediately visible at top of lists\n- No regression in task list performance\n\n## Open Questions\n\n- Should priority affect task ordering within a column?\n- Should we add keyboard shortcuts for priority changes?\n```\n\n---\n\n## Checklist\n\nBefore saving the PRD:\n\n- [ ] Asked clarifying questions with lettered options\n- [ ] Incorporated user's answers\n- [ ] User stories are small and specific\n- [ ] Functional requirements are numbered and unambiguous\n- [ ] Non-goals section defines clear boundaries\n- [ ] Saved to `tasks/prd-[feature-name].md`\n"
  },
  {
    "path": "skills/ralph/SKILL.md",
    "content": "---\nname: ralph\ndescription: \"Convert PRDs to prd.json format for the Ralph autonomous agent system. Use when you have an existing PRD and need to convert it to Ralph's JSON format. Triggers on: convert this prd, turn this into ralph format, create prd.json from this, ralph json.\"\nuser-invocable: true\n---\n\n# Ralph PRD Converter\n\nConverts existing PRDs to the prd.json format that Ralph uses for autonomous execution.\n\n---\n\n## The Job\n\nTake a PRD (markdown file or text) and convert it to `prd.json` in your ralph directory.\n\n---\n\n## Output Format\n\n```json\n{\n  \"project\": \"[Project Name]\",\n  \"branchName\": \"ralph/[feature-name-kebab-case]\",\n  \"description\": \"[Feature description from PRD title/intro]\",\n  \"userStories\": [\n    {\n      \"id\": \"US-001\",\n      \"title\": \"[Story title]\",\n      \"description\": \"As a [user], I want [feature] so that [benefit]\",\n      \"acceptanceCriteria\": [\n        \"Criterion 1\",\n        \"Criterion 2\",\n        \"Typecheck passes\"\n      ],\n      \"priority\": 1,\n      \"passes\": false,\n      \"notes\": \"\"\n    }\n  ]\n}\n```\n\n---\n\n## Story Size: The Number One Rule\n\n**Each story must be completable in ONE Ralph iteration (one context window).**\n\nRalph spawns a fresh Amp instance per iteration with no memory of previous work. If a story is too big, the LLM runs out of context before finishing and produces broken code.\n\n### Right-sized stories:\n- Add a database column and migration\n- Add a UI component to an existing page\n- Update a server action with new logic\n- Add a filter dropdown to a list\n\n### Too big (split these):\n- \"Build the entire dashboard\" - Split into: schema, queries, UI components, filters\n- \"Add authentication\" - Split into: schema, middleware, login UI, session handling\n- \"Refactor the API\" - Split into one story per endpoint or pattern\n\n**Rule of thumb:** If you cannot describe the change in 2-3 sentences, it is too big.\n\n---\n\n## Story Ordering: Dependencies First\n\nStories execute in priority order. Earlier stories must not depend on later ones.\n\n**Correct order:**\n1. Schema/database changes (migrations)\n2. Server actions / backend logic\n3. UI components that use the backend\n4. Dashboard/summary views that aggregate data\n\n**Wrong order:**\n1. UI component (depends on schema that does not exist yet)\n2. Schema change\n\n---\n\n## Acceptance Criteria: Must Be Verifiable\n\nEach criterion must be something Ralph can CHECK, not something vague.\n\n### Good criteria (verifiable):\n- \"Add `status` column to tasks table with default 'pending'\"\n- \"Filter dropdown has options: All, Active, Completed\"\n- \"Clicking delete shows confirmation dialog\"\n- \"Typecheck passes\"\n- \"Tests pass\"\n\n### Bad criteria (vague):\n- \"Works correctly\"\n- \"User can do X easily\"\n- \"Good UX\"\n- \"Handles edge cases\"\n\n### Always include as final criterion:\n```\n\"Typecheck passes\"\n```\n\nFor stories with testable logic, also include:\n```\n\"Tests pass\"\n```\n\n### For stories that change UI, also include:\n```\n\"Verify in browser using dev-browser skill\"\n```\n\nFrontend stories are NOT complete until visually verified. Ralph will use the dev-browser skill to navigate to the page, interact with the UI, and confirm changes work.\n\n---\n\n## Conversion Rules\n\n1. **Each user story becomes one JSON entry**\n2. **IDs**: Sequential (US-001, US-002, etc.)\n3. **Priority**: Based on dependency order, then document order\n4. **All stories**: `passes: false` and empty `notes`\n5. **branchName**: Derive from feature name, kebab-case, prefixed with `ralph/`\n6. **Always add**: \"Typecheck passes\" to every story's acceptance criteria\n\n---\n\n## Splitting Large PRDs\n\nIf a PRD has big features, split them:\n\n**Original:**\n> \"Add user notification system\"\n\n**Split into:**\n1. US-001: Add notifications table to database\n2. US-002: Create notification service for sending notifications\n3. US-003: Add notification bell icon to header\n4. US-004: Create notification dropdown panel\n5. US-005: Add mark-as-read functionality\n6. US-006: Add notification preferences page\n\nEach is one focused change that can be completed and verified independently.\n\n---\n\n## Example\n\n**Input PRD:**\n```markdown\n# Task Status Feature\n\nAdd ability to mark tasks with different statuses.\n\n## Requirements\n- Toggle between pending/in-progress/done on task list\n- Filter list by status\n- Show status badge on each task\n- Persist status in database\n```\n\n**Output prd.json:**\n```json\n{\n  \"project\": \"TaskApp\",\n  \"branchName\": \"ralph/task-status\",\n  \"description\": \"Task Status Feature - Track task progress with status indicators\",\n  \"userStories\": [\n    {\n      \"id\": \"US-001\",\n      \"title\": \"Add status field to tasks table\",\n      \"description\": \"As a developer, I need to store task status in the database.\",\n      \"acceptanceCriteria\": [\n        \"Add status column: 'pending' | 'in_progress' | 'done' (default 'pending')\",\n        \"Generate and run migration successfully\",\n        \"Typecheck passes\"\n      ],\n      \"priority\": 1,\n      \"passes\": false,\n      \"notes\": \"\"\n    },\n    {\n      \"id\": \"US-002\",\n      \"title\": \"Display status badge on task cards\",\n      \"description\": \"As a user, I want to see task status at a glance.\",\n      \"acceptanceCriteria\": [\n        \"Each task card shows colored status badge\",\n        \"Badge colors: gray=pending, blue=in_progress, green=done\",\n        \"Typecheck passes\",\n        \"Verify in browser using dev-browser skill\"\n      ],\n      \"priority\": 2,\n      \"passes\": false,\n      \"notes\": \"\"\n    },\n    {\n      \"id\": \"US-003\",\n      \"title\": \"Add status toggle to task list rows\",\n      \"description\": \"As a user, I want to change task status directly from the list.\",\n      \"acceptanceCriteria\": [\n        \"Each row has status dropdown or toggle\",\n        \"Changing status saves immediately\",\n        \"UI updates without page refresh\",\n        \"Typecheck passes\",\n        \"Verify in browser using dev-browser skill\"\n      ],\n      \"priority\": 3,\n      \"passes\": false,\n      \"notes\": \"\"\n    },\n    {\n      \"id\": \"US-004\",\n      \"title\": \"Filter tasks by status\",\n      \"description\": \"As a user, I want to filter the list to see only certain statuses.\",\n      \"acceptanceCriteria\": [\n        \"Filter dropdown: All | Pending | In Progress | Done\",\n        \"Filter persists in URL params\",\n        \"Typecheck passes\",\n        \"Verify in browser using dev-browser skill\"\n      ],\n      \"priority\": 4,\n      \"passes\": false,\n      \"notes\": \"\"\n    }\n  ]\n}\n```\n\n---\n\n## Archiving Previous Runs\n\n**Before writing a new prd.json, check if there is an existing one from a different feature:**\n\n1. Read the current `prd.json` if it exists\n2. Check if `branchName` differs from the new feature's branch name\n3. If different AND `progress.txt` has content beyond the header:\n   - Create archive folder: `archive/YYYY-MM-DD-feature-name/`\n   - Copy current `prd.json` and `progress.txt` to archive\n   - Reset `progress.txt` with fresh header\n\n**The ralph.sh script handles this automatically** when you run it, but if you are manually updating prd.json between runs, archive first.\n\n---\n\n## Checklist Before Saving\n\nBefore writing prd.json, verify:\n\n- [ ] **Previous run archived** (if prd.json exists with different branchName, archive it first)\n- [ ] Each story is completable in one iteration (small enough)\n- [ ] Stories are ordered by dependency (schema to backend to UI)\n- [ ] Every story has \"Typecheck passes\" as criterion\n- [ ] UI stories have \"Verify in browser using dev-browser skill\" as criterion\n- [ ] Acceptance criteria are verifiable (not vague)\n- [ ] No story depends on a later story\n"
  }
]