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:
| job | owner | lives for | failure mode |
|---|---|---|---|
| Do | one job per VM, one opencode run | 30–75 minutes | the VM dies; the job is re-claimed |
| Check | the lead: a Python policy engine | the session | restart it; it reads the same rows |
| Remember | Supabase Postgres | until you delete it | the 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.
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:
| record | what it answers | fields that matter |
|---|---|---|
| session | what are we doing, and until when? | goal, deadline, phase, lead_token, human_token |
| agent | which worker may claim? | role, token, model, ttl_min, last_seen |
| job | what is the next unit of work? | role, task_md, inputs, state, lease_until, dedupe |
| artifact | what proves it happened? | name, sha256, content or storage_path |
Four rules that keep it alive
- 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.
- 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. - 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.
- 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
pendingtoclaimedfor 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 minCreate 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.
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.sqlThe schema creates six tables, seventeen functions, and one important set of revokes:
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.
You should see six tables and a 401 on a table read:
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" # 401If 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 minA 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.
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;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 -1Two traps, both paid for in the example run:
psql -cdoes not interpolate:'goal'. Feed the SQL on stdin where variables work.insert … returningprints the row and theINSERT 0 1tag. Always take the first line.
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 minBefore 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.
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"]))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 minThe 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.
| move | what it does | why it matters |
|---|---|---|
| 1 claim | rpc_agent_claim, eight tries, five seconds apart | no job → exit; never invent work |
| 2 task | write task.md with an absolute-path header | the agent must not write into / |
| 3 inputs | materialise upstream files in the work dir | the agent reads files, not JSON prompts |
| 4 run | timeout 1500 opencode run --model … | a stuck model must not hold a lease forever |
| 5 heartbeat | renew the 14-minute lease every 45 s | the lead can tell “busy” from “dead” |
| 6 collect | ≤ 40 files; text ≤ 256 KB inline, binaries to Storage | the report stays small; the evidence does not |
| 7 report + die | one RPC, then IMDS id → terminate | nothing outlives its job |
The core is shorter than the table. This is the whole claim-and-report path:
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:
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:
#!/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.jsonagent = 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"]})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.pyThe 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 + bootNow 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:
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 25Two 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.
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 minThe 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.
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.
| phase | job | advance when | on failure |
|---|---|---|---|
| boot / research | researcher | candidates.json parses and lists ≥ 3 | retry once, then stop |
| shortlist | analyst | chosen.json exists | retry once |
| brand | brand, copy | both markdown artifacts exist | retry the missing one |
| build | builder | index.html ≥ 4 KB | retry once |
| qa | qa | result.json verdict PASS | one fix round, then publish what exists |
| publish | lead | index.html exists | write 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.
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 + TTLA gate is a short, boring function. If it is not short, it will grow opinions:
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"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 minYou 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.
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.
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)}`);
}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 minThe 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:
| role | model | ttl | artifact | gate |
|---|---|---|---|---|
| researcher | deepseek-free | 40 m | candidates.json | ≥ 3 candidates, evidence URLs |
| analyst | deepseek-free | 35 m | chosen.json | name + facts + risks present |
| brand | deepseek-free | 30 m | brand-kit.md | palette, type, voice, sections |
| copywriter | deepseek-free | 30 m | content.md | all required sections, no invented facts |
| builder | big-pickle | 75 m | index.html | ≥ 4 KB, single file |
| qa | deepseek-free | 40 m | result.json | verdict + 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:
# 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.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 elapsedCreate 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) | job | run | result |
|---|---|---|---|
| 18:28 | researcher | 553 s | 5 candidates from 38 fetches |
| 18:42 | analyst | 420 s | one subject, facts, risks |
| 18:54 | brand | 30 s | 1,108-word kit |
| 19:01 | copywriter | 112 s | full site copy |
| 19:08 | builder | 676 s | 53,761 B single file |
| 19:25 | qa | 1,571 s | 5 viewports, 9 issues, verdict PASS |
| 19:52 | lead | — | 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.
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
| symptom | cause | fix |
|---|---|---|
| launch rejected: metadata > 32,000 B | the bundle is inside cloud-init | upload it, boot with --bundle-url |
| syntax error at ":" | psql -c does not interpolate :'var' | feed SQL on stdin |
| job done, zero artifacts | subprocess(cwd=) does not set PWD | set PWD + absolute paths in the task header |
| opencode: command not found | sudo resets PATH | prepend the install dirs; use absolute paths |
| service restarts every 10 s | SELinux blocks append to /var/log | journald; set HOME in the unit |
| watchdog kills a live session | UTC parsed as local time | calendar.timegm; UTC end to end |
| third VM refused | tenancy core cap | serialise; probe the limit before parallelising |
| bundle upload 400 | bucket MIME allowlist | add application/gzip |
| claim returns null | role, assignment, or token mismatch | check the agent row and the job's assigned_to |
| job stuck claimed | worker died without reporting | wait for the 14-minute lease, then reap |
| terminate-all does nothing | pretty-printed JSON parsed as ids | parse one id per line; dry-run first |
| QA PASS, page unfinished | the gate only checks layout | content gates: placeholders and dead links fail |
| TTL did not fire | self-termination is intermittent | sweep by name prefix; confirm the instance list |
| no job after a lead restart | an early return in the phase logic | test every phase with a restart, not just a fresh boot |
The three that matter
- PWD. Silent. The agent “succeeds” and writes into
/. Nothing fails until the artifact count is zero. - UTC. A watchdog that is 5.5 hours wrong is worse than no watchdog. Store and compare Unix time; format only for display.
- Your own destructive command. The only outage in the reference run was a
terminate-alltest 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
anonhas no table grants. - Money: set
budget_usdand 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.
./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:
- The role table. One row per artifact you need. If two roles write the same file, you have a coordination bug disguised as parallelism.
- The gates. One function per artifact. If a gate cannot fail on a placeholder, it is not a content gate.
- 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/.