← Context/ blueprints
Mail Archive in Cloudflare R2 — How Every Inbox Gets Into the Bucket and Stays Current
The laptop pulled the whole history; a Cloudflare Worker keeps it current every five minutes. This is how to pick it up from any computer.
Related: Email-Repository-and-Agent-Harness, A-Gateway-Between-Agents-and-My-Accounts.
How it fits together
Gmail (IMAP, read-only)
│ │
│ history │ new mail, every 5 min
▼ ▼
laptop: mail/kaymail.py Worker kay-os-mail-sync
~/.local/share/kay-os/mail cron */5 → one Durable Object per account
│ │
│ mail/r2.sh push │ writes directly
▼ ▼
───────────── R2 bucket kay-os-mail ─────────────History comes from the laptop. Gmail caps daily IMAP downloads, so a first backfill takes days.
mail/backfill.shretries through the cap.New mail comes from the Worker. It begins just past where the laptop's archive ended (the seed), so the two never overlap.
Read-only everywhere. Mailboxes open with
EXAMINEand bodies fetch withBODY.PEEK. Nothing marks, moves, or deletes mail.
Bucket layout (kay-os-mail)
| Key | What | Written by |
raw/<account>/<sha[:2]>/<sha>.eml | original message bytes, named by SHA-256 | r2.sh and the Worker (same paths) |
index/index.sqlite | the laptop's search index (full text of every message) | r2.sh push |
meta/<account>/<encodeURIComponent(mailbox)>/<uidvalidity>/<uid>.json | per-message metadata: uid, sha256, Gmail thread id, labels | Worker |
state/<account>/seed.json | {mailbox: {uidvalidity, lastUid}} where the laptop left off | uploaded once by hand |
state/<account>/status.json | the Worker's cursors, lastRun, fetched, lastError | Worker, every run |
Raw files never change once written, so pushes only add.
The Worker (sync-worker/)
src/index.ts: the cron handler fans out toMailboxSyncDurable Objects, one per address (idFromName(address)), so each account has at most one IMAP session at a time. The object keeps its cursor in Durable Object storage and copies it tostatus.json.src/sync.ts:syncAccount()handles one pass. It fetches up to 200 messages per run, in batches of 50. With no seed, or after a UIDVALIDITY change, it starts from now instead of refetching. On an error it keeps the progress so far and records the message inlastError.src/imap.ts,src/socket.ts: a minimal read-only IMAP client overcloudflare:sockets.wrangler.jsonc:workers_dev: falseandpreview_urls: false, so there is no public URL. Bindings: R2MAIL→kay-os-mail, Durable ObjectSYNC.Secret
ACCOUNTS: a JSON list of{address, password, host?}(Gmail app passwords). It is write-only once set. Currently it lists only mpstaton@gmail.com.
Tests use a fake Gmail and need no network: cd sync-worker && pnpm test && pnpm typecheck.
pnpm smoke runs the IMAP client against a real server and prints counts only.
Setting up another computer
Clone kay-os and check out
development.Install rclone (
brew install rclone,sudo pacman -S rclone; on NixOS r2.sh usesnix run), Node 22+, and pnpm.Create
kay-os/.env. It is gitignored and never committed. The values are in 1Password, vault Lossless Accounts, item "Cloudlfare kay-os-mail" (kzjkc4imuewgr7gdorgohh4w7u):BASHcd kay-os i="op://Lossless Accounts/kzjkc4imuewgr7gdorgohh4w7u" cat > .env <<EOF CLOUDFLARE_ACCOUNT_ID=$(op read "$i/Account ID") CLOUDFLARE_API_TOKEN=$(op read "$i/Your API Token") R2_ACCESS_KEY_ID=$(op read "$i/Access Key ID") R2_SECRET_ACCESS_KEY=$(op read "$i/Secret Access Key") R2_ENDPOINT=$(op read "$i/S3 API Endpoint") KAYOS_R2_BUCKET=kay-os-mail EOF chmod 600 .envWithout a
.env,r2.shandcf.shfall back to reading 1Password on each run.Check that it works:
BASHmail/r2.sh check # keys work, bucket listing (slow: ~400k objects) sync-worker/cf.sh whoami # Cloudflare account lossless-group cd sync-worker && pnpm install && pnpm testTo search mail on this machine, run
mail/r2.sh pullto get the index, ormail/r2.sh pull --rawto get every .eml as well.
The Artifacts repo for the agent harness is in the item
"Cloudlfare kay-os-mail-harness" (6cpphm6nmy6jqbmvn7kp23smwq), which holds
the Remote URL and initial token. Nothing uses it yet.
Everyday commands
# Is the Worker running? lastRun should be under 5 minutes old.
sync-worker/cf.sh tail # live logs: "<address>: fetched N"
rclone cat kayr2:kay-os-mail/state/mpstaton@gmail.com/status.json # with KAYR2 env from r2.sh
# Deploy after changing sync-worker/
cd sync-worker && pnpm test && pnpm typecheck && ./cf.sh deploy
# Change the account list (replaces the whole secret)
./cf.sh secret put ACCOUNTS # paste: [{"address":"...","password":"app password"}, ...]
# Laptop archive → R2 (only new files go up; the index is replaced)
mail/r2.sh pushTo make a seed for an account (run on the machine holding its archive):
sqlite3 ~/.local/share/kay-os/mail/index.sqlite \
"select json_group_object(mailbox, json_object('uidvalidity', uidvalidity, 'lastUid', m))
from (select mailbox, uidvalidity, max(uid) m from messages
where account='ADDRESS' group by mailbox, uidvalidity)" > seed.json
# upload to state/ADDRESS/seed.json, using rclone with the r2.sh remoteThe seed must exist before the account is added to ACCOUNTS. Without it,
the Worker's first run starts from now, and mail between the laptop's last
sync and that moment has to come from the laptop.
State as of 2026-11-07
| Account | Laptop | R2 raw/ | Cloud sync |
| mpstaton@gmail.com | 228,292, backfill done | 228,418 (includes new mail from the Worker) | on since 2026-11-07, cursor UID ≈815,369, no errors |
| michael@learnstart.vc | 170,150, ≈39k still to fetch | 170,150 | not yet |
The LearnStart backfill (mail/backfill.sh michael@learnstart.vc) runs on the
Omarchy laptop and stops at Gmail's daily OVERQUOTA. Rerunning it resumes.
Next
Finish the LearnStart backfill, then
mail/r2.sh push.Make and upload LearnStart's seed, then add it to
ACCOUNTS(hostis optional; it's Gmail).Make
r2.sh pushrun on a schedule on the syncing laptop (systemd timer), so the laptop's backfill reaches R2 without anyone remembering to push.Have the Worker write an index too. Today
index/index.sqlitecomes only from the laptop, so mail the Worker fetches is inraw/andmeta/but can't be searched until something indexes it.Read access for agents: the connector and gateway in A-Gateway-Between-Agents-and-My-Accounts.
Gotchas met so far
wrangler loginfails on this Linux machine because its callback listens only on[::1]:8976. Use the API token throughcf.shinstead.Overlapping
opcalls dismiss each other's 1Password prompts..envavoids that.The 1Password items moved to the Lossless Accounts vault, which gave them new IDs. If
r2.shcan't find its item, check the ID first.r2.sh checksizes every object, so it takes minutes on ~400k files.