# Run Loop

Execute the accepted plan as a control loop. Preserve outcomes and constraints, enforce the persisted ownership profile, and adapt helper missions to current evidence and capabilities.

## 1. Orient

Resolve and report the exact loop root, repository root, Beads epic, coordinator identity, branch, HEAD, loaded skill path, and generated adapter identity. Then read Beads, `IMPLEMENT.md`, `loop-state.md`, `runtime/generation.json`, `runtime/activation.json`, `runtime/binding.json`, Pi-only `runtime/adapter.json` when present, and the selected phase doc. Validate every deterministic generated artifact hash in the generation manifest. Validate the mutable `loop-state.md` mirror against Beads semantics instead of expecting it in the generation hash. Stop on the wrong checkout, a loaded-skill closure mismatch, a mixed generation, or an unknown builder contract. `run` reports the separate repair action; it never updates, converts, migrates, regenerates, or synchronizes itself.

Before a declared builder bootstrap completes, when the repository contains `bin/skills.js`, run `node bin/skills.js doctor` and require the active stable Dirtyloops install to report `source parity: current`. In another repository, require equivalent loaded-source identity evidence or block; a matching harness-reference hash alone does not prove the full control surface. After bootstrap, do not compare the installed frozen builder with the moving candidate source. Instead require the B8/B9 verifier to prove the loaded install against immutable `runtime/builder-certificate.json` and mutable `runtime/builder-activation.json`. Missing certificate-aware verification blocks; it never falls back to source parity or installs candidate code.

When the chosen strategy uses an adapter, ask the bound certified adapter for its runtime manifest, validate it against `runtime-capabilities.schema.json`, and require its harness, captured loaded-adapter closure, coordinator identity, and adapter contract to match the binding and generated adapter policy. Ask the bound certified adapter for its runtime manifest before every delegated launch; cached product names or version guesses are not evidence.

For Pi, when activation is not `ready` for the current generation and coordinator, call `dirtyloops_runtime` with `action=activate` and the absolute loop `doc_root`. A same-session coordinator, including one that only ran `/reload`, must be rejected. From a fresh Pi session, launch the exact read-only vanilla session challenge returned by the adapter, wait for its production completion callback, and acknowledge its exact handle and nonce. The acknowledgement finalizes `runtime/activation.json`; do not claim phase ownership or perform real work before it reports `ready`.

Codex has no injected Dirtyloops adapter closure to reload, so material generation writes activation `ready` with first-party builder evidence. This means the generated builder control plane is current; it does not certify a Program runtime adapter. At every run, prove the capabilities required by the chosen strategy. An adaptive direct strategy may proceed without a separate owner adapter only after exact root, prepared worktree, symbolic branch, HEAD, status, and exclusive coordinator ownership are proved. Mutable delegated owners remain blocked without a certified launch and recovery adapter. An `orchestrator-callback` profile blocks unless separate sessions and structured completion are currently certified.

Then inspect current repo, branch, worktree, model, reasoning, delegation, concurrency, and session capabilities.

Read `Execution profile` from generated state and require Beads, `IMPLEMENT.md`, `loop-state.md`, and the run prompt to agree. Do not reinterpret an explicit `orchestrator-callback` profile as adaptive.

Select one ready phase unless the accepted plan explicitly permits an approved dispatch set of dependency-ready qualified tracer-bullet leaves. If broad Phase milestones group work, never claim them; keep membership in metadata rather than readiness-blocking Beads `parent-child` edges, select only qualified leaves, and audit each leaf with its immutable shared Phase doc. When a self-upgrade plan declares a builder bootstrap, read immutable `runtime/builder-certificate.json` and mutable `runtime/builder-activation.json`. Before both agree, use only direct mutation in one prepared coordinator-owned worktree. After activation, verify the builder release, source commit, adapter, ownership helper, verifier, fixtures, harness executable/configuration/schema, package, complete closure, certificates, coordinator probe, and no-candidate-import canary before every mutable owner launch.

