Suman Patra.writing / urja guide

● Writing · Urja build guide

Suman Patra · hands-on · 30 min read · 3–4 h to build · October 2026

Build the swarm yourself

A Postgres bus, a one-job worker, a deterministic lead, and a dashboard. By the end you will run a multi-agent session that survives every worker it starts.

No orchestration framework, no agent SDK. Every command below is one that ran; every step ends with a checkpoint you can verify before moving on. The example job is a website; the machine does not care what the job is.

The build pathEight steps from an empty Supabase project to a running session, each ending in a checkpoint.01PROJECTschema15 m✓02SESSIONtokens5 m✓03BUS TESTstate read5 m✓04WORKERone job30 m✓05FIRST VMsmoke20 m✓06LEADphases40 m✓07CONSOLEpoll + chat20 m✓08DEFINEroles + task10 m✓09RUNa real run1–2 hevery step ends with something you can verify
fig. 1. Nine steps. Skip a checkpoint and the next step will lie to you.

before you start

  • A new Supabase project (free plan is fine), its pooler host, user and password
  • psql, Python 3.11+, and one VM account (OCI or any cloud)
  • Docker and opencode on the VM image — the bootstrap installs both
  • One free model ID, e.g. opencode/deepseek-v4.1-flash-free
  • Three to four hours, and about a dollar of cloud

what you will have

Postgres tables
6
token-scoped RPCs
17
worker files
1
lead files
1
steps to a live session
9
example run, end to end
1 h 57 m
AI cost, free model pool
$0
box cost, example run
≈ $0.60

before you start

The shape of the machine

Three primitives, four contracts, and one rule that decides everything: state does not live on a worker.

Three primitives, kept apart

Strip any agent session to first principles and three jobs remain. Something has to do the work. Something has to check that the work happened. Something has to remember what occurred.

In this build, those jobs belong to different things:

jobownerlives forfailure mode
Doone job per VM, one opencode run30–75 minutesthe VM dies; the job is re-claimed
Checkthe lead: a Python policy enginethe sessionrestart it; it reads the same rows
RememberSupabase Postgresuntil you delete itthe only thing you must not lose

The worker is therefore allowed to be stupid. It knows one job, not the plan. It does not talk to other agents. It claims a row, does the thing, reports, and deletes its own VM. Everything clever is in the lead, and the lead is boring on purpose.

Four contractsA session owns agents; an agent claims a job; a job reports artifacts. Everything else is derived.SESSIONthe envelopegoal · deadlinelead tokenhuman token→AGENTone workerrole · modelrandom tokenTTL minutes→JOBone unit of worktask_md · inputsstate · attemptslease · dedupe→ARTIFACTthe proofname · mime · bytessha256content or Storagethe lead reads the state and writes the next job
fig. 2. Session owns agents. An agent claims a job. A job leaves artifacts. The lead reads all four.

The four contracts

You only need four records to run a session. If you can describe these, you can skip the rest of the schema and still understand the machine:

recordwhat it answersfields that matter
sessionwhat are we doing, and until when?goal, deadline, phase, lead_token, human_token
agentwhich worker may claim?role, token, model, ttl_min, last_seen
jobwhat is the next unit of work?role, task_md, inputs, state, lease_until, dedupe
artifactwhat proves it happened?name, sha256, content or storage_path

Four rules that keep it alive

  1. Build one vertical slice before the fleet. Bus call, one worker, one lead transition, on the real cloud and the real tenancy. This guide is ordered that way; do not parallelise it.
  2. The worker writes. The lead decides. A worker may report done; only a gate in the lead can advance the session. Never let a worker move the plan.
  3. Rows are the only memory. If a fact matters after the VM dies, write it to Postgres or Storage. Not to a log you will forget.
  4. Delete the VM, keep the session. A worker that outlives its job is a bill, not a feature. TTL and self-termination are part of the design.

Words used below

bus
The Postgres database plus the RPCs that read and write it. No message broker.
claim
One atomic update that moves a job from pending to claimed for one agent.
lease
An expiry on a claim. Expired claims go back to pending; the lead reaps them.
gate
A check in the lead that looks at an artifact and decides whether the phase may advance.
phase
A named stage of the plan: research, shortlist, brand, build, QA, publish.
artifact
A file a worker produced, stored inline (text) or by reference (binary), with a hash.

