Ralph loop

From dannys-code-corner/incan · View interactive version

Ralph loop is an AI agent skill from the GitHub repository dannys-code-corner/incan. Run a high-thoroughness end-to-end implementation loop using clean worker worktrees, per-slice planning, implementation, explicit review/fix iteration, orchestrator integration, and final commit/PR drafting. Use when the user explicitly wants a Ralph/Wiggum-style loop, autonomous multi-agent executi

How to use this skill

Skill file

Ralph Loop

Use this skill when the user wants more than basic delegation. The goal is not "parallelize some work"; the goal is to carry a scoped task through planning, implementation, review, integration, and ship-ready artifacts with explicit backpressure.

Keep orchestrate-parallel-work generic. Use this skill as the opinionated wrapper around it.

Core stance

PDCA model

ralph-loop is a plan -> do -> check -> act loop, not a linear pipeline.

Use these meanings consistently:

Important:

Scope and state isolation

Every Ralph loop must have a persisted loop identity before workers are spawned or resumed. Record it in the orchestrator overview and use it to filter durable state:

Use STATE_ROOT to mean the active loop's state directory. For new loops, prefer a namespaced root:

.agents/state/ralph-loop/<loop-id>/

Legacy top-level state such as .agents/state/ralph-loop/slices.json may be read for migration or handoff, but must not silently drive a new loop unless its recorded loop identity matches the current request.

On every resume, stop-hook continuation, compaction, or long-running restart:

  1. Re-read the latest user instruction.
  2. Re-read STATE_ROOT/overview.md, STATE_ROOT/slices.json, and .agents/state/review-report.md.
  3. Compare persisted loop identity to the latest user instruction.
  4. Classify each slice as:
  1. Schedule only in_scope implementation slices.

Out-of-scope or historical slices may be cited as background evidence, but they must not be advanced, committed, pushed, or turned into PRs from the current loop. If the user wants to pick them up, start or resume a separate Ralph loop with its own loop identity.

Consumer repositories such as IncQL may be used to reproduce, verify, or acceptance-test an Incan compiler/runtime change only when listed as a verification lane. Adding product features, docs CI, repo automation, or cleanup in that consumer repo is a separate implementation loop unless the user explicitly asks for it.

When not to use this skill

Do not use this for:

Workflow

0. RFC intake mode

If the user feeds the loop an RFC, enter RFC intake mode before ordinary execution.

In RFC intake mode:

  1. Run review-rfc on the RFC and apply direct fixes.
  2. Inspect Status: and the design tail honestly.
  3. If unresolved questions remain, summarize them and ask the user before bumping anything.
  4. Check for process blockers that require user input, such as:
  1. If the RFC is still Draft and design is settled, use bump-rfc to move it to Planned.
  2. If implementation is actually being picked up now, use bump-rfc to move it to In Progress. For this skill, the parent Ralph loop itself counts as "a contributor has picked up the work"; a child loop does not need its own PR or branch-level ceremony.
  3. Use the RFC's Implementation Plan and Progress Checklist as the source of truth for implementation phases. If they are missing or weak, strengthen them before spawning workers.
  4. Establish the docs/version baseline up front: verify the repo's actual dev version from the source-of-truth metadata, identify which user-facing docs must change if the feature lands, and do not assume an older release line from stale release notes or worker worktrees.

Do not quietly force an RFC past open design questions. Stop and ask the user.

1. Confirm the scope

Restate the requested end-state before starting execution. Confirm:

If scope is ambiguous, stop and ask a short numbered list of missing decisions.

After confirming scope, write the loop identity into STATE_ROOT/overview.md before creating or resuming slices. If existing durable state lacks a matching loop identity, do not continue it as part of this loop.

2. Pick the execution backend

Default to Codex subagents plus git worktrees under WORKTREE_ROOT.

Resolve WORKTREE_ROOT once at the start of the loop and record its absolute path in STATE_ROOT/overview.md. It is the primary repository's shared sibling tmp/ directory. RALPH_WORKTREE_ROOT is only an assertion of that location: if it resolves elsewhere, stop rather than silently accepting another root. In particular, never use the system temporary directory as a worktree or durable build-output root.

COMMON_GIT_DIR="$(git rev-parse --path-format=absolute --git-common-dir)"
WORKSPACE_ROOT="$(dirname "$(dirname "$COMMON_GIT_DIR")")"
EXPECTED_WORKTREE_ROOT="$WORKSPACE_ROOT/tmp"
mkdir -p "$EXPECTED_WORKTREE_ROOT"
EXPECTED_WORKTREE_ROOT="$(cd "$EXPECTED_WORKTREE_ROOT" && pwd -P)"
if [ -n "${RALPH_WORKTREE_ROOT:-}" ]; then
  [ -d "$RALPH_WORKTREE_ROOT" ] || {
    echo "RALPH_WORKTREE_ROOT must already be $EXPECTED_WORKTREE_ROOT" >&2
    exit 2
  }
  [ "$(cd "$RALPH_WORKTREE_ROOT" && pwd -P)" = "$EXPECTED_WORKTREE_ROOT" ] || {
    echo "RALPH_WORKTREE_ROOT must be $EXPECTED_WORKTREE_ROOT" >&2
    exit 2
  }
