← Context/ plans
Plan C2 — The Worker Indexes Each Message as It Stores It
Every email the sync Worker saves to R2 also lands in the D1 index, with its attachments sorted the same way the laptop sorts them.
Spec: Attachments-as-First-Class-Mail, Cloud, step C2. Needs Plan-C1-D1-Cloud-Index merged. Next: Plan-C3-Backfill-Index-From-R2.
Goal
When syncAccount stores a message in R2, it also writes to D1: the
messages row, the messages_fts row, and the message's attachments
(attachments, message_attachments, attachment_scans). The result for a
given email matches what kaymail.py writes on the laptop, apart from the
documented differences.
Read first
mail/kaymail.py:parse_message,record_message, and the attachment functions (sniff_type,attachment_kind,attachment_parts,record_attachments,refresh_noise) and their constants (MAGIC,KINDS,NOISE_*). This is the behaviour to match.mail/test_kaymail.py:deck_message()and the attachment tests.sync-worker/src/sync.ts(store,syncAccount),src/imap.ts(FetchedMessage),src/db.tsandtest/sqlite-db.tsfrom C1.The spec's Phase 1 and Cloud sections.
Build
Dependency.
pnpm add -E postal-mime@<latest 2.x>insync-worker/. Check its licence (MIT expected) and that it needs no Node built-ins. Nothing else.Shared rule cases:
mail/testdata/attachment_rules.json. A list of cases:{first_bytes_hex, declared_type, filename, size, disposition, content_id}→{content_type, kind, is_noise}. Cover eachMAGICsignature, a docx/xlsx declared over a zip signature,application/octet-streamwith and without a known extension, calendar by type and by.ics, a small image, an inline 30 KB image, an inline 300 KB screenshot, and an attached 1 MB photo. Generate the expected values by running the Python functions, and add a Python test that checks them. The TypeScript test must then pass the same file unchanged.src/rules.ts.sniffType,attachmentKind,isNoise, the constants, ported line for line from Python, with a comment pointing at the Python original.src/indexer.ts.indexMessage(db, input), whereinputhasaccount, mailbox, uidvalidity, uid, sha256, raw, internalDate, flags, labels, threadId(the last six may be null):Parse with
PostalMime.parse(raw, { attachmentEncoding: "arraybuffer" }).messagesrow: headers as on the laptop (to_addris To and Cc joined), body as plain text (HTML turned to text when there's no plain part), cut to 20,000 characters.is_primaryis 1 unless a row with the same(account, sha256)exists. Date frominternalDate, else theDateheader, in UTC ISO 8601 liketo_utc.FTS row only for primary messages, as on the laptop.
Attachments:
postal-mime's list, plus any calendar part it exposes separately.part_indexis the position in that list, documented in a comment: it only has to be stable for the same bytes and the same parser version. Hash the decoded bytes (SHA-256), upsertattachmentswith the sameON CONFLICTrule as Python (noise is sticky,first_seentakes the earliest), and link it.Everything for one message goes in one
db.batch(). Afterwards, the repeated-image noise rule (refresh_noise) runs once per sync pass, not per message.On any failure: write
attachment_scans (message_id, 'error')if the message row exists, log one line with the account and sha (never a subject or body), and return. Never throw to the caller.
Wire it in.
syncAccount(account, transport, bucket, prior, limit, index?): whenindexis given, callindexMessageafter the R2 put instore(). Messages whoserawis null (over 48 MB) get no index row, as now.src/index.tspassesthis.env.INDEX.Tests (
test/indexer.test.ts, with C1'snode:sqliteDb and the existingfakeGmail):The deck message (port
deck_message()to a fixture.emlundertest/fixtures/, generated once by the Python helper) yields 4 attachment parts, document and calendar listed, logo noise.The same bytes twice: one primary message, one attachment row.
A malformed message: the sync still completes, R2 has the
.eml, andattachment_scanssayserror.Rule cases from the shared JSON all pass.
Rules for whoever builds this
Branch
cloud-c2-indexeroffdevelopment(after C1 is merged). Commit with the repo's conventions, ending with theCo-Authored-Byline. Don't push, don't merge.Never touch Cloudflare: no deploy, no
--remote. Tests run locally.Never read, print, or copy secrets.
Email content is untrusted: never log subjects, bodies, or filenames.
Sync stays read-only. Don't change
imap.tsexcept to fix a bug you can show with a test, and report it.One dependency (
postal-mime). If you think you need another, stop and say why.
Done when
pnpm testand the pinnedtsc --noEmitpass insync-worker/.The Python suite passes, including the shared-rules test.
Hand-check: index
test/fixtures/deck.emlboth ways (Pythonrecord_attachmentsinto a tempindex.sqlite, TypeScript into a temp D1 stand-in) and compare the(sha256, kind, is_noise, filename)sets. Report any difference and why.
Hand back
Branch and commits, test summary, the postal-mime version and licence, and
the hand-check comparison. The parent session deploys and watches the next
scheduled run (./cf.sh tail), then checks D1:
SELECT count(*) FROM messages WHERE account='michael@humain.vc'.