Before you type anything

  • Use a new Supabase project. You are about to create a public write path guarded only by tokens.
  • The publishable key is public by design. The database password is not. Never put it on a worker, in a bundle, or in this article's placeholders.
  • Set a budget and a deadline in the session row. The lead refuses to run past the deadline; your wallet has no such guard.
  • Put the code in git before the first launch. The example run did not, and that was its worst omission.

steps 1–3

The bus

One Postgres database, seventeen functions, two tokens. Build the smallest client before you build any agent.

Create the project and apply the schema

step 1 · 15 min

Create a Supabase project, then copy the pooler host, the database user, the password, and the publishable key. Use the pooler host: it survives a laptop network change, while the direct host does not.

bashapply the bus (idempotent)
export PGHOST='aws-0-<region>.pooler.supabase.com'
export PGUSER='postgres.<ref>'
export PGPASSWORD='<password>'      # keep this in your shell, never in a file
export PGDATABASE=postgres
export BUS='https://<ref>.supabase.co'
export KEY='<publishable-key>'
psql -v ON_ERROR_STOP=1 -f bus/schema.sql

The schema creates six tables, seventeen functions, and one important set of revokes:

sqlthe only security model you need
revoke all on public.sessions, public.agents, public.jobs,
              public.messages, public.artifacts, public.events
  from anon, authenticated;

revoke execute on all functions in schema public from public, anon, authenticated;
grant execute on function public.rpc_agent_claim(text, uuid) to anon;
-- ...and sixteen more named functions. No table access. Ever.

Why functions instead of tables? Because the key is in the browser. Every write goes through a security definer function that resolves a token to a session or an agent before doing anything. A leaked publishable key can knock on seventeen doors and open none without a token.

✓ checkpoint 1

You should see six tables and a 401 on a table read:

bashexpected
psql -c '\dt public.*'      # sessions agents jobs messages artifacts events
curl -s -o /dev/null -w '%{http_code}\n' \
  -H "apikey: $KEY" "$BUS/rest/v1/jobs"    # 401

If the table read returns rows, stop. Your grants are wrong and every later token is decoration.

Create a session and its tokens

step 2 · 5 min

A session is one goal with a deadline and two random tokens. Generate them in SQL; do not invent them in your head. Save the block below as session.sql; the command after it reads that file on stdin.

sqlsession.sql — feed it on stdin
insert into public.sessions(goal, deadline, budget_usd, lead_token, human_token)
values (:'goal', :'deadline'::timestamptz, 5,
        encode(gen_random_bytes(16), 'hex'),
        encode(gen_random_bytes(16), 'hex'))
returning id, lead_token, human_token;
bashrun it
psql -At -F' ' -v goal='build one page' \
  -v deadline="$(python3 -c "import datetime;print((datetime.datetime.utcnow()+datetime.timedelta(hours=5)).strftime('%Y-%m-%dT%H:%M:%SZ'))")" \
  < session.sql | head -1

Two traps, both paid for in the example run:

  • psql -c does not interpolate :'goal'. Feed the SQL on stdin where variables work.
  • insert … returning prints the row and the INSERT 0 1 tag. Always take the first line.
✓ checkpoint 2

One session row, two 32-hex tokens, a deadline five hours out. Save the id and both tokens in a file you will delete later. The lead token never leaves the lead VM; the human token goes in the dashboard URL fragment.

Read the state from your laptop

step 3 · 5 min

Before a worker exists, prove the bus from the machine you are sitting at. This is the smallest possible client: one POST, two headers, a token.

pythonbus.py — the whole client
import json, urllib.request

BUS = "https://<ref>.supabase.co"
KEY = "<publishable-key>"

def rpc(name, payload):
    req = urllib.request.Request(
        f"{BUS}/rest/v1/rpc/{name}", data=json.dumps(payload).encode(),
        headers={"apikey": KEY, "Authorization": "Bearer " + KEY,
                 "Content-Type": "application/json"}, method="POST")
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read() or b"null")

state = rpc("rpc_human_state", {"p_human_token": "<human-token>"})
print(state["session"]["phase"], state["session"]["deadline"])
print("agents", len(state["agents"]), "jobs", len(state["jobs"]))
✓ checkpoint 3

boot 2026-…Z, agents 0 jobs 0. If you get bad human token, the token is truncated or belongs to another project. Fix it here, not in the worker.

