# Build a Continuous Software Engine > Complete conceptual architecture, build sequence, explicit interface specifications, operational invariants, and adversarial proof requirements for building a deterministic engine around coding agents so repositories make continuous, verified progress without babysitting. Source guide: https://thisistheway.to/engine Summary index: https://thisistheway.to/engine/llms.txt Companion story: https://jonmagic.com/posts/building-a-continuous-software-engine-the-hard-way/ --- ## 0. Purpose, Ethos & Build Discipline Stop trying to make a coding agent finish a large task in one chat prompt. Wrap fresh, short-lived coding agent sessions inside a boring, deterministic orchestrator that owns durable state, independent verification, process cleanup, native self-stewardship, rolling budgets, ambition discovery, and safe landing. > **Using this file with an agent:** Give an agent this file and say “Build an engine in LANGUAGE.” (Name a target repository too if you already have one in mind.) Ask it to start with the local fixture and show each milestone's exit proof before moving on. Have it run the engine outside its own shell session, either under a service manager or as a detached process, because restarting the agent's shell stops anything running inside it. These are implementation requirements, not results from an engine already built from this guide. ### Six Core Ethos Rules 1. **The deterministic orchestrator owns the loop.** Ordinary software controls state transitions, leases, rolling budgets, timeouts, retries, verification, and landing. Coding agents do bounded creative and analytical work inside that shell. 2. **Design for failure first, then prove it adversarially.** Expect stuck subprocesses, dropped networks, host-load spikes, model oscillation, stale planner replies, and ambiguous remote timeouts. Happy-path unit tests are necessary but insufficient; crash-boundary and fault-injection tests are the proof bar. 3. **Non-blocking over blocking.** Waiting for human approval, an offline network, a flaky dependency, or a slow telemetry probe must never freeze unrelated ready work or tie up a worker slot. 4. **Zoomed-out ambition, zoomed-in goals.** Keep ambitions focused on user and business outcomes with explicit stop rules, and keep goals small, concrete, and independently verifiable so changes land cleanly and isolate blame. 5. **Durable external state behind explicit interfaces.** Treat every agent context window as disposable RAM. Keep intent, contracts, landing provenance, leases, evidence, and event streams behind narrow interfaces. Git, Markdown files, SQLite, and local directories are a suggested zero-infrastructure default adapter, while databases, lock services, object stores, containers, or brokers can implement any interface that satisfies its invariants. 6. **Approachable evidence and bounded human attention.** Store raw command logs, diffs, review verdicts, and rollback reasons with a direct link for authorized readers so an engineer can verify ground truth in thirty seconds, and deterministically cap human triage queues so the engine never dumps dozens of stale decisions on a person. ### Build in this order Trying to build the planner, multi-repo sync, and fleet supervision on day one hides basic bugs in landing and crash recovery. If you are building from a prompt like “Build an engine in LANGUAGE,” keep the requested language, and keep the requested target if one was specified. If no target repository was named, start with the disposable local fixture and the engine's own repository for self-hosting, and use other targets only with explicit authorization. Record the engine source repo, target repo and authorized branch, approved provider and budget limits, and check commands as separate settings. Start in disposable local repositories until you have authority to use a real target, credentials, or remote. Use the project's existing commands, and if none can prove the first behavior, add a focused check. You do not need a web UI, a second provider, or a plugin framework to start. Prefer the standard library and small single-responsibility modules, adding a third-party dependency only when local code would be large or security-fragile. Whenever a rule can be enforced mechanically, enforce it in a fast check with a useful failure message rather than relying on prose alone, while keeping short explanation where it helps humans understand why the rule exists. 1. **Land one contract locally (chapters 1–2).** Build `run`, `status`, and a credential-free `selfcheck` through the same engine path. Use fixture builder and reviewer adapters, real Git and checks, and a throwaway repo. Prove a passing goal lands exactly once, a rejected or malformed verdict never advances the ref, and a crash after ref advance or a ledger wipe does not repeat the landing. Run `selfcheck` as an engine health check; the nested fixture uses fixture health commands, not `selfcheck` again. 2. **Replace the fixture with real tools (chapters 2–3).** Prove the builder can read, edit and run tests in its attempt workspace. Try to write outside it, change verification policy, or leave a child process running after cancellation; none should escape the boundary. With a fresh independent reviewer, land one small real change to the engine through its normal entry point. This is a self-hosting proof, not handoff. 3. **Keep one repository moving (chapters 2–4).** Add the durable scheduler, bounded planner, approval parking, recovery, and budgets. Prove a planner-created step lands after the seed queue drains and an unrelated goal advances while another is parked. Inject both an engine regression (charge only what the verified rollback removed) and a broken tip with no safe rollback (block ordinary landings and surface a repair goal). Restart mid-run and show `status` identifies what happened and what wakes next. Prove the single-repo paths in matrix rows 1–7 before handing off. 4. **Work on a second repository and with a peer (chapter 5).** Run the same executable, loop, planner, and repair cycle against an independently initialized repo with its own commands and policy, rather than giving external targets a weaker one-shot queue that pushes operators into writing wrapper scripts. Prove no checkout or state leakage, a peer race yields one landing, and pull/push preserves human work and refreshes affected consumer artifacts (row 8). Do not use a language port as the second-repo proof. 5. **Operate and finish (chapter 6).** Add resumable events, bounded operator views, discovery and fleet supervision. Prove status stays responsive through stalled probes and upgrades fail closed (row 9). Complete the final readiness bar before calling the engine ready. ### Hand off the work, not the authority The initial operator, not the builder or planner, sets the approved bootstrap ambition: finish this guide's remaining milestones in the requested language, and for the requested target if one was specified (otherwise start with the disposable fixture and the engine's own repository for self-hosting, and use other targets only with explicit authorization). Keep the approved objective, current milestone, proof command and result, and remaining gaps in version control. Seed one small goal for the next missing proof; let the planner propose the next step when the queue drains. Do not fork the language, replace the target, add providers, or change the product direction merely because the engine can. At the end of step 3, hand off only after its proofs pass, including the human-approved reviewer quality baseline. Give the operator the run, status, drain and selfcheck commands, the verified commit, evidence locations, and known limits. If authorized, let the verified runtime continue steps 4–5 under the same ambition. If a required permission, provider, or quality proof is missing, record the blocker and keep unrelated authorized bootstrap work moving; do not hand off. A worker cannot replace or restart its running engine. Stop when the readiness proofs pass and the ambition is satisfied; further direction requires human approval. Never build an outer bootstrap driver or wrapper script around the engine to feed goals or drive repairs while the engine is still incomplete. While the engine is below the self-sustaining threshold, use your coding agent (such as Copilot, Claude, or Codex) directly to build and fix the engine until watch mode, diagnostic repair retries, planning, and native dashboard state reading live inside the engine and it can take over on its own repository and external targets without a wrapper. ### First run: a local fixture One possible `engine.json` in an authorized target checkout (names and format are examples). Read it from a trusted source, not a candidate's working tree. Have your implementation agent write and commit these four executable fixture files on `engine-demo` (they are not shipped with this guide): `greet` prints `bye` with no arguments, `version` with any argument; `check` exits nonzero unless `./greet` prints `hello`; `health` asserts `./greet --version` prints `version` and passes on the seed; `metric` prints the integer 1 if `./check` succeeds, otherwise 0, and exits zero either way. The fixture builder changes only the no-argument output. ```json { "branch": "engine-demo", "checks": ["./check"], "healthChecks": ["./health"], "protectedPaths": ["engine.json", "goals/**", "check", "health", "metric"], "limits": { "attemptSeconds": 60, "maxAttempts": 3 }, "models": { "code": "fixture-builder", "review": "fixture-reviewer" } } ``` Run `engine selfcheck` with credentials unset and network off. It creates throwaway repos with the `greet` goal below, verifies that `check` initially fails, and runs fixture providers through the real loop. Exit zero only if a valid accept advances the ref once, an incomplete verdict (`{"accept":true}`) leaves it unchanged, and both a crash after ref advance but before ledger update and a ledger wipe replay without rebuilding or landing again. Example `status` results: `greet landed; evidence runs/a1/` or `greet rejected: malformed verdict; evidence runs/a2/`. Authorized readers can inspect those runs. This fixture is not the live tool-use or readiness proof. Later, point the same executable at two different repositories. --- ## 1. Explicit Interfaces vs. Suggested Default Adapters Never hard-wire Git CLI commands, one SQLite schema, one model SDK, one ticket host, one event transport, or one process supervisor into the scheduler or core loop. Isolate every external concern behind an explicit interface with a clear invariant so implementations can swap adapters cleanly. | Interface | Required Invariant | Suggested Zero-Infra Adapter | Valid Interchangeable Alternatives | | --- | --- | --- | --- | | 1. Goal & Ambition Store | Immutable content-hashed behavioral contracts; zoomed-out ambition kept separate from routine goal edits; candidate discovery hypotheses stored isolated from active main intent | Markdown files in Git + non-branch Git ref for discovery candidates | Postgres, document store, or issue tracker with immutable content hashing | | 2. Landing Provenance | Atomic, durable mapping from landed commit to `(goal_id, contract_hash, attempt_id, ambition_id)` surviving full local ledger wipes | Structured `Key: value` Git commit trailers on the target branch | External deployment/release ledger keyed to commit SHAs | | 3. Local Operational Ledger & Fencing | Transactional leases with monotonic fences, retry history, budgets, and parked approvals; completed landings recoverable from provenance | Embedded SQLite in WAL mode | Any transactional store with conditional updates | | 4. Workspace Isolation | Clean per-attempt tree at the target commit; workers cannot write outside their workspace | Disposable Git worktree inside an OS sandbox | Containers, microVMs, or isolated workers | | 5. Evidence & Telemetry Store | Append-only raw artifacts per run (contract snapshot, prompt, tool/event stream, diff, verbatim gate stdout/stderr, review verdict, model/effort metadata) plus bounded read-only queries | Plain run directories + JSONL logs + read-only CLI / stdio MCP tools | Object storage (S3/GCS), structured log pipelines, or analytics warehouse | | 6. Execution & Model Routing | Configurable role + content-kind profiles (`code`, `prose`, `review`, `planner`, `judge`) with reasoning effort and ordered cross-provider fallbacks; read-only roles refuse file writes | Coding-agent SDK sessions + deterministic shell command executors | Direct provider API adapters, alternate agent harnesses, or remote workers | | 7. Process Supervision & Watchdog | Isolated process tree terminated cleanly on exit, timeout, livelock, or abrupt orchestrator exit (including `SIGKILL`), plus an explicit clean-exit backstop | Detached POSIX process group (`setsid`) + parent-exit pipe | OS cgroups, Windows job objects, or container lifecycle termination | | 8. Intake & Approval Transport | Thin adapters translating external requests into standard contracts, presenting capped Needs You actions revalidated against authoritative state, and deduplicating outbound callbacks | CLI + researched proposal/promotion PRs + opt-in local dashboard actions | Jira, Linear, GitHub Issues, Slack commands, RFC folders, or custom web UIs | | 9. Distributed Lease & Sync | Atomic compare-and-swap (CAS) multi-machine claim leases with TTL, heartbeat, clock-skew margin, and transient-failure resilience; non-destructive remote sync with fast-forward-only publish | Atomic CAS pushes to dedicated non-branch Git refs + in-memory 3-way merge pull + verified FF push | Redis, etcd, DynamoDB, Consul, or Postgres conditional locks + hosted merge queues | | 10. Event Stream & Observability | Monotonic, cursor-resumable domain event stream and fast degraded local status completely decoupled from remote network probes so monitoring never starves workers | Local HTTP dashboard streaming over Server-Sent Events (SSE) + JSONL log | WebSockets, Kafka, NATS, OpenTelemetry exporters, webhooks, or terminal UI (TUI) | | 11. Fleet Supervision & Upgrade | External supervisor owns process lifecycle and restarts; engine never self-restarts and exposes `drain`, `selfcheck`, live version, verified tip, and post-restart landing progress | OS service manager (`launchd` / `systemd`) + upgrade CLI interlocks | Kubernetes, Nomad, or container fleet orchestrators | --- ## 2. Chapter 1: State, Contracts & Storage Interfaces ### Three State Planes 1. **Durable Intent & Provenance Interface (Authoritative Truth):** Stores ambitions, goal contracts, constraints, and landing provenance. Survives wiping any machine's local state. 2. **Local Operational Ledger & Evidence Interface:** Stores active leases, fences, retries, cooldowns, usage, parked approvals and evidence references. Reconcile landed outcomes from durable intent and provenance; do not infer missing operational state. 3. **Workspace Isolation Interface (Disposable Scratchpad):** Every attempt receives a fresh isolated sandbox and a fresh agent context window; both are discarded cleanly when the attempt finishes or aborts. ### One-Way State Flow State moves in one direction, similar to Redux with side effects in sagas, paired with a Kubernetes-style reconciliation pass so the engine picks up edits people make or commits that arrive from `git pull` outside the loop. - **Keep each kind of truth in one place.** Durable intent and landing provenance, such as goal files and commit trailers, are the source of truth. The operational ledger just tracks what the engine is currently doing, so you can delete it and rebuild it from durable state at any time. - **Reconcile on every tick before scheduling.** Because people edit goals and pull commits outside the loop, each tick brings the ledger back in line with durable intent and Git history before deciding what to run next instead of waiting for a restart. - **Change state only through actions.** Approve, reject, retry, dismiss, pause, and drain each write one small atomic transition or control record for the next tick to apply, so neither the CLI nor a dashboard reaches directly into a running worker. - **Run effects at the edges and write results back through fences.** Agent sessions, checks, review, push and pull, and post-land hooks all run as isolated effects, and their results enter state only through a fenced transition so a stale worker cannot overwrite newer state. - **Treat every view as a projection.** Scheduling input, `status`, and dashboards only read state and never mutate it. When you click a button in a dashboard, it posts an action and waits for the next authoritative snapshot. ### Ambition vs. Goal Boundary & Content-Hashed Contracts - **Ambition (zoomed out):** Describes the business or user problem, beneficiaries, end-state success criteria, constraints, and explicit stop rules. Routine goal authoring and automated planning read ambition and never modify it. - **Goal (zoomed in):** Describes one small, independently verifiable unit of work with observable acceptance criteria, explicit non-goals, prerequisites, risk/approval mode, content kind (`code` or `prose`), optional executor/command, and optional metric specification. - **Behavioral Contract Hash:** Bind intent and landing authorization to an immutable version. The sample below maps intent to `ambitionId`, `title`, `body`, `scope`, `acceptance` and `nonGoals`; the other fields specify how work is run, checked and approved. Any field changing accepted behavior or authorization must invalidate or revalidate in-flight work. Pure queue ordering stays out. If dependencies only affect scheduling, keep them out of the hash but recheck readiness before landing. Revalidate against live trusted policy if checks, protected paths or other permissions change. - **Every Contract Sentence Is Enforced:** Treat every sentence in a contract as a requirement that both the builder and the reviewer will enforce. Leave operating hints like file-size targets or provider workarounds out of the body unless they are real acceptance criteria, and make sure each rule only applies to the case you mean. For example, putting a byte-size hint in a goal body kept a working candidate from landing for eight rounds, and an unscoped provider workaround ended up enforced against the wrong provider. - **Contract-Scoped Lifecycle Hygiene:** - If a goal is deleted while an attempt is in flight, abort the worker promptly and free its slot. - If a goal's behavioral contract hash changes while an attempt is in flight, mark that attempt `superseded`, discard its candidate, clear stale review feedback tied to the prior contract, and start fresh against the new hash. - Reconcile unknown, missing, cyclic, or restored dependencies in a single deterministic, order-independent pass so only affected goals block or escalate. ### Example: one goal, one attempt, one landing The sample goal is `{ id: "greet", priority: 1, dependsOn: [], contract: [...] }`. The ID is the stable key paired with the hash, outside this encoding. This adapter's ordered `contract` fields are: ```text [version, ambitionId, title, body, scope, acceptance, nonGoals, contentKind, approval, executor, command, metric] ``` `version` is the literal `engine-contract-v1`; `ambitionId`, `title`, `body` are strings; `scope` is an array of allowed repo-relative paths, and `acceptance` and `nonGoals` are arrays of strings. `contentKind` is `code|prose`; `approval` is `none|human` (human sign-off before landing, separate from goal admission); `executor` is `agent|command`. `command` is a nonempty string for the command executor and `null` for the agent. `metric` is `null` or `[command, better]`, where its command is a nonempty string and `better` is `higher|lower`. Reject unknown values rather than guessing. Test vector: serialize the array as canonical JSON (RFC 8785), then hash the UTF-8 bytes with SHA-256, with no BOM or trailing newline. The exact input bytes for this ASCII example are: ```text ["engine-contract-v1","bootstrap","Return hello","Make greet return hello.",["greet"],["./check passes"],["No CLI changes"],"code","none","agent",null,["./metric","higher"]] ``` Expected lowercase hex digest: `41f2af5384943d176007d44cc3c4700d8b8ddb317d72484d23bfd44f9947eda9`. In this adapter `H` is `engine-contract-v1:` followed by that digest. Changing `better` to `lower` changes the digest; changing only `priority` does not. Other encodings are valid in independent engines. Peers sharing persisted state must use compatible encodings and test vectors, or migrate explicitly without losing the association to prior proofs and landings. An older verdict cannot authorize a behavior change. An example attempt is `{ id: "a1", target: "fixture:engine-demo", goalId: "greet", contractHash: H, baseSha: B, generation: "g1", fence: 1, phase: "review", evidenceRef: "runs/a1/" }`, where `B` is the recorded base commit. On landing, stamp `{ goalId: "greet", contractHash: H, attemptId: "a1", ambitionId: "bootstrap" }` (for example as Git trailers). Use trusted target history and `(goalId, contractHash)` to determine whether the landing is still live. ### Monotonic Fencing, Portability & Degraded Local Status - **Monotonic Fencing Tokens:** Issue a strictly increasing per-goal integer fence on each lease acquisition within a ledger generation. At every attempt mutation and promotion, compare the attempt's `(ledger generation, per-goal fence)` against the authoritative current tuple in the same transaction or promotion critical section. Reject a mismatch atomically, even when the numeric fences match. Initialize a fresh, never-reused generation after a wipe, before accepting attempt operations. - **A wipe is not a time machine.** Fold only trusted landing and rollback records reachable in target history. Either explicitly trust repository-authorized writers not to forge reserved controller records or use an adapter that authenticates those records independently; Git author and trailer text do not authenticate them. Only an explicit trusted `Rollback-Of: ` reconstructs a rollback charge and removes that exact landing, not every landing for the contract. Requeue a still-current eligible contract with no live landing. Do not infer live leases, approvals, other retry history or provider spend. Invalidate unsupported approvals and recover usage from durable records or wait out the budget window before model admission. - **A human revert is steering, not engine rollback.** After a wipe, a human `git revert` without trusted `Rollback-Of` leaves the original landing live for replay purposes: the contract stays done, with no requeue or rollback charge. Do not infer rollback from the diff. To pursue the change again, create a new goal or make a behavioral edit that produces a new contract hash. A priority-only edit does not reopen the work. - **Raw evidence is private by default.** Keep it in controller-owned, repository-scoped storage with authorized readers and a retention limit. Do not collect credential values or dump environment variables. Expose sanitized summaries, not raw prompts, diffs or logs, in broader status and exports. Redaction is imperfect; keep raw proof available to authorized readers without relying on redaction for access control. - **Portable External References:** Ban hardcoded machine-local paths in tracked files. Resolve references to sibling repositories or external specifications read-only through relative paths or configured environment variables. - **Degraded Local Status:** Validate trusted repository metadata without blocking on slow VCS invocations, and allow read-only local status commands to report recorded tasks, leases, and decisions from the local ledger within a strict timeout even when local VCS or remote network calls hang. --- ## 3. Chapter 2: Independent Verification, Guardrails & Transactional Landing ### Separation of Powers Builders accumulate sunk cost and confirmation bias across turns and must never grade their own work. Every candidate passes a strict funnel: deterministic gates, fresh-context independent review, path-scoped policy, and health verification on the exact tree that would land. ### Give builders tools, not control of the engine Start with one coding-agent adapter. Give it a fresh session with the attempt directory as its working directory, the exact contract, scope and non-goals, applicable repo instructions, check commands, and a short excerpt from the last failure with its evidence reference. Let it search and read the repo, edit permitted files, and run project commands. Ask it to leave changes in the workspace and report what it ran, not to return a patch in chat. Enforce this outside the prompt. Run in an OS sandbox or isolated worker with only the attempt tree writable, approved read-only inputs, and a restricted environment. A Git worktree alone does not isolate a shell. Shared refs, Git metadata, engine state, verifier configuration and the evidence store stay controller-owned. Keep credentials out of workers and their child commands; if inference needs credentials, keep them on the adapter side. Limit network access and disable unneeded tools. Candidate tests also run within the boundary: changed code can execute during a check. When running network-off checks against an external repository, such as a web app with `node_modules`, stage preinstalled dependency trees into the sandbox safely as read-only mounts or copy-on-write copies and preserve symlinks in Git tree snapshots so real builds can pass offline without touching the primary checkout. Reviewers get enforced read-only inspection or a tool-free evidence packet, not an unrestricted shell. The adapter needs only `build(workspace, prompt, deadline, cancellation, onEvent) -> outcome`. Stream activity and usage to the controller and stop the process tree at completion or cancellation. The controller reads the actual tracked and untracked changes, enforces policy, runs checks and stores their captured output. In throwaway repos, make a builder and a candidate check try to overwrite a sibling file, target ref, ledger, verifier settings and sealed gate evidence; submit equivalent requests through the reviewer's tools. Assert denial and unchanged file digests and ref before promotion. Add a harmless marker to raw gate output: it must be readable by the authorized proof reader, denied to an unrelated repo, and absent from exported status. A tool-less executor can help with a fixture; it is not proof of tool use. ### Layer 1: Deterministic Gates & Executable Guardrails The orchestrator itself executes every gate command inside the candidate workspace and requires exit code zero: - **Correctness & Static Checks:** Unit tests, real consumer integration tests, typecheck, build, and repository lint rules (including module size and purpose headers). - **Progressive-Disclosure Doc Ratchets:** Enforce a concise front-door README, reachable documentation links, readable paragraph lengths, and valid local diagrams/media as a ratchet (only newly introduced problems fail so legacy debt never blocks legitimate fixes). - **Supply-Chain & Portability Guardrails:** Block unapproved dependency additions, lockfile entries from unapproved registries or missing integrity hashes, secret patterns, and hardcoded machine-local file paths. - **Protected Paths & Test Integrity:** Protect the operating contract itself (engine config, goal definitions, agent instructions, dependency manifests) unless explicitly authorized, and reject diffs that delete tests, add skip/focus markers, or weaken assertions without authorization. ### Layer 2: Fail-Closed Fresh-Context Review, Model Routing & Backtesting - **Strict Isolation:** Spawn a fresh reviewer without builder chat history. Provide the exact contract, candidate diff and authorized raw gate evidence, plus surrounding code through read-only inspection if needed. - **Verdict protocol:** The reviewer returns exactly one JSON object: `{"accept":true,"reason":"Checks and scope agree"}` or `{"accept":false,"reason":"The check misses empty input"}`. Require exactly these two keys, a boolean and a nonblank string; reject duplicates, extra text, conflicting replies or wrong types. Bind request and candidate identity in the controller's envelope, not in the verdict. No valid accept means no promotion. A confirmed provider outage parks uncharged until a bounded retry; a negative or malformed verdict is not an outage. A rejection should list every blocking defect the reviewer found, within a reasonable length cap, so the next repair round can fix all of them at once instead of uncovering one problem per round. - **Bounded Blocking Criteria:** Reviewers block only on contract violations, real defects, safety issues, or missing verification rather than endless stylistic nitpicks, and review rounds are capped before escalating cleanly. - **Role & Content-Kind Model Routing Interface:** Configure independent profiles for `code`, `prose`, `review`, `planner`, and blind `judge` (using goal content kind to route prose vs. code), each specifying model, optional reasoning effort, and ordered cross-provider fallbacks. Record the exact model and effort used in attempt evidence, and keep routing as operational config rather than hardcoding vendor IDs in core code. - **Reviewer backtest:** Have a human label examples (valid, defective, contract miss, weakened verification). Keep versioned labels out of the prompt. Run the initial reviewer on those cases in disposable repos; a human inspects the errors and approves the baseline and acceptable limits for missed defects and false rejections separately before unattended use. Repeat against that baseline when changing the prompt, model or effort. The fixture tests verdict handling, not reviewer quality. ### Layer 3: Path-Scoped Policy, Transactional Landing & Post-Land Hooks - **Path-Scoped Autonomy & Landing Modes:** Map repository file globs to landing modes (`land`, `pr`, `human`, `off`) and optional autonomy overrides. Resolve any multi-file diff to the **strictest** matching mode across all touched files. Changes routed to `pr` still run clean-candidate health checks before pushing. - **Transactional Landing Critical Section:** 1. Take a consistent snapshot of the branch tip and its verified-health status. Run slow commands outside the final promotion lock. 2. Rebase on that tip if it moved. On conflict, abort cleanly and return evidence to a fresh attempt. Rerun gates on the rebased tree and recheck path policy. If the reviewed change itself changed, require a fresh verdict and any required human approval. 3. Stamp provenance and make the final candidate commit before health checks. Record the SHA checked in a clean checkout. Under the promotion lock, use the existing contract and fence checks and compare the live tip and trusted policy to those used for verification. If anything changed, do not promote: reverify under current policy, including any required review or approval, or supersede stale work. Otherwise compare-and-swap from the checked base to the checked SHA. Never amend after health. Bound integration retries. 4. Record the verified tip in the ledger. Git and a separate ledger do not share a transaction: on restart reconcile from the ref and trailers before scheduling. Recheck health when verified status is uncertain rather than trusting a stale row. - **Crash-Resumable `postLand` Hooks & Artifact Freshness:** Run configured scoped, timeout-bounded post-land commands (for example, rebuilding untracked `dist/` artifacts when `src/` changed) after landing and resume them after crashes without ever undoing a verified commit if a hook fails. Trigger the same artifact rebuild after diverged remote pull merges, health rollbacks, and verified manual branch updates. ### Layer 4: Automatic Culprit-Only Rollback When the target tip fails health checks (due to a flake, async suite, concurrent interaction, or external push): 1. Inspect the history after the last verified ancestor. Only consider recognized engine-owned landings; never revert a human commit or a human-owned PR delivery. If you cannot establish which commits you own, open a repair goal instead of expanding the rollback. 2. In an isolated workspace, undo eligible engine changes newest-first until health checks turn green. Re-test to narrow down what actually had to be removed. 3. Restore newer changes one at a time, verifying each. On the final forward rollback commit, stamp `Rollback-Of: ` once per removed landing before final health checks. Revalidate the live tip and trusted rollback policy, then compare-and-swap to the exact checked rollback SHA; never force-rewrite a shared branch. 4. Charge only removed engine landings, once per landing SHA. Attach the failing evidence and requeue still-current contracts within their retry budgets; exhausted ones need a human. On replay apply each durable rollback charge at most once. Record inseparable changes instead of guessing at a single culprit. 5. If undoing eligible engine changes cannot restore health, treat in-flight work as `unverified-base` (no retry charge), open a repair goal, and run only repair work until the tip is healthy. Do not guess who broke it. --- ## 4. Chapter 3: Watchdogs, Self-Stewardship, Rolling Budgets & Liveness ### Process Supervision & Clean-Exit Discipline - **Detached Process-Group Watchdog Interface:** Run every subprocess under a detached process group (`setsid` + parent-exit pipe, or OS cgroups/containers) that terminates the entire process group cleanly on command completion, backstop timeout, or abrupt orchestrator exit (including `SIGKILL` of the orchestrator or its process group). - **Clean-Exit Backstop:** Enforce a bounded final exit deadline after graceful shutdown so dangling SDK or network handles cannot hold the process alive and block external service-manager restarts. - **Host-Load-Resilient Testing:** Avoid fragile millisecond assertions under contention, warm freshly generated test wrappers, and attach guaranteed cleanup hooks so chaos and dashboard tests never leak stray helpers. ### Stuckness Classification & Retry Ladder - **Stalled vs. Livelock:** Distinguish silent stalls (no output, no diff) from livelock (active token/tool output with zero file diff across a sustained window) and abort both early. - **Retry ladder:** Start `direct`. After the first counted failure, retry with `diagnose` and its evidence. If that retry stalls or repeats a normalized failure, try a smaller `alternative` within the retry limit. Stop `A -> B -> A` oscillation or repeated no-progress work instead of cycling. Escalate with `{ goalId, contractHash, reason, attempts: [{ outcome, evidenceRef }], choices }`: retry with guidance, revise the contract, or retire the goal. - **Intentional reversal:** Compare the candidate diff to the inverse patches of live engine landings on touched paths. Reject a detected reversal unless the contract names the landing and a human authorizes the reversal. The health repair path records rollback separately; it is not a builder exception. **Task states:** A new or reevaluated task is `ready` if eligible, otherwise `waiting` with a reason and wake event. Recheck eligibility before claiming; only an acquired lease moves `ready` to `running`. A finished attempt frees the slot and records its outcome separately. `landed`, `retired`, and `needs-human` end automatic execution of that version. Rollback reopens a still-current `landed` task, an operator retry reopens `needs-human`, and a new authorized contract gets its own state. Deletion or retirement cancels outstanding work and enters `retired`. A failure only updates its own task; shared restrictions such as a broken tip apply independently. | Attempt outcome or scheduler event | Next task state and wake | Charge a code retry? | | --- | --- | --- | | Promotion succeeds | `landed` | No | | Unsuccessful worker or candidate outcome unless an exception below applies: no change, worker crash, unexplained lease expiry, unknown provider error, negative/invalid review, unauthorized protected-path diff, check/docs/metric failure on a verified base, or rebase conflict | `waiting` with bounded backoff, then reevaluate at the deadline; `needs-human` when retries end | Yes | | Confirmed outage (including review) or unverified base | `waiting` with bounded backoff until retry or health recheck; only repair work may run on a known broken tip | No | | Superseded, fenced, or confirmed controller/host interruption | Abort stale work and reevaluate the new contract. A fenced worker stops without changing ownership. After confirmed interruption, reconcile on restart, then reevaluate | No | | Unauthorized reversal or confirmed loss of containment | No promotion; immediate `needs-human`. On containment loss, stop affected execution, quarantine the runner and alert the operator | No automatic retry | | Verified rollback removes a live engine landing | Requeue still-current eligible work within its retry budget; exhausted work goes to `needs-human` | Once per removed landing SHA | | Human approval or optional PR delivery required | `waiting` for a matching decision or confirmed merge. Approval makes the parked candidate eligible for revalidation, not another build; confirmed delivery reconciles to `landed`; rejection goes to `needs-human` | No | | Allowance, prerequisites, pause/drain or worker capacity blocks dispatch | `waiting` for refill or authorized fallback, dependency change, resume, or slot release; reevaluate eligibility on each event | No | On expiry, reconcile any completed ref advance before charging an unexplained failure. The controller applies this once; the revoked worker never charges or requeues itself. A dependency that cannot be satisfied becomes `needs-human` with its blocker. An outage or interruption is confirmed only by controller, adapter, or supervisor evidence tied to the request or lease window (such as a classified infrastructure failure or a recorded host shutdown). Model or worker claims and elapsed time alone do not qualify. Record the reason and supporting evidence in existing attempt diagnostics. Unexpected successful access or mutation outside the boundary, or credential exposure, can establish containment loss; a denied operation is evidence the boundary held, not a breach. Quarantine stops execution and admission on that runner until the boundary is repaired and re-proved. ### Native Self-Stewardship (Replacing Manual Babysitting) Promote recurring operator interventions into native deterministic engine rules: - **Cross-Task Flake Attribution:** Normalize check failure signatures across unrelated goals. When one signature recurs across multiple tasks, prioritize a single systemic repair goal and automatically requeue blocked tasks once that repair lands. - **Bounded Read-Only Pre-Escalation Triage:** On an eligible final failure before escalating to a human, invoke one short, tool-less, read-only diagnosis over the contract and raw evidence. It may grant at most one contract-scoped retry with focused guidance and can never edit files, alter contracts, or approve work. - **Dependency Cascade Hygiene:** When an upstream blocker lands or is retried, automatically cascade retry/readiness to dependent goals in the reconciliation pass. - **Safe Planner Retirement of Superseded Escalations:** Permit the planner to retire strictly eligible superseded escalations (untracked, unlinked goals and their dependent escalations) so abandoned directions never accumulate into dozens of stale Needs You items. - **No Outer Bootstrap Drivers:** Never build an outer bootstrap driver or wrapper script around the engine to keep goals moving or drive repairs. While the engine is still missing watch mode, diagnostic repair retries, planning, or native dashboard state reading, use your coding agent directly to build and fix those capabilities in the engine itself until it can run on its own without a supervisor watching a supervisor. ### Unified Pure Scheduler, Rolling Budgets & Exhaustive Liveness - **Sample tick:** Reconcile completed work, current contracts, ref history and expired leases. Consume cached results and start due bounded probes and sync work if enabled; do not await remote or status I/O on the dispatch path. Snapshot health, dependencies, slots, approvals, cooldowns, budgets and flags. Pure `nextAction(snapshot)` schedules due health/repair first: verify unverified tips before normal dispatch or planning; known broken tips admit only repairs. Otherwise dispatch eligible work in stable order, plan if allowed, or wait for a named event. Apply the result outside the function, rechecking ownership. - **Launch and stop:** Use an external supervisor for continuous operation, or make `run --once` stop admitting at a configured deadline, finish or cancel and clean up its started children, persist state and exit. On restart reconcile before taking new work; a one-pass launcher must not leave unattended children behind. - **Rolling Operational Budgets:** Configure limits in units the provider actually exposes. Record timestamped provider, model, role and attempt with reported input/output tokens or cost, plus turns and host API calls where relevant. Reserve allowance before a call and account for usage across retries, fallbacks and restarts. If usage goes missing, retain a conservative reservation or use an explicit call cap; never call that a token limit. Enforce a per-session output or spending bound where available. Scope the ledger to the allowance: overlapping workers sharing one allowance must share its admission counter, or use explicit separate allocations. - **Admission and fallback:** Shed optional discovery and planning first. At a hard limit, use an authorized fallback with allowance left or park until the window refills. Keep local verification, status and bookkeeping running. Fallback on exhaustion or provider failure is not a way around a check or review rejection. Prove concurrent reservations cannot each take the last allowance, unknown usage is not free, and a restart preserves the next wake time. - **Planner-Pass Lease & Stale-Reply Discard:** Hold an exclusive planner-pass lease per checkout so passes cannot overlap; snapshot ambition hash and landing tip before invoking the planner and discard the reply if either changed before completion. - **Exhaustive finite model:** Declare the task states, wake events, a finite dependency abstraction (for example ready, waiting upstream, impossible), and flags for health, slots, approval, backoff, budget, connectivity, planning, pause and drain. Declare reachability rules (for example `running` owns a slot, deleted work cannot dispatch, only repair runs on a broken tip). Enumerate all reachable states and successors in that model. Assert every non-terminal state acts or names an event that can change its blockers, and eligible independent work is not hidden by a parked task. Record the model and its scope; separately test real dependency resolution, including missing and cyclic dependencies. Do not claim this proves arbitrary graphs or that an external event must arrive. --- ## 5. Chapter 4: Ambition, Continuous Discovery & Human Steering ### Unified Steering Pipeline Route all direction through one pipeline: **Approved Ambition -> Read-Only Just-in-Time Decomposition (next 1-2 small vertical steps) -> Tiered Admission (`auto` vs. `human-gated`) -> Verified Execution & Non-Blocking Approval Parking**. - **Just-in-Time Decomposition:** When runnable work drains and the tip is healthy, a fresh read-only planner inspects ambition, constraints, README/docs, prior goals, recent landings, bounded friction evidence, and configured read-only reference repos, then proposes at most 1-2 bounded goals (vertical feature step, simplification, doc pass, or split of a stalled goal). Plain deterministic code validates every proposal (fresh kebab-case ID, no overwriting, acyclic dependencies only on earlier or existing goals, valid title/body) and enforces cooldowns and empty-pass limits. - **Planner output is a proposal, not a write.** Ask for `{ goals: [{ id, title, acceptance, nonGoals, dependsOn, whyNow }] }` or an empty list with a reason. Require `whyNow` to link a goal to the approved milestone or a recorded blocker. Reject malformed or stale replies; require approval when the justification does not clearly fit the authorized scope. Save the proposal and decision as evidence. Ordinary planning never changes ambition or expands permissions. - **Tiered Admission (Divorced from Transport):** - `auto`: bounded steps under an approved ambition, simplifications, doc passes, and recurring-failure repairs validated deterministically. - `human-gated`: new ambiguous requests, scope shifts, ambition promotions, or protected high-risk boundaries. - **Non-Blocking Approval Parking:** Admission `auto|human-gated` decides whether a proposed goal enters the queue; contract approval `none|human` applies later at landing, subject to repository policy. A verified candidate needing sign-off goes to `waiting` with reason `awaiting-approval` and releases its worker slot. Revalidate approval against the reviewed candidate and current contract before landing; preserve rejection feedback. **Example:** The approved next milestone is approval parking. The planner proposes “land a ready goal while a different goal waits for approval,” with no UI in scope. A builder edits the scheduler and runs a two-goal fixture; an independent reviewer gets the contract, diff and raw results. The engine lands the scheduler change and attaches that proof to the milestone. If the planner instead proposes a dashboard rewrite, it has no authority to run it. A later proposal can add a read-only dashboard under the fleet milestone. ### Disposable Experiments & Representative Workloads - Attach deterministic measurement commands and target directions to metric-gated goals; measure baseline and candidate under identical conditions and land only when the metric improves beyond noise while passing correctness and resource-retention checks. - Base promotion decisions on **representative consumer workloads**, never isolated synthetic microbenchmarks that optimize the wrong proxy. - For exploratory or multi-stack research projects, run small disposable experiments to eliminate weak approaches quickly while durably archiving every explored direction and negative measurement so fresh sessions never repeat dead ends. ### Continuous Ambition Discovery When an approved ambition completes or stagnates, run a separate, human-gated discovery loop: 1. **Deterministic Stagnation Detector:** Qualify repositories based on objective stagnation signals under a fleet lock and per-repository daily spike quotas. 2. **Isolated Candidate Store Interface:** Store candidate hypotheses and append-only discovery decisions off the main branch (suggested default adapter: a dedicated non-branch Git ref; alternative: database table). 3. **Disposable Ambition Spikes:** Execute time- and evidence-bounded spikes in detached checkouts, saving bounded evidence off-branch. Any edit to sensitive configuration or active ambition invalidates in-flight spikes. 4. **Blind, Tool-Less Cross-Provider Judge:** Evaluate anonymized spike evidence using a different model provider with zero write/shell tools. Inconclusive verdicts never support promotion. 5. **Human-Gated Promotion & Honest Outcome Reconciliation:** Promoted candidates open a human-reviewed proposal (e.g., Promotion PR) and never edit active ambition directly. Downstream landings carry ambition attribution in landing provenance; reconciliation tracks linked landings, failures, and rollbacks without fabricating automatic business metrics. ### Compounding Self-Improvement & Bounded Human Attention - **Tool-Building Self-Improvement:** Mine friction telemetry not only for flaky checks, but for repeated diagnostic work, proposing reusable CLI scripts, preflights, or inspection tools that pass the same gates as product code. - **Cross-Project Trace Mining:** Read-only trace mining across multiple repositories identifies recurring systemic friction and missing engine primitives across the fleet. - **Bounded Human Triage:** Deterministically rank and cap the `Needs You` surface (separating overflow and stale planner items) and generate a fixed-size multi-repository digest. --- ## 6. Chapter 5: Multiplayer, Multi-Repo & Distributed Coordination ### Pluggable Intake & Approval Transport Interface Keep admission policy independent of intake surfaces. Any adapter (CLI, researched ticket-to-proposal PR, design doc, issue tracker, chat ops, or authenticated opt-in dashboard actions) writes standard contracts into the Goal & Ambition Store interface and revalidates human actions against authoritative state. Key outbound lifecycle callbacks by run or event marker so retries and peer machines never duplicate updates. ### Distributed Lease & Bidirectional Sync Interface - **Non-Destructive Bidirectional Sync:** Never mutate a human's active checkout or force-push shared branches. Suggested Git default: in-memory 3-way merge pull (or dedicated sync worktree) plus verified fast-forward-only pushes that rebase and re-run health checks before pushing. - **Atomic Compare-and-Swap (CAS) Leases:** Prevent duplicate work across machines with CAS claims carrying owner ID, contract hash, TTL, periodic heartbeat, and clock-skew margin (`expiry + clock_skew_margin`). Suggested default: atomic CAS pushes to non-branch Git refs; alternatives: Redis, etcd, DynamoDB, or Postgres conditional locks. - **Transient-Failure Resilience:** Distinguish confirmed lease loss from temporary network errors. Tolerate transient failures safely inside the lease TTL, reconcile observed remote state after ambiguous timeouts, retry a transient final claim renewal before discarding verified work, and bound each lease operation end-to-end. - **Landing-Time Provenance Deduplication:** Leases are an efficiency optimization, never the final landing guard. Inside the landing critical section, refresh remote history and inspect landing provenance; if the contract hash already landed via a peer, discard the duplicate cleanly. ### Multi-Repository & Sibling Coordination - **Read-Only Portable Sibling References:** Reference sibling repos read-only via relative paths or configured environment variables, never through shared mutable worktrees or hardcoded machine-local paths. - **Consumer-Driven Integration Gates:** Libraries prove readiness against reciprocal consumer workloads, recovery contracts, and packaged outputs in addition to standalone unit tests. - **Declared Artifact Freshness:** Rebuild untracked package outputs (`dist/`, wheels, generated artifacts) via `postLand` and post-pull/rollback/manual-update hooks so downstream consumers always test current builds. - **Branch Policy as a Safety Boundary:** Support branch-pinned workflows (hard rule: never push to `main`) for exploratory prototypes alongside normal integration workflows for shared libraries and services. - **Second-repo quickstart:** Make the target repository and branch explicit in `run` and `status` (by argument or config), and run external target repositories through the same continuous loop, planner, and repair path used for self-hosting instead of a weaker one-shot queue that pushes operators into writing wrapper scripts. Each target owns its checks, approved ambition, state namespace, and evidence. Use the same binary on two different fixture projects with different checks and overlapping goal IDs. Confirm status and provenance stay separate and neither run writes to a human checkout. --- ## 7. Chapter 6: Fleet Operations, Observability & Adversarial Proof ### Non-Blocking Event Stream & Observability Interface - **Cursor-Resumable Domain Events:** Emit a strictly ordered event projection so dashboards, brokers, webhooks, CLI tailers, or TUIs can disconnect and resume without gaps or reordering. Suggested default adapter: local HTTP dashboard streaming over SSE + JSONL event log; alternatives: WebSockets, Kafka/NATS, OpenTelemetry, or TUI. - **Never Let Observability Starve Workers:** Separate fast local read-only ledger status from asynchronous, cached remote VCS/network probes, isolate faults per repository, and enforce strict probe timeouts so monitoring can never trigger the latency or false-offline outage it reports. - **Opt-In Authenticated Steering:** Monitoring is read-only by default. Steering actions (retry, dismiss eligible untracked escalations, approve/reject parked changes, save config) require explicit opt-in flags, authentication, and revalidation against live authoritative state. - **Read-Only Telemetry & Development Story:** Expose read-only CLI/MCP tools returning bounded attempt evidence, friction summaries, and work-category distributions (feature, fix, refactor, docs, harness) so humans and planners spot drift early without granting write permissions. ### Fleet Supervision & Fail-Closed Upgrade Interlocks - **External Supervisor Interface:** The engine never restarts itself. An external supervisor (`launchd`, `systemd`, Kubernetes, Nomad, or fleet controller) owns process restarts and service definitions. - **Fail-Closed Rollout Protocol:** 1. Declare every project sharing the runtime executable. 2. Guard and drain all declared projects; retain upgrade blocks if any engine shutdown is unconfirmed. 3. Install the candidate runtime and verify it with `selfcheck`; on failure, roll back immediately and verify the restored runtime. 4. Reload supervisor service definitions deliberately so stale definitions cannot linger. 5. Gate completion fail-closed on every restarted checkout reporting the target version, a verified tip, and post-baseline landing progress. ### Mandatory Adversarial Proof Matrix An implementation is not ready until it proves all nine boundaries. Use real processes, storage and Git for integration faults and the declared finite model for scheduler enumeration. The fixture is a first check, not a substitute. | Boundary | Adversarial Fault Injection | Required Verified Outcome | | --- | --- | --- | | 1. Abrupt Process & Group Exit | `SIGKILL` orchestrator and separately its process group while a check command and its spawned subprocesses are stuck; simulate dangling SDK handles on shutdown | Zero leftover child or nested subprocesses; clean-exit backstop terminates orchestrator cleanly | | 2. Crash Failpoints & Wipes | Crash before commit or after ref advance but before ledger update. Separately land then engine-roll back with `Rollback-Of` stamped before health, and land then human-revert without it. Wipe the ledger and restart in both cases | No duplicate landings or rollback charges; still-current engine-rolled-back work requeues within its budget; human-reverted work stays done with no requeue or rollback charge; live work is skipped and revoked attempts cannot resume | | 3. Contract Edits & Fencing | Edit behavior or priority, or delete an active goal; submit writes and promotions with a stale fence and, after a wipe, with the old generation but the current numeric fence | Deletion frees the slot; behavioral edits supersede old work and feedback; priority edits preserve healthy work; both stale tuples are rejected atomically without changing ledger or ref | | 4. Fail-Closed Verification | Weaken tests; crash or time out the reviewer; return `{"accept":true}` without a reason, conflicting verdicts, a valid rejection, or a confirmed review outage | Gates catch weakened tests; no promotion without a valid accept; only the confirmed outage parks uncharged among reviewer failures; reviewer meets the approved error limits | | 5. Concurrent Landing & Rollback | Advance tip or change trusted policy during verification; touch mixed-policy paths; cause a rebase conflict and attempt an unauthorized reversal; land a broken engine change then an innocent one after a human commit | Current strictest policy wins; rebase conflict charges a retry with bounded backoff; unauthorized reversal blocks promotion and immediately goes to `needs-human`; promoted SHA equals the checked SHA; rollback charges only removed engine work | | 6. Stuckness, Flakes & Triage | Inject livelock, `A -> B -> A` oscillation, a worker crash, unexplained lease expiry, unknown provider error, confirmed host interruption/outage, and a shared check failure | Stuck work stops; unexplained failures charge and escalate within budget; confirmed interruption/outage is uncharged; one repair requeues affected tasks; triage stays bounded and read-only | | 7. Finite-State Scheduler Liveness | Enumerate every reachable state and successor in the declared finite model; test real missing and cyclic dependencies separately | Non-terminal states act or name a wake that changes eligibility; parked tasks cannot hide independent work; stale plans are discarded | | 8. Distributed Leases & Multi-Repo | Race two peers on one goal; inject transient renewal failure inside TTL and ambiguous push timeout; wake expired peer after peer landed; test stale sibling artifact | Exactly one CAS winner; transient renewal retries cleanly; late peer deduplicates via provenance at landing; post-land/pull/rollback hooks keep sibling artifacts fresh | | 9. Observability & Fleet Upgrades | Stall local VCS and remote network while observability polls; run upgrade with unconfirmed engine stop or failing `selfcheck` | Fast degraded local status never starves workers; upgrade stays blocked or rolls back and verifies restored runtime; post-restart readiness fails closed until version and landing progress confirm | ### Final Readiness Bar 1. All nine Adversarial Proof Matrix boundaries pass reliably under host contention. 2. `selfcheck` passes end-to-end in a throwaway repository and runs inside the engine's own health checks. 3. The engine self-hosts on its own repository through its full gate, independent reviewer, and health check. 4. A multi-hour hands-off soak across multiple repositories runs with native self-stewardship handling flakes, cascades, triage, and post-land rebuilds without manual babysitting.