# 33.3 Build it with Claude Code, step by step (/affordable-self-improving-ai-workers/building-a-durable-ai-worker/build-it-step-by-step)

---
type: Document
title: "33.3 Build it with Claude Code, step by step"
description: "Three build steps with Claude Code: scaffold the Worker, host Pi Durable in a Durable Object with PiHarness and Lifecycle, and add the invoice tools with saved idempotency keys. Each step shows the prompt, the result, what to check and what goes wrong."
status: stable
order: 433.03
ksor:
  owner: team:panaversity
  audience: [ public ]
  approval:
    by: process:panaversity
    at: 2026-11-30T08:18:55Z
chapter: "33"
part: IV
expert_status: manager
concepts: [ "33.3" ]
last_verified: 2026-11-29
sources:
  - id: paper
    title: "Building Affordable, Self-Improving AI Workers (Panaversity, 29 November 2026), sections 6.1 and 6.4"
    resource: "Panaversity paper, version 1.0, 29 November 2026 (not yet published)"
  - id: pi-harness
    title: "Pi harness (Cloudflare Agents documentation, verified 2026-11-29)"
    resource: https://developers.cloudflare.com/agents/harnesses/pi/
generated:
  at: 2026-11-30T08:18:55Z
  by: human:zia
trust_tier: unverified
build_id: sha256:d6ce3f28a2cf8e492a60bae1b426b7cc6466e35e83d70c3b9763db2c55009f4b
dirty: true
ksor_version: 0.0.60
---

**In everyday life.** A site manager does not hand the builders the whole drawing and leave for a month. The foundation is checked before the walls go up, and the walls before the roof.

**What you will learn.** How to build the worker in small steps with Claude Code, and what to check after each one.

**Why it matters.** A small step has a small review. If you ask for the whole worker at once, you get two thousand lines to read, and you will not read them.

Every step below has the same shape: **the prompt** you send, **what Claude Code produced** (shortened), **what to check**, and **what usually goes wrong**. The code shown was tested for this book with `agents` 0.34.1 and Pi Durable 1.6.1.

### Step 1. Scaffold the Worker

> Step 1. Read CLAUDE.md and spec.md. Create a Cloudflare Worker in src/worker.ts with one Durable Object class, ApWorker, using SQLite storage. In wrangler.jsonc, add its binding and a migration next to the lab's ledger. Use the pinned packages. Do not add the tools yet. Run npm test: the tests should still fail, but the project must build.

**What Claude Code produced.** A binding for `ApWorker` (the name the Worker's code uses to reach the object), and a migration (Wrangler's record of which object classes exist; not the SQL migration of 33.4) that creates the class with SQLite storage. They sit next to the two objects the lab ships: the test ledger and a local stand-in for Postgres. It also made an empty `ApWorker` class.

```jsonc
{
  "name": "brightline-ap",
  "main": "src/worker.ts",
  "compatibility_date": "2026-11-20",
  "compatibility_flags": ["nodejs_compat"],
  "durable_objects": { "bindings": [
    { "name": "AP_WORKER", "class_name": "ApWorker" },  // added in Step 1
    { "name": "LEDGER", "class_name": "Ledger" },        // shipped with the lab
    { "name": "RECORDS", "class_name": "Records" }       // shipped: local Postgres stand-in
  ] },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ApWorker", "Ledger", "Records"] }],
  "vars": { "MODEL": "haiku" }
}
```

**What to check.** Open `package.json`. The versions should be `agents` 0.34.x and Pi Durable 1.6.x, as `CLAUDE.md` says, not `latest`. Pi 1.7.0 came out two days before this page was written, and `agents` 0.34 does not support it yet.

**What usually goes wrong.** Claude Code installs the newest Pi because it is newest. The build then fails with a version error from `agents`. Tell it to read `CLAUDE.md` again.

### Step 2. Host Pi Durable in the Durable Object

> Step 2. Read node_modules/agents/docs/harnesses/pi.md first. In ApWorker, host Pi Durable with PiHarness and Lifecycle on the plain DurableObject class. Do not use the full Agent class. Create the Pi registry inside the object. Use the model setting from spec.md, and the recorded answers in tests. Add submit, wait and status methods.