Before bootstrap, source parity compares the active stable builder to its accepted source. After bootstrap, compare the loaded builder to the frozen builder release and certificate, never to the moving candidate worktree. A candidate source edit must not force installation of candidate control-plane code; a frozen builder drift must revoke activation.

Before mutation, run the bundled readiness module against the selected phase:

```sh
node <dirtyloops-skill-dir>/scripts/execution-readiness.mjs \
  --doc-root docs/implementation/<stream> \
  --phase <phase-doc>.md \
  --policy block
```

When Beads has already re-sliced a broad authored phase into explicit tracer-bullet leaves, audit the selected leaf together with its immutable shared phase doc. The leaf must carry the `tracer-bullet` label, a one-bounded-PR ownership note, concrete acceptance criteria, and a `spec_id` matching that phase doc; otherwise the projection fails closed. Preserve hashes for both sources:

```sh
bd show <selected-leaf-id> --json | \
  node <dirtyloops-skill-dir>/scripts/execution-readiness.mjs \
    --doc-root docs/implementation/<stream> \
    --phase <shared-phase-doc>.md \
    --issue-json /dev/stdin \
    --policy block
```

Treat this result as boundary readiness, not launch authority. `ready` means the work is sliced and reviewable. `needs-clarification` pauses for missing boundary information. `requires-reslice` proposes a plan amendment in Beads and the turn doc; it never rewrites the phase graph itself.

Then run the live launch preflight. It requires the exact selected ID to appear in `bd ready`, rejects epics and grouping milestones, verifies the dependency mirror and active generation, and blocks placeholder ownership:

```sh
node <dirtyloops-skill-dir>/scripts/launch-readiness.mjs \
  --doc-root docs/implementation/<stream> \
  --phase <shared-phase-doc>.md \
  --issue <selected-leaf-id> \
  --policy block
```

Proceed to checkout preparation or mutation only on `launchable`. A `boundary_status` of `ready` with launch status `blocked` is an honest normal state, not permission to infer missing ownership or bypass live Beads.

Completion criterion: the phase outcome, constraints, open questions, acceptance evidence, dependencies, boundary-readiness report, live launch-readiness report, builder binding, ready builder activation, exact checkout ownership, and capabilities required by the chosen strategy are known. A non-ready execution boundary, non-launchable leaf, activation, wrong checkout, or missing required capability is a blocker, never a reason to infer behavior from a product version.

## 2. Record The Orchestration Brief

Before broad work, add a compact brief to the phase turn doc:

```json
{
  "phase_issue_id": "...",
  "risk": "low|medium|high",
  "execution_profile": "adaptive|orchestrator-callback",
  "strategy": "direct|delegates|sessions|native-multi-agent|hybrid",
  "implementation_owner": "...",
  "review_independence": "...",
  "delegation_plan": ["..."],
  "model_and_effort_rationale": "...",
  "required_evidence": ["..."],
  "user_constraints": ["..."]
}
```

Enforce the profile's ownership topology. Choose tier, effort, helper missions, concurrency, and coordination proportionally. For implementation and review, enumerate independent evidence questions and strongly encourage useful helpers under the 20-per-stage ceiling and certified capacity. Record why when a non-trivial stage uses none. The brief is a decision record, not an immutable script; revise it when evidence changes and record why.

Completion criterion: the chosen strategy is proportionate, executable on the current surface, and preserves every invariant.

## 3. Execute Safely

In `adaptive`, work directly or appoint owners according to the brief. Direct mutation requires a prepared coordinator-owned worktree. Until a launch adapter is certified, read-only helpers or reviewers must report and verify the exact absolute checkout, branch, and HEAD before inspection, and no mutable owner may launch. In `orchestrator-callback`, the control thread never implements or reviews: launch a separate implementation owner and later a separate review owner, each with the concrete current orchestrator thread ID and one logical terminal-result identity. Owners may launch evidence-driven helpers under certified capacity. Route every child operation through capabilities exposed by the certified adapter. If creating child contexts that mutate or review repository state, follow `launch-safety.md`. Keep one owner per mutable checkout and keep phase scope narrow.