fi
WORKTREE_ROOT="$EXPECTED_WORKTREE_ROOT"

git-common-dir keeps the default stable when the loop runs from a linked worktree.

Before creating a worktree, and before every command that can perform a substantial build, enforce the storage boundary:

  1. Record du -sk "$WORKTREE_ROOT", df -k "$WORKSPACE_ROOT", and the primary repository's git worktree list --porcelain inventory in STATE_ROOT/storage-ledger.md.
  2. Record every Ralph-owned output path in that ledger, including CARGO_TARGET_DIR, generated SDK/provider caches, package/distribution output, and test fixtures that copy repositories or build trees.
  3. Put each such path under WORKTREE_ROOT, normally under a loop-specific .ralph-cache/<loop-id>/ directory. Do not rely on a tool's default temporary path.
  4. Treat 20 GiB as a hard combined ceiling for all Ralph-owned material in WORKTREE_ROOT. If the ledger or measured root is at the ceiling, do not start another build; first retire an already-integrated Ralph worktree/cache, or report a concrete blocker. Never solve this by moving output to /tmp or /private/tmp.

For every build/test command, set CARGO_TARGET_DIR and TMPDIR to that slice's owned locations. Set any project-specific output variables too (for example, TOOLCHAIN_DIST for Incan's release-toolchain smoke commands). The ledger must distinguish retained worktrees from reclaimable targets/caches and must name the owner slice. Any primary-repository worktree outside WORKTREE_ROOT is legacy or foreign and must be explicitly recorded; a Ralph-owned one is a cleanup blocker, not a reason to create another outside-root worktree. git worktree remove alone is not cleanup when a worker placed output in a separate cache directory.

If the user explicitly wants OpenCode:

If OpenCode is requested but unavailable, say so plainly and either stop or fall back to Codex only with the user's approval.

3. Prepare the orchestration boundary

Use start-work once at the orchestration boundary to resolve issue/RFC context, branch naming, and relevant learnings.

Do not mechanically run start-work inside every worker unless each worker owns a distinct issue or RFC. The important requirement is a clean worktree plus resolved context, not duplicated branch ceremony.

Create WORKTREE_ROOT first if it does not exist.

Create:

Create durable slice state under each worktree. The paths below are relative to STATE_ROOT; for new loops STATE_ROOT should normally be .agents/state/ralph-loop/<loop-id>:

Treat the slice folder as the source of truth for that slice. Do not rely on memory or only on conversational context.

Use these files deliberately:

Base all worker worktrees from the same resolved starting point unless there is a deliberate dependency chain.

For non-decomposed work, the single-agent implementation still belongs in a fresh worktree under WORKTREE_ROOT; "keep the work local" does not mean "edit the primary checkout directly."

Before spawning workers, identify:

For milestone, RFC-wide, or compiler-boundary work, also write an ## Acceptance Contract section into STATE_ROOT/overview.md before implementation starts. Include:

Do not defer this acceptance contract to release-branch closeout. The release branch should verify the contract, not discover it.

Do not treat RFC edits or release notes alone as sufficient user documentation.

4. Decide whether parallelism is justified

Before spawning workers, decide whether the task actually decomposes cleanly. If it does not, keep the work local and continue as a single-agent Ralph loop.

When it does decompose, hand off to orchestrate-parallel-work for slice definition, ownership, and worktree isolation under WORKTREE_ROOT. Pass the resolved WORKTREE_ROOT, loop-specific .ralph-cache/<loop-id>/ root, and 20 GiB ceiling as mandatory inputs; the delegated orchestrator and workers must not recompute or override their own temporary root.

If the task came from an RFC:

For each slice, create tasks.md with explicit task items. Keep them concrete and finishable, not vague “phase done” markers.

Also create tasks.json for the same slice. tasks.json is the authoritative status surface; tasks.md is the human-readable companion.

Suggested shape:

{
  "slice_id": "lifecycle-env",
  "status": "planned",
  "tasks": [
    {
      "id": "T1",
      "title": "Establish manifest/env schema ownership boundary",
      "status": "todo",
      "notes": ""
    },
    {
      "id": "T2",
      "title": "Remove CLI-local env schema parsing",
      "status": "todo",
      "notes": ""
    }
  ]
}