steps 4–5

The worker

One job, one VM, one run. The worker is deliberately the least clever part of the system.

Build the one-job worker

step 4 · 30 min

The worker is a Python file with no opinions. It claims exactly one job, writes the task to disk, runs opencode under a timeout, collects the files, reports once, and terminates its own VM. It never reads the phase, never talks to another agent, and never decides what happens next.

movewhat it doeswhy it matters
1 claimrpc_agent_claim, eight tries, five seconds apartno job → exit; never invent work
2 taskwrite task.md with an absolute-path headerthe agent must not write into /
3 inputsmaterialise upstream files in the work dirthe agent reads files, not JSON prompts
4 runtimeout 1500 opencode run --model …a stuck model must not hold a lease forever
5 heartbeatrenew the 14-minute lease every 45 sthe lead can tell “busy” from “dead”
6 collect≤ 40 files; text ≤ 256 KB inline, binaries to Storagethe report stays small; the evidence does not
7 report + dieone RPC, then IMDS id → terminatenothing outlives its job

The core is shorter than the table. This is the whole claim-and-report path:

pythonworker/agent-worker.py (abridged)
job = rpc("rpc_agent_claim", {"p_token": TOKEN})["job"]
if not job:
    return 0

open("task.md", "w").write(HEADER + job["task_md"])       # HEADER sets the absolute workdir
for name, content in (job["inputs"].get("files") or {}).items():
    open(name, "w").write(content)                        # upstream artifacts as files

rc = subprocess.call(
    ["timeout", str(MAX_RUN), OPENCODE, "run", "--model", MODEL,
     open("task.md").read()], cwd=WORK)

arts = collect()                                          # sha256 + inline/Storage routing
state = "done" if rc == 0 else "failed"
rpc("rpc_agent_report", {
    "p_token": TOKEN, "p_job": job["id"], "p_state": state,
    "p_result": {"rc": rc, "files": [a["name"] for a in arts]},
    "p_message": summary, "p_artifacts": arts})
self_terminate()

Three environment variables are not optional. The worker sets PWD itself because subprocess(cwd=…) does not update it, and it prepends the install directories because sudo resets PATH:

pythonthe two silent bugs
os.environ["PATH"] = ":".join(["/home/opc/.opencode/bin", "/usr/local/bin",
                               "/usr/bin", "/bin", "/usr/sbin", "/sbin"])
os.environ["PWD"] = WORK
os.environ["HOME"] = os.environ.get("HOME") or "/home/opc"

Now prove the worker before paying for a VM. Create a smoke agent and one job, then run the worker on your laptop against the bus. Use a stub instead of opencode so the test costs nothing:

bash/tmp/fake-opencode
#!/usr/bin/env bash
# ignores the prompt; proves claim → collect → report without a model
echo "WORKER_OK" > result.md
printf '{"ok": true, "at": "%s"}\n' "$(date -u +%FT%TZ)" > probe.json
pythoncreate the smoke agent + job
agent = rpc("rpc_lead_agent_create", {
    "p_token": LEAD, "p_role": "smoke", "p_model": "none", "p_ttl": 25})
rpc("rpc_lead_enqueue", {
    "p_token": LEAD, "p_role": "smoke", "p_title": "smoke job",
    "p_task_md": "Write result.md containing WORKER_OK. Do not ask questions.",
    "p_dedupe": "smoke-local-1", "p_agent": agent["id"]})
bashrun the worker locally
export URJA_BUS="https://<ref>.supabase.co" URJA_KEY="<publishable-key>"
export URJA_TOKEN="<agent-token>" URJA_ROLE=smoke URJA_SESSION="<session-id>"
export URJA_WORK=/tmp/urja-work URJA_MAX_RUN=120 URJA_OPENCODE=/tmp/fake-opencode
export URJA_MODEL=none
mkdir -p "$URJA_WORK"
chmod +x /tmp/fake-opencode
python3 worker/agent-worker.py
✓ checkpoint 4

The worker logs claimed …: smoke job, opencode rc=0 in 0s, reported done with 2 artifacts. In the bus, the job is done and two artifacts exist with SHA-256 values. On a laptop it also logs no oci cli; relying on TTL and exits; that is correct.

If the job stays claimed, the report failed. If it is done with zero artifacts, your PWD is wrong — the files went somewhere else.