Before a broad Phase enters mutable execution, compile it into qualified tracer-bullet Beads leaves when more than one independent acceptance boundary exists. Each leaf owns one outcome, dependency set, write and interface surface, worktree and branch, test set, review record, and PR-sized internal contribution. Several disjoint leaves may run in one approved Wave. Review branch diffs independently, admit them to the one integration branch in dependency order, and run combined checks there. Do not turn each internal branch into a separate external PR unless the accepted publication policy requires it.

When the bound adapter emits a completion handle and nonce, persist and acknowledge that exact pair with the loop's absolute `doc_root` before launching another child. Return the same acknowledgement response for valid duplicate delivery and never repeat downstream effects. Treat emission as pending until durable acknowledgement succeeds.

Structured completion is the normal coordination path and uses no status, sleep, or wait polling. Pi `dirtyloops_child action=recover` and the legacy `action=status` compatibility alias are reason-required recovery operations, not observation APIs. Use `missed-heartbeat` only after the adapter's own activity evidence exceeds its configured silence window; use `delivery-recovery` only for an unacknowledged completion; reserve `operator-request` for explicit intervention. The adapter rejects premature recovery, rate-limits repeated attempts, and records accepted and rejected telemetry durably.

After delivery recovery, stop ordinary launches and request safe coordinator renewal with `dirtyloops_runtime action=renew`. The adapter anchors every authorized delivery recovery in the non-rewindable activation sidecar before re-emission, snapshots every degraded handle at the handoff boundary, and keeps requested renewal fail-closed until closeout is durably reconciled. Supply the phase Beads issue, repo-relative turn doc, PR state, expected symbolic branch, and a verified safe ownership boundary. A fresh coordinator must complete the returned activation probe and acknowledgement before work resumes. Context-pressure renewal is also allowed at a safe boundary when supported by adapter-observed context usage; no fixed context threshold, coordinator lifetime, model, or topology is implied.

Resolve open questions with evidence. If evidence invalidates an accepted decision, phase boundary, dependency, or acceptance criterion, stop broad implementation and propose a plan amendment. Record the evidence, affected phases, proposed change, and whether user approval is required. Do not silently rewrite authored phase docs.

Completion criterion: implementation reaches locally verifiable completion or a concrete blocker/replanning trigger.

## 4. Review And Verify

Apply `review-ci.md`. Review must be independent enough for the phase's consequence and preserve every role named by the accepted phase. A thermonuclear reviewer must use `thermo-nuclear-code-quality-review`. An adversarial reviewer must not invoke or consult that skill. The orchestration brief chooses a separate session, bounded delegate, native multi-agent context, or another fresh review context supported by the adapter for each required reviewer.

For a phase-defined shared repair process, wait for every required role under the same review-set ID and pass number. Combine and deduplicate findings, appoint one repair owner, rerun affected tests and all required reviewers, then increment the shared pass once. Enforce the accepted limit. If required findings remain at the limit, stop and ask the user instead of starting another pass.

Resolve CI to an allowed state and record evidence.

Completion criterion: acceptance evidence, review outcome, and CI state are explicit.

## 5. Close The Phase

Update the existing turn doc with the final execution summary, changes, tests, review, CI, repairs, PR/commit state, plan adaptations, and follow-ups. Update Beads first, export when applicable, then update `loop-state.md`.

Completion criterion: Beads and docs agree, the phase is complete or concretely blocked, and ownership has returned safely to the coordinator.

## 6. Continue Or Stop

Continue to the next ready Beads phase by default. Re-orient and write a new orchestration brief for every phase; do not assume the prior topology or model policy still fits.

Stop when the epic is complete, blocked, interrupted, review/CI is unresolved, a consequential plan amendment needs approval, or `--once` was requested.

Completion criterion: the response names current state, evidence, Beads updates, continuation status, and exact stop reason when stopped.