Example shape:

# Slice Tasks — lifecycle-env

- [ ] Establish manifest/env schema ownership boundary
- [ ] Remove CLI-local env schema parsing
- [ ] Add internal manifest override discovery
- [ ] Make env overlays affect nested `incan lock`
- [ ] Add focused tests
- [ ] Run slice verification
- [ ] Run slice review/fix loop

Subagents should work tasks to completion against these files and update them as state changes.

The orchestrator should maintain slices.json with entries like:

[
  {
    "loop_id": "incan-557-std-environ",
    "slice_id": "lifecycle-env",
    "repo": "encero-systems/incan",
    "scope_role": "implementation",
    "owner": "<worker name or id>",
    "worktree": "<WORKTREE_ROOT>/...",
    "status": "doing",
    "next_action": "Implement T2"
  }
]

Use scope_role: "verification" for downstream acceptance lanes. Verification slices may run checks and collect evidence, but they must not mutate consumer product code unless the loop identity explicitly allows cross-repo implementation.

5. Give each worker a strict end-to-end contract

Each worker must own a non-overlapping slice with:

For RFC-driven work, prefer one child loop per implementation phase or tightly related checklist group.

Each worker must perform this loop inside its slice:

  1. Plan
  1. Do
  1. Check
  1. Act
  1. Repeat until:

or report a concrete blocker with its classification.

The slice's .agents/state/review-report.md must be kept current throughout this loop.

The slice folder under STATE_ROOT/<slice-id>/ must also stay current throughout this loop.

Allowed slice states:

Do not invent vague alternatives like “mostly done” or “almost ready”.

Workers must be told:

Require every worker to return the shape in reference.md.

6. Integrate centrally

The orchestrator owns integration. Workers do not integrate each other.

The orchestrator must:

The orchestrator worktree's .agents/state/review-report.md is the integration source of truth.

The orchestrator's STATE_ROOT/overview.md is the integration state source of truth.

Worker cleanup is part of integration, not optional closeout. For every slice marked done:

  1. Confirm handoff.md, the worker changed-file list, and the accepted patch are reflected in the orchestrator worktree.
  2. Run the relevant integrated verification before removing the worker sandbox.
  3. Record integration metadata in slices.json, such as integrated_at, integrated_by, and worktree_removed.
  4. If the worker worktree is clean, remove it with git worktree remove <worker-path>.
  5. If the worker worktree is dirty only because of files already integrated into the orchestrator branch or task-owned scratch state, record the inventory in overview.md or slices.json, then remove that Ralph-owned worker worktree with git worktree remove --force <worker-path>.
  6. Remove the slice's Ralph-owned target/cache/output paths from WORKTREE_ROOT/.ralph-cache/<loop-id>/<slice-id>/, then update STATE_ROOT/storage-ledger.md with the reclaimed size. Do not remove an unowned path or a path with unknown contents.
  7. After the worktree is removed, delete the disposable worker branch only when it is task-owned and the orchestrator branch contains the accepted work.

Do not force-remove a worker worktree with unknown or unintegrated changes. Do not push while accepted slice work exists only in a worker worktree or worker branch.

STEERING.md must be checked at the start of every major iteration. If it changes the priority, scope, or urgency of the work, the orchestrator must update slices.json, affected scope.md / tasks.json, and continue from the new direction rather than pretending the original ordering still applies.

If STEERING.md or a resume hook mentions slices from another loop identity, treat them as out of scope until the user explicitly says to resume that separate loop.

Do not stop at "worker green." Cross-slice regressions and consistency problems belong to the orchestrator.

7. Finish with ship-ready artifacts

When code is ready:

For RFC-driven work, only the parent loop drafts or owns the final PR description. Child loops must not produce PRs of their own.

If the user says "greenlight for PR", "green light for PR", or otherwise approves PR publication for RFC-driven work, treat RFC finalization as part of the pre-PR gate. Before reporting the branch ready for review or opening/marking a PR ready:

Do not leave a fully implemented RFC in In Progress while presenting the PR as review-ready. Do not use Refs #NNN as an escape hatch for RFC-driven Ralph-loop work unless the user explicitly changed the scope to a partial implementation. If the branch implements only part of the RFC, say that directly, leave the RFC active, and do not present the PR as a full-RFC closeout.

The orchestrator runs the commit, push, and PR flow itself once the integrated gate passes. Do not leave finished, verified work uncommitted.

Quality bar

Treat these as default expectations, not optional polish:

If the task teaches a durable lesson about orchestration, testing, or worktree hygiene, consider add-learning before finishing.

Relationship to other skills

Nesting rule

Use this shape:

Do not recurse ralph-loop indefinitely. A child loop is a phase owner, not another top-level orchestrator.

Validation checklist

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.