From 74e795462b24da153fd2e365a02643b6d801d5cf Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Thu, 7 May 2026 23:09:25 +0000 Subject: [PATCH 1/5] feat: Integrate Ralph Loop mechanism for automated app development - Adopted Ralph Loop pattern from ChristianKuri/ralph-and-opencode - Added `ralph.sh` script to orchestrate the loop execution - Added `.opencode/skills/` globally available OpenCode agent skills - Added `prompt.md` instructions and `prd.json.example` format definition - Updated `AGENTS.md` with instructions on how to use Ralph Loop Co-authored-by: Rishabh-Bajpai <28703138+Rishabh-Bajpai@users.noreply.github.com> --- .../skills/compound-engineering/SKILL.md | 250 +++++++++++++++++ .opencode/skills/dev-browser/SKILL.md | 52 ++++ .opencode/skills/frontend-design/SKILL.md | 39 +++ .opencode/skills/prd/SKILL.md | 242 ++++++++++++++++ .opencode/skills/ralph/SKILL.md | 259 ++++++++++++++++++ AGENTS.md | 31 ++- prd.json.example | 64 +++++ scripts/ralph/prompt.md | 116 ++++++++ scripts/ralph/ralph.sh | 193 +++++++++++++ 9 files changed, 1245 insertions(+), 1 deletion(-) create mode 100644 .opencode/skills/compound-engineering/SKILL.md create mode 100644 .opencode/skills/dev-browser/SKILL.md create mode 100644 .opencode/skills/frontend-design/SKILL.md create mode 100644 .opencode/skills/prd/SKILL.md create mode 100644 .opencode/skills/ralph/SKILL.md create mode 100644 prd.json.example create mode 100644 scripts/ralph/prompt.md create mode 100755 scripts/ralph/ralph.sh diff --git a/.opencode/skills/compound-engineering/SKILL.md b/.opencode/skills/compound-engineering/SKILL.md new file mode 100644 index 0000000..72b5aa0 --- /dev/null +++ b/.opencode/skills/compound-engineering/SKILL.md @@ -0,0 +1,250 @@ +--- +name: compound-engineering +description: "Compound Engineering workflow for AI-assisted development. Use when planning features, executing work, reviewing code, or codifying learnings. Follows the Plan → Work → Review → Compound loop where each unit of engineering makes subsequent work easier. Triggers on: plan this feature, implement this, review this code, compound learnings, create implementation plan, systematic development." +--- +This skill implements Compound Engineering—a development methodology where each unit of work makes subsequent work easier, not harder. Inspired by Every.to's engineering approach. + +## Core Philosophy + +**Each unit of engineering work should make subsequent units of work easier—not harder.** + +Traditional development accumulates technical debt. Every feature adds complexity. Every change increases maintenance burden. Compound engineering inverts this by creating a learning loop where each bug, failed test, or problem-solving insight gets documented and used by future work. + +## The Compound Engineering Loop + +``` +Plan → Work → Review → Compound → (repeat) +``` + +1. **Plan (40%)**: Research approaches, synthesize information into detailed implementation plans +2. **Work (20%)**: Execute the plan systematically with continuous validation +3. **Review (20%)**: Evaluate output quality and identify learnings +4. **Compound (20%)**: Feed results back into the system to make the next loop better + +80% of compound engineering is in planning and review. 20% is in execution. + +## Step 1: Plan + +Before writing any code, create a comprehensive plan. Good plans start with research: + +### Research Phase +1. **Codebase Analysis**: Search for similar patterns, conventions, and prior art in the codebase +2. **Commit History**: Use `git log` to understand how related features were built +3. **Documentation**: Check README, AGENTS.md, and inline documentation +4. **External Research**: Search for best practices relevant to the problem + +### Plan Document Structure +Create a plan document (markdown) with: + +```markdown +# Feature: [Name] + +## Context +- What problem does this solve? +- Who is affected? +- What's the current behavior vs desired behavior? + +## Research Findings +- Similar patterns found in codebase: [list with file links] +- Relevant prior implementations: [commit references] +- Best practices discovered: [external references] + +## Acceptance Criteria +- [ ] Criterion 1 (testable) +- [ ] Criterion 2 (testable) +- [ ] Criterion 3 (testable) + +## Technical Approach +1. Step 1: [specific action] +2. Step 2: [specific action] +3. Step 3: [specific action] + +## Code Examples +[Include code snippets that follow existing patterns] + +## Testing Strategy +- Unit tests: [what to test] +- Integration tests: [what to test] +- Manual verification: [steps] + +## Risks & Mitigations +- Risk 1: [mitigation] +- Risk 2: [mitigation] +``` + +### Detail Levels +- **Minimal**: Quick issues for simple features (1-2 hours work) +- **Standard**: Issues with technical considerations (1-2 days work) +- **Comprehensive**: Major features requiring architecture decisions (multi-day work) + +## Step 2: Work + +Execute the plan systematically: + +### Execution Workflow +1. **Create isolated environment**: Use feature branch or git worktree +2. **Break down into tasks**: Create TODO list from plan +3. **Execute systematically**: One task at a time +4. **Validate continuously**: Run tests after each change +5. **Commit incrementally**: Small, focused commits with clear messages + +### Working Principles +- Follow existing patterns discovered in research +- Run tests after every meaningful change +- If something fails, understand why before proceeding +- Keep changes focused—don't scope creep + +### Quality Checks During Work +```bash +# After each change, verify: +npm run typecheck # or equivalent +npm test # run affected tests +npm run lint # check code quality +``` + +## Step 3: Review + +Before merging, perform comprehensive review: + +### Review Checklist + +**Code Quality** +- [ ] Follows existing codebase patterns and conventions +- [ ] No unnecessary complexity—prefer duplication over wrong abstraction +- [ ] Clear naming that matches project conventions +- [ ] No debug code or console.logs left behind + +**Security** +- [ ] No secrets or sensitive data exposed +- [ ] Input validation where needed +- [ ] Safe handling of user data + +**Performance** +- [ ] No obvious performance regressions +- [ ] Database queries are efficient (no N+1) +- [ ] Appropriate caching if applicable + +**Testing** +- [ ] Tests cover acceptance criteria +- [ ] Edge cases considered +- [ ] Tests are maintainable, not brittle + +**Architecture** +- [ ] Change is consistent with system design +- [ ] No unnecessary coupling introduced +- [ ] Follows separation of concerns + +### Multi-Perspective Review +Consider the code from different angles: +- **Maintainer perspective**: Will this be easy to modify in 6 months? +- **Performance perspective**: Any bottlenecks? +- **Security perspective**: Any vulnerabilities? +- **Simplicity perspective**: Can this be simpler? + +## Step 4: Compound + +This is where the magic happens—capture learnings to make future work easier: + +### What to Compound + +**Patterns**: Document new patterns discovered or created +```markdown +## Pattern: [Name] +When to use: [context] +Implementation: [example code] +See: [file reference] +``` + +**Decisions**: Record why certain approaches were chosen +```markdown +## Decision: [Choice Made] +Context: [situation] +Options considered: [alternatives] +Rationale: [why this choice] +Consequences: [trade-offs] +``` + +**Failures**: Turn every bug into a lesson +```markdown +## Lesson: [What Went Wrong] +Symptom: [what was observed] +Root cause: [actual problem] +Fix: [solution] +Prevention: [how to avoid in future] +``` + +### Where to Codify Learnings + +1. **AGENTS.md**: Project-wide guidance that applies everywhere +2. **Subdirectory AGENTS.md**: Specific guidance for subsystems +3. **Inline comments**: Only when the code isn't self-explanatory +4. **Test cases**: Turn bugs into regression tests + +### Compounding in Practice + +After completing work, ask: +- What did I learn that others should know? +- What mistake did I make that can be prevented? +- What pattern did I discover or create? +- What decision was made and why? + +Document these in the appropriate location so future agents (and humans) benefit. + +## Practical Commands + +### Planning a Feature +``` +Plan implementation for: [describe feature] +- Research the codebase for similar patterns +- Check git history for related changes +- Create a detailed plan with acceptance criteria +- Include code examples that match existing patterns +``` + +### Executing Work +``` +Execute this plan: [plan reference] +- Create feature branch +- Break into TODO list +- Work through systematically +- Run tests after each change +- Create PR when complete +``` + +### Reviewing Code +``` +Review this change: [PR/diff reference] +- Check for code quality issues +- Look for security concerns +- Evaluate performance implications +- Verify test coverage +- Suggest improvements +``` + +### Compounding Learnings +``` +Compound learnings from: [work just completed] +- What patterns were used or created? +- What decisions were made and why? +- What failures occurred and how to prevent them? +- Update AGENTS.md with relevant guidance +``` + +## Key Principles + +1. **Prefer duplication over wrong abstraction**: Simple, clear code beats complex abstractions +2. **Document as you go**: Every command generates documentation that makes future work easier +3. **Quality compounds**: High-quality code is easier to modify +4. **Systematic beats heroic**: Consistent processes beat individual heroics +5. **Knowledge should be codified**: Learnings should be captured and reused + +## Success Metrics + +You're doing compound engineering well when: +- Each feature takes less effort than the last similar feature +- Bugs become one-time events (documented and prevented) +- New team members can be productive quickly (institutional knowledge is accessible) +- Code reviews surface fewer issues (patterns are established and followed) +- Technical debt decreases over time (learnings compound) + +Remember: You're not just building features—you're building a development system that gets better with each use. \ No newline at end of file diff --git a/.opencode/skills/dev-browser/SKILL.md b/.opencode/skills/dev-browser/SKILL.md new file mode 100644 index 0000000..cc73e30 --- /dev/null +++ b/.opencode/skills/dev-browser/SKILL.md @@ -0,0 +1,52 @@ +--- +name: dev-browser +description: "Use Chrome DevTools MCP for browser-based verification, UI regression checks, screenshots, console/network inspection, and quick performance traces. Trigger when verifying frontend changes in a live browser, capturing evidence, or debugging client-side issues." +license: MIT +compatibility: opencode +--- + +# Dev Browser (Chrome DevTools MCP) + +Use the Chrome DevTools MCP tools to verify UI changes, capture evidence, and inspect console/network state. + +## When to use +- Verify frontend changes in a live browser +- Capture viewport or full-page screenshots +- Inspect console errors/warnings +- Inspect network requests and responses +- Run quick performance traces + +## Preconditions +- Chrome is installed and reachable by the MCP server +- MCP is configured in `~/.config/opencode/opencode.json` +- Prefer headless mode for automation +- Avoid sensitive data in the browser session + +## Standard workflow +1. Discover or select a page: + - `list_pages` + - `select_page` (if needed) +2. Navigate: + - `new_page` or `navigate_page` +3. Wait for stability: + - `wait_for` (use a key selector or page-ready signal) +4. Capture evidence: + - `take_screenshot` (set `fullPage: true` for full page) + - `take_snapshot` for DOM snapshot +5. Debug: + - `list_console_messages` + - `list_network_requests` → `get_network_request` for details + +## Performance (optional) +- `performance_start_trace` +- Interact or wait for the target state +- `performance_stop_trace` +- `performance_analyze_insight` + +## Output expectations +- Provide screenshot path or attached image +- Summarize console and network findings +- Note any errors and next checks + +## Quick example +Use the dev-browser skill to verify `/en/games/...` renders correctly, capture a full-page screenshot, and confirm there are no console errors. diff --git a/.opencode/skills/frontend-design/SKILL.md b/.opencode/skills/frontend-design/SKILL.md new file mode 100644 index 0000000..3def23c --- /dev/null +++ b/.opencode/skills/frontend-design/SKILL.md @@ -0,0 +1,39 @@ +--- +name: frontend-design +description: "Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics." +license: Complete terms in LICENSE.txt +--- +This skill guides creation of distinctive, production-grade frontend interfaces that avoid generic "AI slop" aesthetics. Implement real working code with exceptional attention to aesthetic details and creative choices. + +The user provides frontend requirements: a component, page, application, or interface to build. They may include context about the purpose, audience, or technical constraints. + +## Design Thinking +Before coding, understand the context and commit to a BOLD aesthetic direction: +- **Purpose**: What problem does this interface solve? Who uses it? +- **Tone**: Pick an extreme: brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian, etc. There are so many flavors to choose from. Use these for inspiration but design one that is true to the aesthetic direction. +- **Constraints**: Technical requirements (framework, performance, accessibility). +- **Differentiation**: What makes this UNFORGETTABLE? What's the one thing someone will remember? + +**CRITICAL**: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity. + +Then implement working code (HTML/CSS/JS, React, Vue, etc.) that is: +- Production-grade and functional +- Visually striking and memorable +- Cohesive with a clear aesthetic point-of-view +- Meticulously refined in every detail + +## Frontend Aesthetics Guidelines +Focus on: +- **Typography**: Choose fonts that are beautiful, unique, and interesting. Avoid generic fonts like Arial and Inter; opt instead for distinctive choices that elevate the frontend's aesthetics; unexpected, characterful font choices. Pair a distinctive display font with a refined body font. +- **Color & Theme**: Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes. +- **Motion**: Use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (animation-delay) creates more delight than scattered micro-interactions. Use scroll-triggering and hover states that surprise. +- **Spatial Composition**: Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density. +- **Backgrounds & Visual Details**: Create atmosphere and depth rather than defaulting to solid colors. Add contextual effects and textures that match the overall aesthetic. Apply creative forms like gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, and grain overlays. + +NEVER use generic AI-generated aesthetics like overused font families (Inter, Roboto, Arial, system fonts), cliched color schemes (particularly purple gradients on white backgrounds), predictable layouts and component patterns, and cookie-cutter design that lacks context-specific character. + +Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. NEVER converge on common choices (Space Grotesk, for example) across generations. + +**IMPORTANT**: Match implementation complexity to the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well. + +Remember: Claude is capable of extraordinary creative work. Don't hold back, show what can truly be created when thinking outside the box and committing fully to a distinctive vision. \ No newline at end of file diff --git a/.opencode/skills/prd/SKILL.md b/.opencode/skills/prd/SKILL.md new file mode 100644 index 0000000..42e2480 --- /dev/null +++ b/.opencode/skills/prd/SKILL.md @@ -0,0 +1,242 @@ +--- +name: prd +description: "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." +license: MIT +compatibility: opencode +--- + +# PRD Generator + +Create detailed Product Requirements Documents that are clear, actionable, and suitable for implementation. + +--- + +## The Job + +1. Receive a feature description from the user +2. Ask 3-5 essential clarifying questions (with lettered options) +3. Generate a structured PRD based on answers +4. Save to `tasks/prd-[feature-name].md` + +**Important:** Do NOT start implementing. Just create the PRD. + +--- + +## Step 1: Clarifying Questions + +Ask only critical questions where the initial prompt is ambiguous. Focus on: + +- **Problem/Goal:** What problem does this solve? +- **Core Functionality:** What are the key actions? +- **Scope/Boundaries:** What should it NOT do? +- **Success Criteria:** How do we know it's done? + +### Format Questions Like This: + +``` +1. What is the primary goal of this feature? + A. Improve user onboarding experience + B. Increase user retention + C. Reduce support burden + D. Other: [please specify] + +2. Who is the target user? + A. New users only + B. Existing users only + C. All users + D. Admin users only + +3. What is the scope? + A. Minimal viable version + B. Full-featured implementation + C. Just the backend/API + D. Just the UI +``` + +This lets users respond with "1A, 2C, 3B" for quick iteration. + +--- + +## Step 2: PRD Structure + +Generate the PRD with these sections: + +### 1. Introduction/Overview +Brief description of the feature and the problem it solves. + +### 2. Goals +Specific, measurable objectives (bullet list). + +### 3. User Stories +Each story needs: +- **Title:** Short descriptive name +- **Description:** "As a [user], I want [feature] so that [benefit]" +- **Acceptance Criteria:** Verifiable checklist of what "done" means + +Each story should be small enough to implement in one focused session. + +**Format:** +```markdown +### US-001: [Title] +**Description:** As a [user], I want [feature] so that [benefit]. + +**Acceptance Criteria:** +- [ ] Specific verifiable criterion +- [ ] Another criterion +- [ ] Typecheck/lint passes +- [ ] **[UI stories only]** Verify in browser using dev-browser skill +``` + +**Important:** +- Acceptance criteria must be verifiable, not vague. "Works correctly" is bad. "Button shows confirmation dialog before deleting" is good. +- **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. + +### 4. Functional Requirements +Numbered list of specific functionalities: +- "FR-1: The system must allow users to..." +- "FR-2: When a user clicks X, the system must..." + +Be explicit and unambiguous. + +### 5. Non-Goals (Out of Scope) +What this feature will NOT include. Critical for managing scope. + +### 6. Design Considerations (Optional) +- UI/UX requirements +- Link to mockups if available +- Relevant existing components to reuse + +### 7. Technical Considerations (Optional) +- Known constraints or dependencies +- Integration points with existing systems +- Performance requirements + +### 8. Success Metrics +How will success be measured? +- "Reduce time to complete X by 50%" +- "Increase conversion rate by 10%" + +### 9. Open Questions +Remaining questions or areas needing clarification. + +--- + +## Writing for Junior Developers + +The PRD reader may be a junior developer or AI agent. Therefore: + +- Be explicit and unambiguous +- Avoid jargon or explain it +- Provide enough detail to understand purpose and core logic +- Number requirements for easy reference +- Use concrete examples where helpful + +--- + +## Output + +- **Format:** Markdown (`.md`) +- **Location:** `tasks/` +- **Filename:** `prd-[feature-name].md` (kebab-case) + +--- + +## Example PRD + +```markdown +# PRD: Task Priority System + +## Introduction + +Add 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. + +## Goals + +- Allow assigning priority (high/medium/low) to any task +- Provide clear visual differentiation between priority levels +- Enable filtering and sorting by priority +- Default new tasks to medium priority + +## User Stories + +### US-001: Add priority field to database +**Description:** As a developer, I need to store task priority so it persists across sessions. + +**Acceptance Criteria:** +- [ ] Add priority column to tasks table: 'high' | 'medium' | 'low' (default 'medium') +- [ ] Generate and run migration successfully +- [ ] Typecheck passes + +### US-002: Display priority indicator on task cards +**Description:** As a user, I want to see task priority at a glance so I know what needs attention first. + +**Acceptance Criteria:** +- [ ] Each task card shows colored priority badge (red=high, yellow=medium, gray=low) +- [ ] Priority visible without hovering or clicking +- [ ] Typecheck passes +- [ ] Verify in browser using dev-browser skill + +### US-003: Add priority selector to task edit +**Description:** As a user, I want to change a task's priority when editing it. + +**Acceptance Criteria:** +- [ ] Priority dropdown in task edit modal +- [ ] Shows current priority as selected +- [ ] Saves immediately on selection change +- [ ] Typecheck passes +- [ ] Verify in browser using dev-browser skill + +### US-004: Filter tasks by priority +**Description:** As a user, I want to filter the task list to see only high-priority items when I'm focused. + +**Acceptance Criteria:** +- [ ] Filter dropdown with options: All | High | Medium | Low +- [ ] Filter persists in URL params +- [ ] Empty state message when no tasks match filter +- [ ] Typecheck passes +- [ ] Verify in browser using dev-browser skill + +## Functional Requirements + +- FR-1: Add `priority` field to tasks table ('high' | 'medium' | 'low', default 'medium') +- FR-2: Display colored priority badge on each task card +- FR-3: Include priority selector in task edit modal +- FR-4: Add priority filter dropdown to task list header +- FR-5: Sort by priority within each status column (high to medium to low) + +## Non-Goals + +- No priority-based notifications or reminders +- No automatic priority assignment based on due date +- No priority inheritance for subtasks + +## Technical Considerations + +- Reuse existing badge component with color variants +- Filter state managed via URL search params +- Priority stored in database, not computed + +## Success Metrics + +- Users can change priority in under 2 clicks +- High-priority tasks immediately visible at top of lists +- No regression in task list performance + +## Open Questions + +- Should priority affect task ordering within a column? +- Should we add keyboard shortcuts for priority changes? +``` + +--- + +## Checklist + +Before saving the PRD: + +- [ ] Asked clarifying questions with lettered options +- [ ] Incorporated user's answers +- [ ] User stories are small and specific +- [ ] Functional requirements are numbered and unambiguous +- [ ] Non-goals section defines clear boundaries +- [ ] Saved to `tasks/prd-[feature-name].md` diff --git a/.opencode/skills/ralph/SKILL.md b/.opencode/skills/ralph/SKILL.md new file mode 100644 index 0000000..b6ff530 --- /dev/null +++ b/.opencode/skills/ralph/SKILL.md @@ -0,0 +1,259 @@ +--- +name: ralph +description: "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." +license: MIT +compatibility: opencode +--- + +# Ralph PRD Converter + +Converts existing PRDs to the prd.json format that Ralph uses for autonomous execution. + +--- + +## The Job + +Take a PRD (markdown file or text) and convert it to `prd.json` in your ralph directory. + +--- + +## Output Format + +```json +{ + "project": "[Project Name]", + "branchName": "ralph/[feature-name-kebab-case]", + "description": "[Feature description from PRD title/intro]", + "userStories": [ + { + "id": "US-001", + "title": "[Story title]", + "description": "As a [user], I want [feature] so that [benefit]", + "acceptanceCriteria": [ + "Criterion 1", + "Criterion 2", + "Typecheck passes" + ], + "priority": 1, + "passes": false, + "notes": "" + } + ] +} +``` + +--- + +## Story Size: The Number One Rule + +**Each story must be completable in ONE Ralph iteration (one context window).** + +Ralph spawns a fresh OpenCode 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. + +### Right-sized stories: +- Add a database column and migration +- Add a UI component to an existing page +- Update a server action with new logic +- Add a filter dropdown to a list + +### Too big (split these): +- "Build the entire dashboard" - Split into: schema, queries, UI components, filters +- "Add authentication" - Split into: schema, middleware, login UI, session handling +- "Refactor the API" - Split into one story per endpoint or pattern + +**Rule of thumb:** If you cannot describe the change in 2-3 sentences, it is too big. + +--- + +## Story Ordering: Dependencies First + +Stories execute in priority order. Earlier stories must not depend on later ones. + +**Correct order:** +1. Schema/database changes (migrations) +2. Server actions / backend logic +3. UI components that use the backend +4. Dashboard/summary views that aggregate data + +**Wrong order:** +1. UI component (depends on schema that does not exist yet) +2. Schema change + +--- + +## Acceptance Criteria: Must Be Verifiable + +Each criterion must be something Ralph can CHECK, not something vague. + +### Good criteria (verifiable): +- "Add `status` column to tasks table with default 'pending'" +- "Filter dropdown has options: All, Active, Completed" +- "Clicking delete shows confirmation dialog" +- "Typecheck passes" +- "Tests pass" + +### Bad criteria (vague): +- "Works correctly" +- "User can do X easily" +- "Good UX" +- "Handles edge cases" + +### Always include as final criterion: +``` +"Typecheck passes" +``` + +For stories with testable logic, also include: +``` +"Tests pass" +``` + +### For stories that change UI, also include: +``` +"Verify in browser using dev-browser skill" +``` + +Frontend 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. + +--- + +## Conversion Rules + +1. **Each user story becomes one JSON entry** +2. **IDs**: Sequential (US-001, US-002, etc.) +3. **Priority**: Based on dependency order, then document order +4. **All stories**: `passes: false` and empty `notes` +5. **branchName**: Derive from feature name, kebab-case, prefixed with `ralph/` +6. **Always add**: "Typecheck passes" to every story's acceptance criteria + +--- + +## Splitting Large PRDs + +If a PRD has big features, split them: + +**Original:** +> "Add user notification system" + +**Split into:** +1. US-001: Add notifications table to database +2. US-002: Create notification service for sending notifications +3. US-003: Add notification bell icon to header +4. US-004: Create notification dropdown panel +5. US-005: Add mark-as-read functionality +6. US-006: Add notification preferences page + +Each is one focused change that can be completed and verified independently. + +--- + +## Example + +**Input PRD:** +```markdown +# Task Status Feature + +Add ability to mark tasks with different statuses. + +## Requirements +- Toggle between pending/in-progress/done on task list +- Filter list by status +- Show status badge on each task +- Persist status in database +``` + +**Output prd.json:** +```json +{ + "project": "TaskApp", + "branchName": "ralph/task-status", + "description": "Task Status Feature - Track task progress with status indicators", + "userStories": [ + { + "id": "US-001", + "title": "Add status field to tasks table", + "description": "As a developer, I need to store task status in the database.", + "acceptanceCriteria": [ + "Add status column: 'pending' | 'in_progress' | 'done' (default 'pending')", + "Generate and run migration successfully", + "Typecheck passes" + ], + "priority": 1, + "passes": false, + "notes": "" + }, + { + "id": "US-002", + "title": "Display status badge on task cards", + "description": "As a user, I want to see task status at a glance.", + "acceptanceCriteria": [ + "Each task card shows colored status badge", + "Badge colors: gray=pending, blue=in_progress, green=done", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 2, + "passes": false, + "notes": "" + }, + { + "id": "US-003", + "title": "Add status toggle to task list rows", + "description": "As a user, I want to change task status directly from the list.", + "acceptanceCriteria": [ + "Each row has status dropdown or toggle", + "Changing status saves immediately", + "UI updates without page refresh", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 3, + "passes": false, + "notes": "" + }, + { + "id": "US-004", + "title": "Filter tasks by status", + "description": "As a user, I want to filter the list to see only certain statuses.", + "acceptanceCriteria": [ + "Filter dropdown: All | Pending | In Progress | Done", + "Filter persists in URL params", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 4, + "passes": false, + "notes": "" + } + ] +} +``` + +--- + +## Archiving Previous Runs + +**Before writing a new prd.json, check if there is an existing one from a different feature:** + +1. Read the current `prd.json` if it exists +2. Check if `branchName` differs from the new feature's branch name +3. If different AND `progress.txt` has content beyond the header: + - Create archive folder: `archive/YYYY-MM-DD-feature-name/` + - Copy current `prd.json` and `progress.txt` to archive + - Reset `progress.txt` with fresh header + +**The ralph.sh script handles this automatically** when you run it, but if you are manually updating prd.json between runs, archive first. + +--- + +## Checklist Before Saving + +Before writing prd.json, verify: + +- [ ] **Previous run archived** (if prd.json exists with different branchName, archive it first) +- [ ] Each story is completable in one iteration (small enough) +- [ ] Stories are ordered by dependency (schema to backend to UI) +- [ ] Every story has "Typecheck passes" as criterion +- [ ] UI stories have "Verify in browser using dev-browser skill" as criterion +- [ ] Acceptance criteria are verifiable (not vague) +- [ ] No story depends on a later story diff --git a/AGENTS.md b/AGENTS.md index 357e59a..0692d94 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,4 +38,33 @@ cp .env.example .env - Frontend: Vite + React 18 + TypeScript - Backend: Flask + Flask-SQLAlchemy + SQLite (default) -- DB override: Set `DATABASE_URL` in `.env` for PostgreSQL \ No newline at end of file +- DB override: Set `DATABASE_URL` in `.env` for PostgreSQL# Ralph Agent Instructions + +## Overview + +Ralph is an autonomous AI agent loop that runs OpenCode repeatedly until all PRD items are complete. Each iteration is a fresh OpenCode instance with clean context. + +## Commands + +```bash +# Run Ralph (from your project that has prd.json) +./ralph.sh [max_iterations] +``` + +## Key Files + +- `ralph.sh` - The bash loop that spawns fresh OpenCode instances +- `prompt.md` - Instructions given to each OpenCode instance +- `prd.json.example` - Example PRD format + +## Patterns + +- Each iteration spawns a fresh OpenCode instance with clean context +- Memory persists via git history, `progress.txt`, and `prd.json` +- Stories should be small enough to complete in one context window +- Always update AGENTS.md with discovered patterns for future iterations + +## Codebase Patterns +- Follow Telegram-like UI fidelity patterns from the referenced series where compatible with PRD scope. +- Do not add out-of-scope features (multi-user chat, group chat, video/audio calling). +- Keep Linux as the only supported host OS. diff --git a/prd.json.example b/prd.json.example new file mode 100644 index 0000000..fbc4066 --- /dev/null +++ b/prd.json.example @@ -0,0 +1,64 @@ +{ + "project": "MyApp", + "branchName": "ralph/task-priority", + "description": "Task Priority System - Add priority levels to tasks", + "userStories": [ + { + "id": "US-001", + "title": "Add priority field to database", + "description": "As a developer, I need to store task priority so it persists across sessions.", + "acceptanceCriteria": [ + "Add priority column to tasks table: 'high' | 'medium' | 'low' (default 'medium')", + "Generate and run migration successfully", + "Typecheck passes" + ], + "priority": 1, + "passes": false, + "notes": "" + }, + { + "id": "US-002", + "title": "Display priority indicator on task cards", + "description": "As a user, I want to see task priority at a glance.", + "acceptanceCriteria": [ + "Each task card shows colored priority badge (red=high, yellow=medium, gray=low)", + "Priority visible without hovering or clicking", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 2, + "passes": false, + "notes": "" + }, + { + "id": "US-003", + "title": "Add priority selector to task edit", + "description": "As a user, I want to change a task's priority when editing it.", + "acceptanceCriteria": [ + "Priority dropdown in task edit modal", + "Shows current priority as selected", + "Saves immediately on selection change", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 3, + "passes": false, + "notes": "" + }, + { + "id": "US-004", + "title": "Filter tasks by priority", + "description": "As a user, I want to filter the task list to see only high-priority items.", + "acceptanceCriteria": [ + "Filter dropdown with options: All | High | Medium | Low", + "Filter persists in URL params", + "Empty state message when no tasks match filter", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 4, + "passes": false, + "notes": "" + } + ] +} diff --git a/scripts/ralph/prompt.md b/scripts/ralph/prompt.md new file mode 100644 index 0000000..298819f --- /dev/null +++ b/scripts/ralph/prompt.md @@ -0,0 +1,116 @@ +# Ralph Agent Instructions + +You are an autonomous coding agent working on a software project. + +## Your Task + +1. Read the PRD at `prd.json` (in the same directory as this file) +2. Read the progress log at `progress.txt` (check Codebase Patterns section first) +3. Check you're on the correct branch from PRD `branchName`. If not, check it out or create from main. +4. Pick the **highest priority** user story where `passes: false` +5. Implement that single user story using the compound loop below + - Load the `compound-engineering` skill + - Plan (40%): Research approaches, synthesize information into detailed implementation plans + - Work (20%): Execute the plan systematically with continuous validation + - Review (20%): Evaluate output quality and identify learnings + - Compound (20%): Feed results back into the system to make the next loop better + - Add or update tests required by the story +6. Run quality checks (e.g., typecheck, lint, test - use whatever your project requires) +7. Update AGENTS.md files if you discover reusable patterns (see below) +8. If checks pass, commit ALL changes with message: `feat: [Story ID] - [Story Title]` +9. Update the PRD to set `passes: true` for the completed story +10. Append your progress to `progress.txt` + +## Progress Report Format + +APPEND to progress.txt (never replace, always append): +``` +## [Date/Time] - [Story ID] +- What was implemented +- Files changed +- **Learnings for future iterations:** + - Patterns discovered (e.g., "this codebase uses X for Y") + - Gotchas encountered (e.g., "don't forget to update Z when changing W") + - Useful context (e.g., "the evaluation panel is in component X") +--- +``` + +The learnings section is critical - it helps future iterations avoid repeating mistakes and understand the codebase better. + +## Consolidate Patterns + +If 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: + +``` +## Codebase Patterns +- Example: Use `sql` template for aggregations +- Example: Always use `IF NOT EXISTS` for migrations +- Example: Export types from actions.ts for UI components +``` + +Only add patterns that are **general and reusable**, not story-specific details. + +## Update AGENTS.md Files + +Before committing, check if any edited files have learnings worth preserving in nearby AGENTS.md files: + +1. **Identify directories with edited files** - Look at which directories you modified +2. **Check for existing AGENTS.md** - Look for AGENTS.md in those directories or parent directories +3. **Add valuable learnings** - If you discovered something future developers/agents should know: + - API patterns or conventions specific to that module + - Gotchas or non-obvious requirements + - Dependencies between files + - Testing approaches for that area + - Configuration or environment requirements + +**Examples of good AGENTS.md additions:** +- "When modifying X, also update Y to keep them in sync" +- "This module uses pattern Z for all API calls" +- "Tests require the dev server running on PORT 3000" +- "Field names must match the template exactly" + +**Do NOT add:** +- Story-specific implementation details +- Temporary debugging notes +- Information already in progress.txt + +Only update AGENTS.md if you have **genuinely reusable knowledge** that would help future work in that directory. + +## Quality Requirements + +- ALL commits must pass your project's quality checks (typecheck, lint, test) +- Do NOT commit broken code +- Keep changes focused and minimal +- Follow existing code patterns + +## Browser Testing (Required for Frontend Stories) + +For any story that changes UI, you MUST verify it works in the browser: + +1. Load the `dev-browser` skill +2. Navigate to the relevant page +3. Verify the UI changes work as expected +4. Take a screenshot if helpful for the progress log + +A frontend story is NOT complete until browser verification passes. + +### Dev Browser MCP Notes +- Use Chrome DevTools MCP tools through the `dev-browser` skill. +- Default flow: `list_pages` → `navigate_page`/`new_page` → `wait_for` → `take_screenshot`. +- Always check `list_console_messages`; inspect requests with `list_network_requests` if needed. + +## Stop Condition + +After completing a user story, check if ALL stories have `passes: true`. + +If ALL stories are complete and passing, reply with: +COMPLETE + +If there are still stories with `passes: false`, end your response normally (another iteration will pick up the next story). + +## Important + +- Work on ONE story per iteration +- Commit frequently +- Keep CI green +- Read the Codebase Patterns section in progress.txt before starting diff --git a/scripts/ralph/ralph.sh b/scripts/ralph/ralph.sh new file mode 100755 index 0000000..27e41d4 --- /dev/null +++ b/scripts/ralph/ralph.sh @@ -0,0 +1,193 @@ +#!/bin/bash +# Ralph Wiggum - Long-running AI agent loop +# Usage: ./ralph.sh [max_iterations] + +set -e + +MAX_ITERATIONS=${1:-10} +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PRD_FILE="$SCRIPT_DIR/prd.json" +PROGRESS_FILE="$SCRIPT_DIR/progress.txt" +ARCHIVE_DIR="$SCRIPT_DIR/archive" +LAST_BRANCH_FILE="$SCRIPT_DIR/.last-branch" +LOG_DIR="${RALPH_LOG_DIR:-$SCRIPT_DIR/logs}" +ITERATION_TIMEOUT_SECONDS="${RALPH_ITERATION_TIMEOUT_SECONDS:-7200}" +MAX_STAGNANT_ITERATIONS="${RALPH_MAX_STAGNANT_ITERATIONS:-5}" +STAGNANT_COUNT=0 + +get_passed_count() { + if [ ! -f "$PRD_FILE" ]; then + echo "-1" + return + fi + + local count + count=$(jq -r '[.userStories[]? | select(.passes == true)] | length' "$PRD_FILE" 2>/dev/null || true) + if [ -z "$count" ]; then + echo "-1" + else + echo "$count" + fi +} + +get_remaining_count() { + if [ ! -f "$PRD_FILE" ]; then + echo "-1" + return + fi + + local count + count=$(jq -r '[.userStories[]? | select(.passes != true)] | length' "$PRD_FILE" 2>/dev/null || true) + if [ -z "$count" ]; then + echo "-1" + else + echo "$count" + fi +} + +# Archive previous run if branch changed +if [ -f "$PRD_FILE" ] && [ -f "$LAST_BRANCH_FILE" ]; then + CURRENT_BRANCH=$(jq -r '.branchName // empty' "$PRD_FILE" 2>/dev/null || echo "") + LAST_BRANCH=$(cat "$LAST_BRANCH_FILE" 2>/dev/null || echo "") + + if [ -n "$CURRENT_BRANCH" ] && [ -n "$LAST_BRANCH" ] && [ "$CURRENT_BRANCH" != "$LAST_BRANCH" ]; then + # Archive the previous run + DATE=$(date +%Y-%m-%d) + # Strip "ralph/" prefix from branch name for folder + FOLDER_NAME=$(echo "$LAST_BRANCH" | sed 's|^ralph/||') + ARCHIVE_FOLDER="$ARCHIVE_DIR/$DATE-$FOLDER_NAME" + + echo "Archiving previous run: $LAST_BRANCH" + mkdir -p "$ARCHIVE_FOLDER" + [ -f "$PRD_FILE" ] && cp "$PRD_FILE" "$ARCHIVE_FOLDER/" + [ -f "$PROGRESS_FILE" ] && cp "$PROGRESS_FILE" "$ARCHIVE_FOLDER/" + echo " Archived to: $ARCHIVE_FOLDER" + + # Reset progress file for new run + echo "# Ralph Progress Log" > "$PROGRESS_FILE" + echo "Started: $(date)" >> "$PROGRESS_FILE" + echo "---" >> "$PROGRESS_FILE" + fi +fi + +# Track current branch +if [ -f "$PRD_FILE" ]; then + CURRENT_BRANCH=$(jq -r '.branchName // empty' "$PRD_FILE" 2>/dev/null || echo "") + if [ -n "$CURRENT_BRANCH" ]; then + echo "$CURRENT_BRANCH" > "$LAST_BRANCH_FILE" + fi +fi + +# Initialize progress file if it doesn't exist +if [ ! -f "$PROGRESS_FILE" ]; then + echo "# Ralph Progress Log" > "$PROGRESS_FILE" + echo "Started: $(date)" >> "$PROGRESS_FILE" + echo "---" >> "$PROGRESS_FILE" +fi + +echo "Starting Ralph - Max iterations: $MAX_ITERATIONS" + +mkdir -p "$LOG_DIR" + +MODEL_FLAGS=(--model=claude-3-5-sonnet-20241022) + +TIMEOUT_CMD=() +TIMEOUT_ENABLED=0 +if [[ "$ITERATION_TIMEOUT_SECONDS" =~ ^[0-9]+$ ]] && [ "$ITERATION_TIMEOUT_SECONDS" -gt 0 ]; then + if command -v timeout >/dev/null 2>&1; then + TIMEOUT_CMD=(timeout "$ITERATION_TIMEOUT_SECONDS") + TIMEOUT_ENABLED=1 + else + echo "Warning: 'timeout' not found; running without per-iteration timeout." + fi +else + ITERATION_TIMEOUT_SECONDS=0 +fi + +if ! [[ "$MAX_STAGNANT_ITERATIONS" =~ ^[0-9]+$ ]]; then + MAX_STAGNANT_ITERATIONS=5 +fi + +OPENCODE_CMD=(opencode run "${MODEL_FLAGS[@]}") +if [ "$TIMEOUT_ENABLED" -eq 1 ]; then + RUN_CMD=("${TIMEOUT_CMD[@]}" "${OPENCODE_CMD[@]}") +else + RUN_CMD=("${OPENCODE_CMD[@]}") +fi + +for i in $(seq 1 $MAX_ITERATIONS); do + echo "" + echo "═══════════════════════════════════════════════════════" + echo " Ralph Iteration $i of $MAX_ITERATIONS" + echo "═══════════════════════════════════════════════════════" + + PASSED_BEFORE=$(get_passed_count) + ITERATION_LOG="$LOG_DIR/iteration-$i.log" + echo " Log: $ITERATION_LOG" + + # Run opencode with the ralph prompt + # Use 'opencode run' for non-interactive execution (not just 'opencode' which launches TUI) + # Use Google model if available, otherwise use default + set +e + "${RUN_CMD[@]}" < "$SCRIPT_DIR/prompt.md" 2>&1 | tee "$ITERATION_LOG" | tee /dev/stderr + RUN_STATUS=${PIPESTATUS[0]} + set -e + + if [ "$TIMEOUT_ENABLED" -eq 1 ] && [ "$RUN_STATUS" -eq 124 ]; then + { + echo "## $(date) - Iteration $i" + echo "- Iteration timed out after ${ITERATION_TIMEOUT_SECONDS}s." + echo "- Log: $ITERATION_LOG" + echo "---" + } >> "$PROGRESS_FILE" + fi + + TOKEN_SEEN=0 + if grep -q "COMPLETE" "$ITERATION_LOG"; then + TOKEN_SEEN=1 + fi + + REMAINING_COUNT=$(get_remaining_count) + if [ "$REMAINING_COUNT" -eq 0 ]; then + echo "" + echo "Ralph completed all tasks!" + echo "Completed at iteration $i of $MAX_ITERATIONS" + exit 0 + fi + + if [ "$TOKEN_SEEN" -eq 1 ]; then + echo "Completion signal detected, but PRD still has remaining stories." + fi + + PASSED_AFTER=$(get_passed_count) + if [ "$PASSED_BEFORE" -ge 0 ] && [ "$PASSED_AFTER" -ge 0 ]; then + if [ "$PASSED_AFTER" -gt "$PASSED_BEFORE" ]; then + STAGNANT_COUNT=0 + else + STAGNANT_COUNT=$((STAGNANT_COUNT + 1)) + fi + else + echo "Warning: Unable to read prd.json for progress detection." + fi + + if [ "$MAX_STAGNANT_ITERATIONS" -gt 0 ] && [ "$STAGNANT_COUNT" -ge "$MAX_STAGNANT_ITERATIONS" ]; then + { + echo "## $(date) - Ralph stopped" + echo "- Reason: No progress for ${STAGNANT_COUNT} consecutive iterations." + echo "- Log: $ITERATION_LOG" + echo "---" + } >> "$PROGRESS_FILE" + echo "" + echo "Ralph stopped due to repeated non-progress iterations." + echo "Check $PROGRESS_FILE and $ITERATION_LOG for details." + exit 1 + fi + + echo "Iteration $i complete. Continuing..." + sleep 2 +done + +echo "" +echo "Ralph reached max iterations ($MAX_ITERATIONS) without completing all tasks." +echo "Check $PROGRESS_FILE for status." +exit 1 From 69b03cd0c06bb945b733d68103d8c01f568646a0 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Fri, 8 May 2026 00:46:02 +0000 Subject: [PATCH 2/5] feat: Integrate Ralph Loop mechanism for automated app development - Adopted Ralph Loop pattern from ChristianKuri/ralph-and-opencode - Added `ralph.sh` script to orchestrate the loop execution - Added `.opencode/skills/` globally available OpenCode agent skills - Added `prompt.md` instructions and `prd.json.example` format definition - Updated `AGENTS.md` with instructions on how to use Ralph Loop - Added UI checkboxes to "Create Chat Project" modals to scaffold Ralph Loop - Backend copies Ralph Loop files securely without using shell subprocesses Co-authored-by: Rishabh-Bajpai <28703138+Rishabh-Bajpai@users.noreply.github.com> --- backend/app/routes.py | 31 +++++++++++++++++++++++++++++++ frontend/src/App.tsx | 20 ++++++++++++++++++++ frontend/src/api.ts | 1 + 3 files changed, 52 insertions(+) diff --git a/backend/app/routes.py b/backend/app/routes.py index 0d0132e..f8a1747 100644 --- a/backend/app/routes.py +++ b/backend/app/routes.py @@ -1518,6 +1518,37 @@ def create_project(): db.session.add(project) db.session.commit() + use_ralph_loop = body.get("useRalphLoop", False) + if use_ralph_loop: + import shutil + import stat + import logging + try: + # Backend runs from repo root or backend dir + # Try to locate the source template files + repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + src_scripts = os.path.join(repo_root, "scripts", "ralph") + src_prd = os.path.join(repo_root, "prd.json.example") + + if not os.path.exists(src_scripts): + # fallback + src_scripts = os.path.abspath(os.path.join("scripts", "ralph")) + src_prd = os.path.abspath("prd.json.example") + + target_scripts = os.path.join(normalized_path, "scripts", "ralph") + os.makedirs(target_scripts, exist_ok=True) + + shutil.copy(os.path.join(src_scripts, "ralph.sh"), os.path.join(target_scripts, "ralph.sh")) + shutil.copy(os.path.join(src_scripts, "prompt.md"), os.path.join(target_scripts, "prompt.md")) + shutil.copy(src_prd, os.path.join(normalized_path, "prd.json")) + + ralph_sh_path = os.path.join(target_scripts, "ralph.sh") + st = os.stat(ralph_sh_path) + os.chmod(ralph_sh_path, st.st_mode | stat.S_IEXEC) + except Exception as e: + # Proceed anyway if we fail + logging.error(f"Failed to initialize Ralph Loop: {e}") + try: _ensure_project_session(project, opencode_client) except Exception as exc: diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 9e8e7cc..3dc864e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -3218,6 +3218,7 @@ export function App() { const [newProjectName, setNewProjectName] = useState(""); const [newProjectRootPath, setNewProjectRootPath] = useState(""); const [newProjectPath, setNewProjectPath] = useState(""); + const [createWithRalph, setCreateWithRalph] = useState(false); const [defaultProjectRoot, setDefaultProjectRoot] = useState(""); const [projectSearch, setProjectSearch] = useState(""); const [highlightedProjectId, setHighlightedProjectId] = useState(null); @@ -5795,6 +5796,7 @@ export function App() { await createProject({ name: trimmedProjectName, path: targetProjectPath, + useRalphLoop: createWithRalph, }); setNewProjectName(""); setNewProjectRootPath(preferredProjectRoot); @@ -6335,6 +6337,14 @@ export function App() { placeholder={preferredProjectRoot || "Project root path"} /> {preferredProjectRoot ? Root path: {preferredProjectRoot} : null} +
+
+ +
+ {ralphPanel ? ralphPanel : null} + {loading ?

Loading tasks...

: null} {error ?

{error}

: null} @@ -3149,6 +3156,106 @@ function ChatStateCard({ ); } +const RALPH_TASK_INSTRUCTION = `Read prd.json in this project's root directory. If prd.json does not exist, reply with GOAL_MET: yes. + +Find the highest priority user story where passes is false (lowest priority number). Implement that single story: +- Plan the approach before writing code +- Make the required changes following existing code patterns +- Run any available quality checks (tests, typecheck, lint) +- Commit all changes with message: feat: [story-id] - [story-title] +- Update prd.json to set passes: true for the completed story + +At the end of your response include exactly one of: +GOAL_MET: yes (if all stories now have passes: true) +GOAL_MET: no (if there are still stories with passes: false)`; + +const RALPH_GOAL_DEFINITION = "All user stories in prd.json have passes: true"; + +function RalphLoopPanel({ + prdData, + prdLoading, + prdError, + prdInitializing, + onInitPrd, + onCreateRalphTask, +}: { + prdData: PrdData | null; + prdLoading: boolean; + prdError: string | null; + prdInitializing: boolean; + onInitPrd: () => Promise; + onCreateRalphTask: () => void; +}) { + const totalStories = prdData?.userStories?.length ?? 0; + const passedStories = prdData?.userStories?.filter((s) => s.passes).length ?? 0; + const allDone = totalStories > 0 && passedStories === totalStories; + + return ( +
+
+

Ralph Loop

+
+ PRD Tracker + {prdData ? ( + + {passedStories}/{totalStories} + + ) : null} +
+
+ + {prdLoading ?

Loading PRD…

: null} + {prdError ?

{prdError}

: null} + + {!prdLoading && !prdData ? ( +
+

No prd.json found in this project.

+ +
+ ) : null} + + {prdData ? ( + <> +
    + {prdData.userStories.map((story) => ( +
  • + + {story.passes ? "✓" : story.id} + + + {story.title} + +
  • + ))} +
+ {!allDone ? ( + + ) : ( +

All stories complete 🎉

+ )} + + ) : null} +
+ ); +} + + function EmptyState() { return ( (null); @@ -3313,6 +3419,11 @@ export function App() { const [taskPreviewRuns, setTaskPreviewRuns] = useState([]); const [taskEnabledInput, setTaskEnabledInput] = useState(true); + const [prdData, setPrdData] = useState(null); + const [prdLoading, setPrdLoading] = useState(false); + const [prdError, setPrdError] = useState(null); + const [prdInitializing, setPrdInitializing] = useState(false); + const [opencodeStatus, setOpencodeStatus] = useState("checking..."); const [schedulerStatus, setSchedulerStatus] = useState(null); const [schedulerLoading, setSchedulerLoading] = useState(false); @@ -5022,6 +5133,49 @@ export function App() { } } + async function loadProjectPrd(projectId: string) { + setPrdLoading(true); + setPrdError(null); + try { + const result = await fetchProjectPrd(projectId); + setPrdData(result.prd); + } catch (error) { + setPrdError(error instanceof Error ? error.message : "Failed to load PRD"); + setPrdData(null); + } finally { + setPrdLoading(false); + } + } + + async function handleInitPrd() { + if (!activeProjectId) { + return; + } + setPrdInitializing(true); + setPrdError(null); + try { + const result = await initProjectPrd(activeProjectId); + setPrdData(result.prd); + } catch (error) { + setPrdError(error instanceof Error ? error.message : "Failed to create PRD"); + } finally { + setPrdInitializing(false); + } + } + + function handleCreateRalphTask() { + resetTaskForm(); + setTaskNameInput("Ralph Loop"); + setTaskDescriptionInput("Autonomous PRD agent: completes user stories one at a time."); + setTaskTypeInput("goal"); + setTaskInstructionInput(RALPH_TASK_INSTRUCTION); + setTaskGoalInput(RALPH_GOAL_DEFINITION); + setTaskIntervalInput(15); + setTaskEnabledInput(true); + setTaskAutoDisableOnGoalMetInput(true); + setTaskHeartbeatInput(false); + } + function scheduleStreamRefresh(projectId: string) { if (refreshDebounceRef.current !== null) { window.clearTimeout(refreshDebounceRef.current); @@ -5210,12 +5364,15 @@ export function App() { setSelectedProjectFileContent(null); setProjectFileContentError(null); setProjectFileContentLoading(false); + setPrdData(null); + setPrdError(null); return; } void loadTaskDetails(activeProjectId); void loadProjectRuntime(activeProjectId); void loadProjectSessions(activeProjectId); + void loadProjectPrd(activeProjectId); projectFileDirectoryRequestsRef.current.clear(); setProjectFileEntries([]); setProjectFilesTruncated(false); @@ -5796,7 +5953,6 @@ export function App() { await createProject({ name: trimmedProjectName, path: targetProjectPath, - useRalphLoop: createWithRalph, }); setNewProjectName(""); setNewProjectRootPath(preferredProjectRoot); @@ -6337,14 +6493,6 @@ export function App() { placeholder={preferredProjectRoot || "Project root path"} /> {preferredProjectRoot ? Root path: {preferredProjectRoot} : null} -
-
- -