RaphaelLoop
Treat the user's complete request as one goal. Preserve its objective, constraints, exclusions, approval boundaries, and stop conditions across every iteration.
Use this flow:
text
Goal -> Contract -> Baseline -> Task DAG -> Bounded work -> Independent verification -> Checkpoint -> Terminal decision
Do not start an open-ended loop. Convert ambiguous persistence such as “keep going,” “make it good,” or “until done” into observable predicates and finite limits first.
1. Admit or decline the loop
Start RaphaelLoop only when all of these are true:
- The goal can be evaluated by a repeatable command, query, inspection, or measurable artifact.
- Work can be split into increments that fit within one iteration.
- Scope, prohibited changes, and approval boundaries are known.
- At least one finite iteration, time, token, cost, or deadline limit exists.
Use a disclosed default limit of 10 iterations only when the goal, scope, verifier, and approval boundary are already valid. Route one-step work to a normal task instead of creating loop state.
Decline the loop when success depends entirely on taste, required evidence is unavailable, continuous monitoring has no finite boundary, or the requested automation would perform unapproved irreversible actions.
2. Select one host protocol
Identify the current host and keep it fixed for the goal:
| Host | Skill location | Agent destination | Bundled protocol |
|---|
| Codex | ~/.codex/skills/raphael-loop
| | |
| Claude Code | ~/.claude/skills/raphael-loop
| | |
Resolve
from the absolute path of this loaded
; do not assume the consumer project's working directory contains RaphaelLoop scripts. The host role health check is required before Agent dispatch in
or
. Skip it for read-only
and
unless the user explicitly asks to audit host registration:
bash
bash "$SKILL_DIR/scripts/install-agents.sh" --harness <codex-or-claude> --check
Interpret exit codes exactly:
- : continue.
- : run the installer with , report every host-level target, obtain explicit approval, then run it without and check again. Stop as if approval is unavailable.
- : correct the host argument or ask one focused question if the host cannot be identified.
- : run , explain which host-level files would be backed up or replaced, and obtain explicit approval before refreshing them. Check again after refresh; otherwise stop before dispatch.
- : report an invalid bundled Agent set and stop.
The installer must use only files inside this Skill. Do not download an Agent catalog or substitute remote instructions.
Treat bundled Agent files as a separate host-level lifecycle from the Skill directory. A Skills CLI update or removal does not refresh or remove them automatically.
- For a requested refresh, run , obtain explicit approval for the reported targets, run the installer, and finish with .
- Before removing the Skill, run , report the exact managed files, obtain explicit approval, then run . Tell the user to remove the Skill with their package manager only after this succeeds.
- If uninstall returns , do not delete or overwrite anything. The files differ from the current manifest; require review or an approved refresh first.
- Never remove backup directories automatically.
3. Select one operating mode
Choose exactly one mode before loading or mutating loop state:
| Mode | Use when | Allowed behavior |
|---|
| The user needs a governed loop definition before execution. | Inspect read-only context, compile and validate a contract, explain risks; do not initialize state or change the project. |
| The user authorizes implementation toward the contract. | Initialize or resume state, claim work, implement, verify, checkpoint, recover, and decide. |
| A prior loop was interrupted or compacted. | Load state, run an integrity audit, preserve counters and verified tasks, then continue only from the runnable frontier. |
| The user needs a review of a contract, loop state, or evidence. | Run or and report gaps; do not dispatch Agents, execute task deliverables, or change state. |
Infer
only when the request clearly authorizes changes. Use
for planning requests and
for review requests. A status request remains read-only. Do not turn an audit into implementation.
4. Compile the executable goal contract
Create a JSON contract using examples/runtime-contract.json, then validate it before changing the project. Load references/runtime.md when constructing fields or operating the kernel.
text
schema_version, goal_id, objective, success_mode,
scope.allowed, scope.prohibited,
predicates[id, kind, command[], timeout_seconds, runs, required_passes],
limits[max_iterations, max_minutes, max_tokens, max_cost, max_recoveries, max_stalls],
approval_gates,
tasks[id, deliverable, depends_on, scope, predicate_ids, rollback_plan, side_effects]
Require an objective, scope, at least one predicate, fixed verifier argument arrays, a finite value for every limit, and a predicate-linked acyclic task graph. Ask one question that removes the largest blocking ambiguity when any required field cannot be derived safely.
Do not accept subjective predicates such as
,
, or
. A count-only request succeeds after the requested count; report quality metrics separately instead of inventing a quality claim.
Verifier commands must be arrays, never shell strings. Side effects require a declared approval gate and idempotency key, but the runtime never executes them. In
, run
python3 "$SKILL_DIR/scripts/raphael_loop.py" validate --contract /absolute/contract.json
; this validates without creating consumer state.
5. Initialize recoverable runtime state
Use the bundled zero-dependency Python kernel for every mechanical transition. Resolve it from the loaded Skill, not the consumer working directory:
bash
RAPHAEL_RUNTIME="$SKILL_DIR/scripts/raphael_loop.py"
python3 "$RAPHAEL_RUNTIME" init --contract /absolute/contract.json --project /absolute/project
Store active state at
.raphael-loop/<goal-id>/state.json
inside the consumer project. Add
to that project's ignore rules when appropriate. Do not hand-edit runtime state, counters, leases, evidence, hashes, or checkpoint snapshots.
The state records:
text
contract and hash; project root and baseline fingerprint;
status; task DAG; ownership leases; evidence ledger;
iteration, time, token, cost, recovery, and stall usage;
failure signatures; last verified checkpoint; transition events
resumes an existing state only when its contract hash matches. If it returns
, apply the
audit before claiming work. Never reset budget usage or repeat a verified task. A materially changed contract requires a new goal ID or an explicit retirement of the old state.
In
, run
and
before claiming work. In
, use
or
only. The runtime captures a project fingerprint and writes a checkpoint only after fresh verification so resumed work can distinguish delivery claims from accepted evidence.
6. Build the minimum task DAG
Work backward from the predicates:
- Add a baseline task for each verifier.
- Derive the smallest deliverables that can change a failing predicate.
- Connect real dependencies and expose the runnable frontier.
- Split oversized work into independently verifiable vertical increments.
- Use bounded read-only investigation tasks for unknowns.
- Delete tasks that do not affect a predicate or remove a blocking dependency.
Every task must include:
text
id, deliverable, dependencies, acceptance, allowed_scope,
capability, risk, status, owner, evidence
Use only
,
,
,
,
, or
as task status. Move a task to
only after its acceptance check passes.
7. Route the built-in roles
Use these protocol-equivalent roles:
| Role | Responsibility |
|---|
| Maintain contract, limits, checkpoints, progress, and terminal decision. |
| Produce the minimum predicate-linked task DAG. |
| Assign runnable work with exclusive ownership. |
| Deliver one bounded task packet. |
| Independently evaluate the declared acceptance checks. |
| Turn a stable failure signature into one new recovery action or a stop recommendation. |
Prefer a host-provided specialist when its description directly matches the required capability. Use
when no specialist exists. Always retain
and an independent
.
Send every assigned Agent a compact packet containing:
text
contract summary, task id, current evidence, exclusive responsibility,
allowed scope, dependencies, acceptance command, expected return, prohibitions
Require each Agent to return
, changes or findings,
, and
. Do not send unrelated conversation history.
The Controller is the only role that requests terminal
; the Orchestrator requests
; the Worker reports a bounded outcome through
; the Verifier requests
; and Recovery requests
. Agents may propose transitions, but they must not simulate successful kernel output or edit state directly.
Run at most three workers concurrently and preserve one host slot for the root. Parallelize only tasks with disjoint files, external objects, dependencies, and mutable state. Sequence shared ownership and integration work.
8. Execute one bounded iteration
At each loop boundary:
- Refresh cancellation, limits, and predicate evidence.
- Apply terminal rules before spending another iteration.
- Select the smallest critical-path increment from the runnable frontier.
- Assign the minimum capable, non-conflicting Agent set.
- Let the root integrate results and resolve ownership conflicts.
- Ask to run the predeclared checks independently.
- Update the DAG, progress vector, failure signature, and checkpoint.
- Apply terminal rules again.
For the executable transitions, use:
bash
python3 "$RAPHAEL_RUNTIME" claim --state "$STATE" --task "$TASK" --owner "$OWNER"
python3 "$RAPHAEL_RUNTIME" record --state "$STATE" --task "$TASK" --owner "$OWNER" --outcome progress
python3 "$RAPHAEL_RUNTIME" verify --state "$STATE" --predicate "$PREDICATE"
python3 "$RAPHAEL_RUNTIME" checkpoint --state "$STATE" --task "$TASK" --owner "$OWNER"
python3 "$RAPHAEL_RUNTIME" decide --state "$STATE"
The root performs project edits through normal host tools between
and
. The kernel only governs state and declared verifiers. A checkpoint rejects evidence when any project file changes after verification.
Count one iteration from task selection through verification and checkpoint. Do not count a pure status check, approval wait, or recovery-state load as a new iteration.
Define measurable progress as at least one of:
- A success-predicate metric improves.
- A task passes its acceptance check.
- A blocking dependency is removed and independently verified.
Do not count elapsed time, code volume, Agent output, replanning, or unverified completion claims as progress.
9. Recover without retry loops
Normalize a failure signature as:
text
<verifier-name> + <exit-code-or-result> + <error-class>
On the first occurrence, preserve the raw evidence and assign
one targeted hypothesis. If the same signature returns after recovery and no new actionable evidence or alternative critical-path task exists, stop as
.
Record the recovery boundary with
python3 "$RAPHAEL_RUNTIME" retry ...
. The first matching signature permits one new action; its second matching occurrence blocks the task. The runtime records but never performs a rollback or side effect.
Stop as
after
two completed iterations leave the progress vector unchanged. Switch to a different runnable critical-path task once when evidence supports it; do not hide a stall with unrelated work.
Resume a blocked goal only after new evidence, permission, user input, or environment state changes the blocking condition. Preserve prior history and start a new recovery audit.
10. Apply deterministic terminal priority
Use this exact priority:
text
cancelled > succeeded > exhausted > blocked
- : the user cancels or replaces the goal.
- : the contract's or predicate combination is true in fresh independent evidence.
- : a finite limit is reached before success.
- : the stall or repeated-failure rule is met, or a required permission, input, tool, or dependency remains unavailable.
When success and a limit are reached in the same verified checkpoint, use
. Treat an unavailable, failed, or stale verifier as
, never as success.
Stop immediately after a terminal decision. Do not add optional cleanup or unrelated improvements after the goal ends.
11. Preserve authority and evidence
- Never expand the user's authorization because the work is iterative.
- Require approval for publishing, payment, deletion, production writes, permission elevation, and other irreversible effects.
- Preserve user-owned changes and declare file or object ownership before concurrent work.
- Never weaken tests, thresholds, or verifiers to make a predicate pass unless changing them is explicitly the goal.
- Never let the producer be the only verifier of its deliverable.
- Never describe or as success.
- Never execute a verifier through a shell or substitute an undeclared command at runtime.
- Treat verifier commands as trusted code with inherited host authority. Use reviewed project-local checks; the runtime kernel is not a sandbox and cannot guarantee cleanup of deliberately detached descendants.
- Treat evidence logs as potentially sensitive local artifacts; do not print credentials from verifier commands.
End with a terminal report containing the terminal state and reason, host, iterations and budget used, roles used, every predicate and its latest evidence, changed artifacts, validation results, remaining DAG or blocker when unfinished, and state-file path.
12. Load examples only when needed
- Runtime contract: examples/runtime-contract.json
- Test-repair loop: examples/repair-failing-tests.md
- Performance loop: examples/improve-performance.md
- Cross-layer delivery loop: examples/deliver-cross-layer-feature.md