Run the worker on a real VM

step 5 · 20 min + boot

Now put the same file on a disposable VM. The VM image needs Docker, the oci CLI, and opencode; the bootstrap in the example repo installs all three. Package the worker and a role bootstrap into a small tarball, then pass an env file:

bashbundle + launch
tar czf run/urja-worker.tgz worker bootstrap-worker.sh

cat > run/smoke.env <<'EOF'
URJA_BUS=https://<ref>.supabase.co
URJA_KEY=<publishable-key>
URJA_TOKEN=<agent-token>
URJA_ROLE=smoke
URJA_MODEL=opencode/deepseek-v4.1-flash-free
URJA_WORK=/home/opc/work
URJA_MAX_RUN=900
URJA_SESSION=<session-id>
URJA_REGION=<region>
EOF
chmod 600 run/smoke.env

./agent-vm.sh launch --bundle run/urja-worker.tgz \
  --bootstrap bootstrap-worker.sh --env-file run/smoke.env \
  --name urja-smoke --ttl 25

Two details decide whether this works:

  • Do not put the bundle in cloud-init. The metadata service rejects user data over 32,000 bytes; a base64 worker bundle blows past it. Upload the tarball to Storage and boot with --bundle-url, or launch with the local bundle flag the tool supports.
  • The env file is 600 and never contains the database password. The worker only needs the publishable key and its own token.
✓ checkpoint 5

Watch the job, not the VM. Within about six minutes: pending → claimed → done, two artifacts, and the instance reaches TERMINATED without you touching it. If the job is claimed but the artifacts are empty, check the task header and PWD. If the claim never happens, the agent token and role do not match the job.

steps 6–7

The lead

A coordinator that reads the database every fifteen seconds and applies rules. No conversation, no model call, no hidden state.

Build the policy engine

step 6 · 40 min

The lead is a loop with six moves. It never “thinks”; it reads rows and applies the phase rules. That is what makes it restartable: kill it, start it again, and it resumes from the same state.

The lead tickEvery fifteen seconds the lead beats the session, reaps expired leases, reads state, heals dead assignments, checks the deadline, then applies the phase rules.01 BEATsession updated_at02 REAPexpired leases03 READthe whole state04 HEALdead assignments05 DEADLINEpublish what exists06 PHASEspawn / advance15 sone passthe coordinator is a loop over the database, not over a conversation
fig. 3. One tick. If a move fails, the next tick tries again; the database is the retry buffer.
pythonlead/lead.py (skeleton)
TICK = 15

while True:
    rpc("rpc_lead_beat", {"p_token": LEAD})
    rpc("rpc_lead_reap", {"p_token": LEAD})
    s = rpc("rpc_lead_state", {"p_token": LEAD})
    heal_orphans(s)                      # a job assigned to a dead agent gets a new VM

    if now() > deadline_ts() - 600:      # ten minutes before the deadline
        publish(s, forced=True)
        return

    phase = s["session"]["phase"]
    jobs = {j["dedupe"]: j for j in s["jobs"] if j.get("dedupe")}

    if phase in ("boot", "research"):
        j = jobs.get("research-1")
        if j is None:
            spawn("researcher", RESEARCH, dedupe="research-1", ttl=40)
        elif j["state"] == "done":
            candidates = artifact_json(s, "candidates.json")
            if len(candidates["candidates"]) < 3:
                return fail("not enough candidates")
            phase("shortlist", 20)
    # ...the other phases follow the same shape

    time.sleep(TICK)

Each phase has one job, one artifact, and one question. If the artifact answers the question, advance; if the job failed, replace the worker or stop.

phasejobadvance whenon failure
boot / researchresearchercandidates.json parses and lists ≥ 3retry once, then stop
shortlistanalystchosen.json existsretry once
brandbrand, copyboth markdown artifacts existretry the missing one
buildbuilderindex.html ≥ 4 KBretry once
qaqaresult.json verdict PASSone fix round, then publish what exists
publishleadindex.html existswrite the report and stop

Spawning is two writes and one launch. The order matters: create the agent, enqueue the job with a dedupe key and an assignment, then start the VM. The dedupe key is what makes a restarted lead safe.

pythonspawn() — idempotent by construction
agent = rpc("rpc_lead_agent_create", {"p_token": LEAD, "p_role": role,
                                      "p_model": model, "p_ttl": ttl})