**What Claude Code produced.**

```ts
export class ApWorker extends DurableObject<Env> {
  registry = createRegistry();            // one registry per object

  harness = new PiHarness({
    harness: ({ storage, context, onWake }) => {
      const models = createModels();
      configureModel(models, this.env);   // Haiku live, recorded answers in tests
      installApTools(this.registry, this);
      return Harness.open(storage, { models, registry: this.registry, onWake }, context);
    },
    defaults: { model: workerModel(this.env), maxTurns: 12 },
  });

  lifecycle = Lifecycle.install(this).use(this.harness);

  submit(text: string, operationId: string) {
    return this.harness.submit(text, { operationId });
  }
}
```

Three lines carry the design. `PiHarness` gives Pi Durable the object's SQLite storage, so every checkpoint is saved inside the object. `Lifecycle` connects Pi to the object's alarm, so Pi can wake the object after a crash or when a deadline passes, with no request from outside. `maxTurns: 12` is the budget line of the spec.

**Why not the full `Agent` class?** Cloudflare's `Agent` class adds chat, scheduling and state sync for apps with a user interface. This worker has none. The paper's section 6.4 hosts Pi on a plain Durable Object, which has fewer moving parts to review.

**What to check.** Where is the registry created? The registry is the list where Pi finds each tool by its name. It must be a field of the object, never a variable at the top of the file. A registry at module scope is shared by every object in the same process, and one conversation's tools can then see another's state. Where does `submit` take its `operationId`? It must come from the caller, so that a message sent twice is accepted once.

**What usually goes wrong.** Claude Code writes `new Harness(...)` or `harness.run(...)` from memory. Neither exists in 1.6. The build fails, or worse, a test passes by accident. The fix is the line in `CLAUDE.md`: read the installed docs, never guess a Pi API.

### Step 3. Add the invoice tools

> Step 3. Add the four tools from spec.md in src/tools/. lookup_invoice and match_po read only. post_invoice must save its idempotency key with api.memo() before it calls the ledger, and send the key with the call. Leave request_approval as a stub that approves at once; we build it properly next. Run tests 1, 6 and 7.

**What Claude Code produced** for the tool that moves money:

```ts
export const postInvoice = (ledger: () => LedgerStub) => ({
  name: "post_invoice",
  description: "Post an approved invoice for payment. Changes the ledger.",
  parameters: obj({ invoice: str() }),
  replay: "safe", // safe only because the key below is saved before the call
  async execute({ invoice }, api, context) {
    const key = await api.memo("post.key", crypto.randomUUID(), context);
    const res = await ledger().post(key, invoice);
    return { output: [{ type: "text",
      text: `${invoice} ${res.posted ? "posted" : "already posted"}` }] };
  },
});
```

Read the first line of `execute` slowly. The first time the tool runs, `api.memo` saves a new random key under the name `post.key` and returns it. If the object dies after the ledger call, Pi runs the tool again after the restart. This time `api.memo` finds the saved key and returns the *same* one. The ledger sees a key it knows, and answers "already posted".

When we tested this, the crash came right after the ledger call. The ledger showed **one post and two post calls**, and the worker's final message said "already posted". That is test 1 passing for the right reason.

**What to check.**

- Every tool marked `replay: "safe"` either changes nothing, or saves its key with `api.memo()` before its outside call.
- The key is sent *to* the outside system. A key saved but not sent protects nothing.
- The outside system really refuses a key it has seen. Here it is your ledger. With a real bank or accounting API, read its documentation on idempotency keys, and how long it keeps them.

**What usually goes wrong.** The most common version looks harmless:

```ts
const res = await ledger().post(crypto.randomUUID(), invoice); // wrong
```

It passes every test that does not crash. It pays twice after the first crash that does.

> **The invariant.** Save the key, then act. A tool that acts first and saves later is not replay-safe, whatever it is marked.

**Check yourself.** Claude Code saves the key with `api.memo()`, but *after* the ledger call, to record what was sent. Is the tool replay-safe? *(No. If the object dies between the call and the memo, the rerun makes a new key and posts again.)*
