Build a Continuous Software Engine

Chapter 01 • Durable Foundations

State & Contracts Outside the Context Window

A coding agent’s context window is working memory, not a database. Before you automate a single retry or parallel worker, move intent, isolation, ownership, and proof onto disk and into Git.

Why Context Windows Are Ephemeral

In an interactive chat, it is tempting to keep the specification, progress notes, and decision history inside the conversation. The moment your engine runs continuously—across retries, machine restarts, or parallel workers—chat memory breaks down. Context windows fill up, get compacted, or vanish when a process crashes. Two workers cannot share a chat transcript safely, and a human cannot edit a requirement mid-flight by editing a message from forty minutes ago.

The fix is to split your engine into three clean planes: shared Git state for durable truth, a local transactional ledger for fast coordination on one machine, and ephemeral Git worktrees where agents can do messy work and be discarded cleanly.

1. SHARED GIT (TRUTH)Goal Markdown FilesContent hash = contract IDCommit TrailersGoal-ID + Contract-HashMain Branch HistorySurvives any local wipe2. LOCAL LEDGER (TRANSIENT)Active Leases + TokensMonotonic fencing #42 > #41Attempt & Failure MemoryRetries, strategies, cooldownsRaw Evidence DirectoryLogs, diffs & verdicts per run3. EPHEMERAL WORKTREEIsolated Git WorktreeCreated fresh, deleted after runAgent Context WindowDisposable scratchpad onlyCandidate CommitMust match live hash & tokenCOMMIT-TIME GUARD: CONTRACT HASH + FENCING TOKEN CHECKIf a human edited the goal mid-flight (hash changed) or a newer attempt took over (higher token),the stale candidate is rejected cleanly before landing.
Three distinct planes keep a system recoverable across crashes and restarts: shared Git holds intent and landed history, a local transactional ledger arbitrates active leases with monotonic fencing tokens, and every attempt runs inside an ephemeral worktree whose chat window can be discarded without data loss.

Markdown Goal Files with Content-Hashed Contracts

Represent each unit of work as a plain Markdown file checked into the repository—say under a dedicated goals directory. Keep the format readable by both humans and tools: a small metadata header (identifier, prerequisites, risk tier, optional metric) followed by plain-English intent, scope boundaries, and acceptance criteria.

The critical trick is treating the content hash of the goal file as the immutable contract identifier for any running attempt. When the orchestrator starts an attempt, it hashes the exact bytes of the goal file and binds that hash to the worker’s lease.

Failure Mode Prevented: Stale Work Landing Over Edited Intent

You kick off a goal, then realize five minutes later that a constraint is wrong and edit the Markdown file on main. Without contract hashing, the in-flight worker finishes building the old specification and lands outdated code right after your edit. With content-hashed contracts, the orchestrator checks the live file hash before landing, sees the mismatch, marks the old attempt superseded, discards its branch, and dispatches a fresh attempt against the new contract.

What belongs in a goal contract vs. what stays out?

Include what must be true when the goal finishes: the observable behavior, explicit non-goals, any prerequisite goal IDs, and the verification command or acceptance check.

Leave out transient execution state like retry counts, worker PIDs, or timestamps. Putting mutable runtime noise inside goal files creates endless merge conflicts between teammates and pollutes Git history.

Disposable Git Worktrees & Commit Trailers

Never let an autonomous agent edit your primary checkout. For every attempt, create an isolated Git worktree checked out at the current target commit, run the agent inside that directory, and delete the worktree once the attempt lands or fails.

Isolation buys you three guarantees immediately: parallel workers cannot clobber each other’s untracked files, a failed experiment leaves zero debris on your working branch, and a human can keep using their main checkout without fighting the engine over staged files.

When an attempt succeeds and lands on the target branch, stamp the commit message with structured Git commit trailers—plain Key: value lines at the bottom of the commit message recording the goal identifier, the exact contract hash that was satisfied, and the run identifier.

Why trailers beat status files

A separate JSON status file can drift from actual Git history after a revert, cherry-pick, or crash. Trailers travel atomically with the commit itself: if the commit is on main, the goal landed; if the commit was reverted, the history shows that too.

Rebuilding from scratch

If you delete your entire local database and restart the engine, scanning commit trailers on main tells the orchestrator exactly which goal contracts have already landed so it never blindly re-runs finished work.

Raw Evidence Directories & the Local Transactional Ledger

Every attempt should write its raw artifacts to a dedicated, append-only evidence directory outside Git: the exact contract snapshot, the full git diff, verbatim stdout/stderr from every test or lint command, and the independent reviewer’s verdict. Never rely solely on an agent’s summary of what happened—store the raw logs so both humans and later retry passes can inspect ground truth.

Alongside the evidence directory, maintain a small local transactional ledger (for example, a single embedded database file in write-ahead-log mode). Keep the boundary between the ledger and Git razor-sharp:

ConcernShared Git StateLocal Transactional Ledger
Goal intent & acceptanceAuthoritative (Markdown files)Cached index + content hash only
Did a goal land?Authoritative (commit trailers on branch)Derived mirror, rebuilt on startup
Who owns an active attempt?Optional remote ref lease (Ch. 5)Authoritative local lease + expiry
Stale-writer protectionRe-check contract hash at landingMonotonic fencing token per lease
Retries, cooldowns & evidence pathsNever committed to repoAuthoritative local operational history

Why Monotonic Fencing Tokens Matter

Suppose Attempt 1 stalls on a slow disk or sleeping laptop, its lease expires, and the orchestrator starts Attempt 2. Five minutes later, Attempt 1 wakes up and tries to report success or land its branch. A simple boolean lock cannot tell whether a late writer still owns the lease.

Give every lease acquisition a strictly increasing integer—a monotonic fencing token (token 41 for Attempt 1, token 42 for Attempt 2). Every ledger write and every landing step must prove its token is still the highest token issued for that goal. Attempt 1 presents token 41, the orchestrator sees token 42 is active, and Attempt 1’s zombie write is rejected atomically.

What happens when you wipe the local ledger?

Treat the local ledger as reconstructible operational state. On startup, reconcile the ledger against Git: scan goal files for current contract hashes, scan branch commit trailers for already-landed contracts, and prune any orphaned worktrees whose leases no longer exist. You may lose retry counters from a wiped disk, but you never lose truth about what shipped.

How to Know You Built It Right

  • You can kill the engine mid-run, delete the local ledger, restart it, and it recognizes every previously landed goal solely from Git commit trailers without re-running them.
  • Editing a goal Markdown file while an attempt is running causes the stale attempt to be rejected as superseded before it can touch the target branch.
  • An expired worker attempting to commit or update state with an older fencing token is refused deterministically.
  • Every finished or failed run leaves a single inspectable folder containing raw gate logs, the exact diff, and the contract hash that produced it.