job = rpc("rpc_lead_enqueue", {
    "p_token": LEAD, "p_role": role, "p_title": title, "p_task_md": task,
    "p_inputs": inputs, "p_dedupe": key, "p_agent": agent["id"]})
launch_vm(agent, name)                   # bootstrap + /etc/urja.env + TTL

A gate is a short, boring function. If it is not short, it will grow opinions:

pythona content gate, not a vibe check
def gate_candidates(s):
    a = artifact(s, "candidates.json")
    if not a:
        return False, "researcher left no candidates.json"
    try:
        n = len(json.loads(a["content"])["candidates"])
    except Exception:
        return False, "candidates.json is not valid JSON"
    return n >= 3, f"{n} candidates"
✓ checkpoint 6

Start the lead. Within one tick it writes phase=research, creates one agent row, and enqueues one job with dedupe=research-1. Kill it, start it again: it must not create a second research job. If it does, your dedupe index is missing or the enqueue is not using it.

Serve a dashboard the human can trust

step 7 · 20 min

You do not need websockets. Poll one RPC every three seconds and render the state. The human token goes in the URL fragment, so it never reaches the server's access log.

javascriptthe whole dashboard loop
const token = location.hash.slice(3);
async function tick() {
  const s = await rpc("rpc_human_state", { p_human_token: token });
  document.querySelector("#phase").textContent =
    `${s.session.phase} · ${s.session.phase_pct}%`;
  renderAgents(s.agents); renderJobs(s.jobs); renderFeed(s.events);
}
tick(); setInterval(tick, 3000);

Chat is one insert and one read. The human writes a message; the lead reads unread messages on its next tick and answers with a status. There is no command channel, and that is deliberate. rpc() is the same POST helper from Step 3, with the same headers.

javascriptone message, no control plane
await rpc("rpc_human_say", { p_human_token: token, p_body: "how is it going?" });

// on the lead, inside the tick:
for (const m of rpc("rpc_lead_read", { p_token: LEAD, p_to: "lead" })["messages"]) {
  reply(`phase ${state.session.phase} · jobs ${countStates(state.jobs)}`);
}
✓ checkpoint 7

Open http://<lead-ip>/#t=<human-token>. You see the phase, the agent rows, the job queue, and the event feed. Send “status”. Within fifteen seconds the lead replies with the phase and job counts. If the page is blank, check the token in the fragment and the browser console for a 401.

steps 8–9

Run it

Pick a job, write its contract, and let the machine spend a couple of hours doing the work you would have done badly at 2 a.m.

Write the roles and the task contract

step 8 · 10 min

The machine is generic; the plan is yours. A role is one agent type with one job shape, one model, one time budget, and one artifact that proves it worked. Six roles were enough for a website:

rolemodelttlartifactgate
researcherdeepseek-free40 mcandidates.json≥ 3 candidates, evidence URLs
analystdeepseek-free35 mchosen.jsonname + facts + risks present
branddeepseek-free30 mbrand-kit.mdpalette, type, voice, sections
copywriterdeepseek-free30 mcontent.mdall required sections, no invented facts
builderbig-pickle75 mindex.html≥ 4 KB, single file
qadeepseek-free40 mresult.jsonverdict + issues + screenshots

The task is a contract, not a wish. Every task in the example run had five sections, and the working-directory header was added by the worker, not by you:

markdowna task that can be graded
# Mission
One sentence: what this agent is responsible for.

# Inputs
Files in this directory: chosen.json, content.md …

# Output (exact names)
- result.md      max 10 lines, what you did
- out.json       the structured artifact the gate reads

# Rules
Never invent a fact, price, quote or URL. If a source is blocked, record it.
Write every file with an absolute path under /home/opc/work.

# Done when
The output files exist and the gate in the lead can read them.
✓ checkpoint 8

Read your task as if you were the gate. Can you answer “did this work?” from the named files alone? If not, the gate will be a vibe check and you will ship a page with placeholders.

Run it end to end

step 9 · 1–2 h elapsed

Create the session with a deadline, launch the lead with a five-hour TTL, and watch. The lead will do the hiring; your only job is to answer messages and resist the urge to hand-fix an app file. In the reference run, seven jobs ran in this order:

