# 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
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]
Thread: https://ampcode.com/threads/$AMP_CURRENT_THREAD_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")
---
```
Include the thread URL so future iterations can use the `read_thread` tool to reference previous work if needed.
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<number>` 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.
## Stop Condition
After completing a user story, check if ALL stories have `passes: true`.
If ALL stories are complete and passing, reply with:
<promise>COMPLETE</promise>
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
/goal Autonomously scan, plan, refactor, and fix all boolean naming, double negatives, mixed polarity, single-letter boolean parameters (v bool, b bool), bare verb/noun identifiers (stop bool -> isStopped bool, stopOnFail -> isStopOnFail), awkward isExists identifiers (isExists -> isDefined), compound negative chains (!a || !b || c -> discrete checks), and complex condition violations across the codebase, modifying source files directly to enforce affirmative prefixes (is and has only (can, should, was, etc. are banned)), implicit evaluation (no == true), positive framing (no !isSuccess), and discrete condition decomposition until 100% green without stopping
/loop 1h /triage (or self-paced, no interval; equivalently, "run wiki-linter for a full health-check pass"). Safe fully unattended: wiki-linter only writes to wiki/issues.md, never edits page content beyond mechanical frontmatter fixes, and never calls AskUserQuestion — every iteration completes without a human present
/goal Autonomously scan, plan, refactor, and verify all regular expression usage across the codebase, eliminating raw regexp.MustCompile and regexp.Compile outside package lazyregex, replacing inline compilation and blind re.MatchString test assertions with thread-safe lazyregex.New(...) and wrapped lazyregex.MatchResult(...) returning *MatchResult (ResultGroup) and structured *appfault.AppError diagnostics, enforcing affirmative evaluation (rs.IsMatch(), rs.IsSuccess(), rs.IsFailed()), and providing rich failure diagnostics showing pattern, compared text, character count, and failure cause until 100% green without stopping
/goal All tests under test/auth pass — show npm test -- test/auth exiting 0; git diff --stat lists only src/auth and no test file is modified; or stop after 15 turns
/loop 1h with a prompt that runs this tick. /loop works in local and cloud roots. Never leave the cadence to memory or lossy completion notifications. At each tick, re-read this playbook from trunk with git show origin/main:pstack/skills/poteto-mode/playbooks/autopilot-full.md and audit the operation against it. Fix drift during that tick. Probe each owner with a generic liveness or status check, and collect the decision trails. Count only side effects as progress: commits, pushes, PR or check deltas, and store reports. Treat a lane that errors, or that passes its expected runtime without a side effect, as stuck. Stand it down and dispatch a replacement at once. Do not wait for a polite return. The tick judges an owner by the pushed branch and the decision trail that step 2 requires, and it replaces an owner whose agent cannot start a turn. Each tick also runs the lane stuck test over the program's agent list, where the platform has one, and over every owner's children.tsv. Whether or not a stop works, the root has the owner record each stuck subagent as stuck and, if its work is still needed, replace it. Each replacement that stalls gets the same steps. The root takes both steps when the owner cannot. A stall never proves or drops the work. When merges batch, run a retro pass and a post-merge bot-comment sweep. End the tick only when no delegated work is left, even after the last merge
/goal The requested change is implemented, reviewed, verified by the project’s documented checks, and Claude has surfaced evidence in the transcript: changed files, commands run, exit codes, risks, rollback notes, and next steps. Stop after 20 turns if blocked or if progress stalls
Email is the missing tool in your harness. ConnectMyEmail gives Claude Code and Codex a clean MCP into Gmail, iCloud and IMAP — triage, drafts, follow-ups, on a loop.
/goal Take Story P2-2 (PNG-grounded PerceptionArtifact + standalone vision node) of Epic P2 from current state through full implementation, testing, and validation. Use spawned bmad-party-mode for the mandatory Tier-3 pre-dev green-light and for any major decision/impasse. Pre-author the spec + Codex dev-prompt; hand dev+test creation to the Codex agent; then run Claude T11 (bmad-code-review 3-lane + remediation + commit + flip done). The goal is accomplished when P2-2 is committed done on branch fidelity-perception-arc-2026-06-19 with the validation gates below all green
/goal Execute specs/03-ship.md (read it and BRIEF.md first). Write README.md and SECURITY.md per the spec, then run the full macro regression and attempt deploy. Final turn must contain ALL of: (a) npx tsc --noEmit output with exit code 0 stated; (b) npm test full output with exit 0; (c) against a running wrangler dev, quoted curl -sS output of GET /.well-known/oauth-authorization-server AND GET /.well-known/oauth-protected-resource, both returning JSON; (d) quoted curl -i POST /mcp with no Authorization header showing HTTP 401 and a WWW-Authenticate header; (e) quoted curl -i POST /token with Content-Type: application/x-www-form-urlencoded and a bogus grant showing an HTTP 4xx OAuth JSON error body (not 415, not 500); (f) ls README.md SECURITY.md output plus the quoted markdown headings of both files; (g) quoted grep output showing README.md contains the literal strings GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, ALLOWED_HOSTED_DOMAIN, /callback, and all three Google OAuth scope URLs from BRIEF.md; (h) EITHER wrangler deploy output plus quoted curl of the deployed /.well-known/oauth-authorization-server returning JSON, OR the literal line "DEPLOY BLOCKED: <reason>" followed by the exact commands for me to run; (i) the literal heading "HUMAN ACCEPTANCE CHECKLIST" followed by the human-only steps from specs/03-ship.md verbatim. Stop after 10 turns and output a status report if not complete
Refactor src/utils.js into focused modules under 200 lines each, keeping all exports and signatures intact, until npm run build and npm test both pass with matching test counts.
/goal src/utils.js is split into focused modules each under 200 lines with all imports updated, proven in the transcript by npm run build and npm test both exiting 0 with the same passing-test count as before. Do not change any exported function signature. Stop after 25 turns and report what remains
/goal Reproduce and fix the flaky checkout test so it passes 20 consecutive runs, verified by npm test -- checkout, while preserving checkout API behavior and existing correctness tests. Use the checkout test files, checkout service code, fixtures, and related logs. Between iterations, record the observed failure mode, hypothesis, change, and rerun result. If reproduction stays unavailable or valid paths are exhausted, stop with reproduction attempts, logs, most likely absent condition, blocker, and next input needed
/goal "…" works autonomously until the goal is done and verified, or reports exactly why it is blocked. Exits 0 or 2 in headless mode, so it works in CI. |
Run a full review pass inline, apply validated blocking findings at their owning layer, re-run fresh until the gate clears or blockers plateau—capped at 3 rounds with escalation.
/goal why-review fix-loop convergence: repeatedly run the full-mode /why-review pass INLINE over {target}. After each review, apply only VALIDATED findings that block the current round (all open severities in round 1 — Round-1 LOW closure; CRITICAL/HIGH/MEDIUM from round 2) at their owning layer, then re-run a FRESH full review pass over the CHANGED target. If the current round's blocking findings >0 → apply fixes and run another round; if a fresh full review pass clears the current bar (round 1: zero open findings; round 2: zero CRITICAL/HIGH/MEDIUM, LOW deferred) → CONVERGED, clear the gate. Do NOT open another round for LOW-only findings from round 2. Cap at {N=3} review rounds; a failing test gate is outside the cap and the no-progress rule — keep fixing and re-running until the tests pass, never forcing green; if review blockers do not shrink across 2 consecutive rounds or increase, or the review budget (round 3) is spent with review blockers still open → STOP and escalate via AskUserQuestion. Never loop open-ended
A second, read-only loop that babysits a first one. Every ten minutes it reads the run's state file and latest log, runs the test suite so its evidence is an exit code rather than a self-report, and applies four explicit escalation triggers (no progress across two checks, repeated identical stack trace, budget exceeded, merge-queue conflict). On any trigger it prints ESCALATE and stops so a human looks; it never restarts, edits, merges, or pushes. Exits when the state file reports PASS or DONE, and after twelve checks regardless. Adapted from ECC's loop-operator agent (affaan-m/ECC, MIT), which lists the same triggers but has no cadence, cap, check command, or exit.
/loop every 10 minutes act as the loop operator for the autonomous run in this repo: run `cat state/loops/*.md`, `tail -100 logs/latest.log`, and `npm test` each pass, then report the active loop pattern, current phase, last successful checkpoint, the npm test exit code, failing checks, and cost drift against the budget in the state file. Print ESCALATE and stop this loop if any of these is true: no progress across two consecutive checks, the same stack trace repeats, cost exceeds the budget, or a merge conflict is blocking the queue — escalate to me, never fix it yourself. Otherwise print CONTINUE with one line of evidence. Report-only: never edit code, never restart or kill processes, never merge or push — any PR the run opens waits for me. Exit when the state file says Status: PASS or DONE. Stop after 12 checks regardless.
A recurring six-phase check (build, types, lint, tests with coverage, secret and debug-log grep, diff size) that prints one fixed-format report every fifteen minutes so you catch drift before the PR, not in review. It is strictly read-only: the loop reports, you decide what to fix. It exits when the tests pass and the report reads READY twice running, escalates instead of retrying when the same check fails three times, and stops after eight checks no matter what. Adapted from ECC's verification-loop skill (affaan-m/ECC, MIT), whose 'continuous mode' names the cadence but has no turn cap, exit, or failure path; all three are added here.
/loop every 15 minutes while I work: run `npm run build`, `npx tsc --noEmit`, `npm run lint`, and `npm test -- --coverage`, then grep src/ for `sk-`, `api_key`, and `console.log`, then `git diff --stat`. Print a VERIFICATION REPORT with Build / Types / Lint / Tests (X/Y passed, Z% coverage) / Security / Diff as PASS or FAIL and an overall READY or NOT READY for PR verdict, plus an Issues to Fix list. Report only — never edit files, never commit. Exit when `npm test` exits 0 and the report says READY twice in a row. If the same check FAILs on three consecutive passes, stop and escalate to me with the failing output instead of retrying. Stop after 8 checks regardless.
Two reviewers from different model families, each in a fresh context, must both pass an objective rubric before a PR is opened — the maker-checker split with real model diversity. Each failed round fixes only what was flagged and re-reviews with reviewers that have no memory of the last round, so nothing anchors on prior findings. Hard cap of three rounds, tests may never be edited to pass, and the loop ends by opening a PR rather than pushing. Adapted from ECC's /santa-loop (affaan-m/ECC, MIT), which auto-pushes on agreement and has no verifiable exit; this version adds the test-exit condition and the human merge gate.
/goal Ship the current diff only after two independent reviewers both PASS. Scope is `git diff --name-only HEAD` (or the path in $ARGUMENTS). First write a rubric with objective PASS/FAIL criteria: correctness, security (no secrets, injection, OWASP top 10), error handling, completeness, internal consistency, no regressions. Each round launch two reviewers in parallel with fresh context and no memory of earlier rounds: Reviewer A is a Claude subagent, Reviewer B is a different model via `codex exec --sandbox read-only` (fall back to a second Claude subagent and say so in the report). Both return a JSON verdict with per-criterion PASS/FAIL and critical issues. If either FAILs: fix only the flagged issues with minimal diffs, never modify the tests to make them pass, commit "fix: address review findings (round N)", run `npm test`, and re-review with fresh reviewers. Exit when both reviewers PASS and `npm test` exits 0 — then open a PR for me to merge; never push to main or merge. Stop after 3 rounds; if still failing, print the unresolved issues and escalate to me instead of shipping.
Email is the missing tool in your harness. ConnectMyEmail gives Claude Code and Codex a clean MCP into Gmail, iCloud and IMAP — triage, drafts, follow-ups, on a loop.
The generic persistent-task Ralph pattern: iterate on one named task until its acceptance criteria are met and the suite is green, bounded by a 15-turn cap and a no-progress stop. Anti-reward-hacking clauses keep it from editing tests to go green, and it hands off via a PR instead of merging. Swap the check command for your stack's.
/loop Work the named task to completion. Each turn: pick the next incomplete subtask, make the smallest change that advances it, then run `npm test && npm run lint` and fix whatever breaks before moving on. Stop when every acceptance criterion for the task is met and `npm test` exits 0 — or stop after 15 turns, whichever comes first. Never modify, skip, or weaken a test to make it pass, never delete a failing assertion, and keep each diff minimal and scoped to the named task. If two consecutive turns produce no progress, stop and report what is blocking. When the task is done, open a pull request for review — never merge it yourself.
/goal until grep -q "users/:id/avatar" src/routes/users.ts AND pnpm test -- tests/integration/users.avatar.spec.ts passes AND grep -q "/users/{id}/avatar" openapi.yaml AND pnpm lint passes, or stop after 15 turns
/goal every task in .toh/plan.md is checked and the build command exits 0 — or stop after 40 turns . A Haiku evaluator judges the condition FROM THE TRANSCRIPT — one more reason the QC gate quotes actual output: unquoted results are invisible to the evaluator. |
/loop 2m Read tasks/qa-config.md to get the pre-QA test command and log command. Run the pre-QA test command. If it fails or any infrastructure issue is detected: read logs using the log command, diagnose the root cause, fix it, and re-run. Report to the user only when something fails or when all checks pass clean. Do not interrupt QA for passing tests
Shape and execute infrastructure readiness objectives by gathering evidence, seeking approval at decision boundaries, then validating provisioning, configuration, and rollback in non-production before production deployment.
/goal Use the installed shape-goal and goal-engine skills to discover, approve, and complete this repository's next Infrastructure / Deployment Readiness objective. During shaping, load shape-goal's required-input specification for Infrastructure / Deployment Readiness; exhaustively inspect repository instructions, Git state and history, infrastructure-as-code, environment and secret references, build artifacts, deployment workflows, health checks, runbooks, rollback paths, supported environments, prior incidents and goals, the project harness, and connected authoritative systems before asking the user. Resolve every material input from evidence where possible. Continue inside this /goal only when an already-approved Goal Contract or authoritative artifact resolves every owner decision. Otherwise create or resume SHAPING.md, save the unresolved decision and one recommended question, stop as Approval required, and tell the user to resume shape-goal outside /goal; do not ask the question or take another autonomous turn, and do not make production changes before approval. Then hand off within this same goal to goal-engine to reconcile infrastructure and application assumptions, validate provisioning and configuration in approved non-production or simulated environments, verify artifact provenance, migrations, smoke and health gates, observability, failure handling, and rollback, and remove verified readiness blockers; apply relevant assurance overlays, repository-native verification, regression protection, independent review where warranted, durable progress state, and reusable closeout. Do not declare success when shaping is complete. Finish only when every approved readiness gate passes with surfaced evidence, environment differences and residual risks are documented, rollback remains viable, and no production deployment or mutation has occurred without explicit authority. Stop only for a contract-defined blocker, approval boundary, budget, material goal drift, or two consecutive no-progress cycles
Discover and execute a benchmark optimization goal, freeze the protocol, compare candidates under identical conditions, and deploy only validated improvements with regression protection.
/goal Use the installed shape-goal and goal-engine skills to discover, approve, and complete this repository's next Measured Optimization / Benchmark objective. During shaping, load shape-goal's required-input specification for Measured Optimization / Benchmark; exhaustively inspect repository instructions, Git state and history, requirements, architecture, plans, tests and CI, runtime behavior, prior goal state, the project harness, and any connected authoritative sources before asking the user. Resolve every material input from evidence where possible; ask only unresolved owner decisions, one at a time with a recommended answer, and do not make production changes until the user approves a Goal Contract. Then hand off within this same goal to goal-engine to freeze the benchmark protocol, compare champion and challengers under identical conditions, and retain only meaningful improvements; apply relevant assurance overlays, repository-native verification, regression protection, independent review where warranted, durable progress state, and reusable closeout. Do not declare success when shaping is complete. Finish only when every approved acceptance and overlay gate passes with surfaced evidence and protected behavior has not regressed. Stop only for a contract-defined blocker, approval boundary, budget, material goal drift, or two consecutive no-progress cycles
/goal changes-review self-recursive loop: review the full diff → run /why-review --validate-findings on every finding → SELF-FIX each validated finding → restart /changes-review from Phase 0 over the WHOLE updated diff (combined with the prior fixes, not just the last fix) → loop until one complete review pass clears that round's bar (rounds 1-2: zero findings; round 3+: zero CRITICAL/HIGH/MEDIUM, a LOW-only round ENDS the loop with the LOWs recorded as deferred) → then run Phase 7.5: one standalone FULL-mode /why-review over the whole target+diff (NOT --validate-findings), fixing and re-running until it is clean → only then run the Phase 8 /docs-update. Do not stop while any validated finding is unfixed, any review pass is non-clean, or the holistic full-mode /why-review has unaddressed findings
/goal Implement every task in PLAN.md without stopping until pnpm test passes and pnpm build succeeds. Execution strategy: assess dependencies, shared context, write overlap, and independent verification before using subagents; keep final integration with the main agent. Surface each checkpoint with commands and exit codes. Pause for credentials, production data, or destructive actions
/ralph-loop "Refactor codebase to use TypeScript. Output COMPLETE when all files converted and tests pass." --completion-promise "COMPLETE" --max-iterations 100
Email is the missing tool in your harness. ConnectMyEmail gives Claude Code and Codex a clean MCP into Gmail, iCloud and IMAP — triage, drafts, follow-ups, on a loop.