time (UTC)jobrunresult
18:28researcher553 s5 candidates from 38 fetches
18:42analyst420 sone subject, facts, risks
18:54brand30 s1,108-word kit
19:01copywriter112 sfull site copy
19:08builder676 s53,761 B single file
19:25qa1,571 s5 viewports, 9 issues, verdict PASS
19:52lead—published, phase done

Two workers died on the way (18:55 and 19:19) because the tenancy refused a third concurrent VM. The lead created replacements and re-assigned the same job rows; both finished. That is the whole point of putting the job in Postgres.

When the last gate passes, the lead publishes. Decide in advance what “publish” means, because it is two different operations:

  • Rendered: copy the HTML to the dashboard host. Easy to look at, dies with the VM.
  • Durable: upload the same bytes to Storage or a static host. Survives, may not render HTML (Storage serves it as text/plain).

Write the same SHA-256 for both, and say which one is the demo and which one is the record.

✓ checkpoint 9

Phase done at 100%. The artifact table has the final file; the hash on disk matches the hash in the row; the report names every job and its attempts. If the phase is done but the copy is unfinished, your QA gate was too narrow — see the next section.

after the run

When it breaks

These are not model failures. They are edges between systems, and they all look like work until you check the artifacts.

The failures you will actually hit

symptomcausefix
launch rejected: metadata > 32,000 Bthe bundle is inside cloud-initupload it, boot with --bundle-url
syntax error at ":"psql -c does not interpolate :'var'feed SQL on stdin
job done, zero artifactssubprocess(cwd=) does not set PWDset PWD + absolute paths in the task header
opencode: command not foundsudo resets PATHprepend the install dirs; use absolute paths
service restarts every 10 sSELinux blocks append to /var/logjournald; set HOME in the unit
watchdog kills a live sessionUTC parsed as local timecalendar.timegm; UTC end to end
third VM refusedtenancy core capserialise; probe the limit before parallelising
bundle upload 400bucket MIME allowlistadd application/gzip
claim returns nullrole, assignment, or token mismatchcheck the agent row and the job's assigned_to
job stuck claimedworker died without reportingwait for the 14-minute lease, then reap
terminate-all does nothingpretty-printed JSON parsed as idsparse one id per line; dry-run first
QA PASS, page unfinishedthe gate only checks layoutcontent gates: placeholders and dead links fail
TTL did not fireself-termination is intermittentsweep by name prefix; confirm the instance list
no job after a lead restartan early return in the phase logictest every phase with a restart, not just a fresh boot

The three that matter

  1. PWD. Silent. The agent “succeeds” and writes into /. Nothing fails until the artifact count is zero.
  2. UTC. A watchdog that is 5.5 hours wrong is worse than no watchdog. Store and compare Unix time; format only for display.
  3. Your own destructive command. The only outage in the reference run was a terminate-all test against the live session. Dry-run by default, print the plan, require a second word.

Safety and cleanup

  • Secrets: the db password never leaves your laptop; worker env files are 600; the publishable key is public only because anon has no table grants.
  • Money: set budget_usd and a deadline; the lead publishes what exists ten minutes before the deadline instead of running forever.
  • Teardown: terminate by name prefix, then list instances and confirm. A TTL is a backstop, not a guarantee.
  • Record: capture the artifact table, the report, and the hashes before you delete anything. The box is not the run.
bashwind down
./agent-vm.sh terminate-all urja-            # prints the plan first
oci compute instance list -c "$COMPARTMENT" --all \
  | grep -c '"lifecycle-state": "RUNNING"'   # must be 0
psql -c "select phase, status from sessions order by created_at desc limit 1"

Make it yours

The machine does not know what a wedding is. To point it at your own job, change three things:

  1. The role table. One row per artifact you need. If two roles write the same file, you have a coordination bug disguised as parallelism.
  2. The gates. One function per artifact. If a gate cannot fail on a placeholder, it is not a content gate.
  3. The task templates. Exact output names, absolute paths, and a “done when” line the gate can read.

Then keep the rest: one job per VM, fourteen-minute leases, dedupe keys, a deadline guard, and a lead that never calls a model.

The full engineering story — what the reference run produced, the two agent deaths and retries, the green QA gate over broken copy — is in the three-part write-up. The code is in bus/schema.sql, worker/agent-worker.py, lead/lead.py, and tools/.