Skip to content

feat(integrations): patches save IMAP attachments into their files - #1264

Merged
allisonmahmood merged 22 commits into
mainfrom
feat/imap-attachments
Nov 7, 2026
Merged

allisonmahmood merged 22 commits into
mainfrom
feat/imap-attachments

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Nov 6, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #1262 (reads), which is stacked on #1266 (#1251's connections and pages). Review only this PR's diff.

Rebased onto #1266 at f9897e7 with #1262 at d05caa3; the commit ids below are the rebased ones. Rebasing added 0ac096f: #1266 gave each integration's recent calls an intro saying what its calls keep, and IMAP's now says a stage keeps its size, never its filename or upload token.

What changed

A patch could read a company mailbox (#1262), but not keep what came attached: invoices arrive as PDFs, and a patch had no way to save one. Now a tier 2 action stages a message's attachment and adopts it into the patch's own file store, byte for byte, in patchy dev and published.

How it works:

  • stageAttachment({ ref, part }) answers { upload, size, sha256, contentType, filename }. The part is checked against the message's current BODYSTRUCTURE: the wire takes numbered sections only, never HEADER, TEXT or .MIME, and a forwarded message's container is refused while its own parts stage. Patchy downloads the part through the call's session, under its gates, recheck and destroy rules, decoded by BINARY where the server offers it, in 1 MiB chunks, with ImapFlow's byte bound one past 20 MiB, so a larger part answers too_large and is never staged cut.
  • Host staging. The bytes stage through a new internal Files entry point, FileStaging, which shares the page staging route's code: the same reservation, quotas (16 uploads and 100 MiB per viewer per patch), one-hour expiry and single-use adoption. Only the Upload crosses into workerd; the action adopts it with ctx.files.<store>.put(name, upload).
  • Bounds. imap.download.chunk (1 MiB, held within imap.parser.literal by a test) and imap.attachments.concurrent (4 per process, from download to staging) join the limits registry.
  • patchy dev. The dev door gets a private byte transport: the instance downloads the part and answers its bytes, at most 20 MiB, with their size and sha256. The dev daemon stages them in its local store only once they match. JSON results keep their 8 MiB bound.
  • Recent calls record a stage's size, in a new nullable bytes column (migration 0035), never its filename or Upload. Wide events carry stagedBytes.
  • The patchy-imap skill covers staging, names by ref and part, and the refusals, and carries one complete reference importer. That importer is word for word the imap scenario's (a test holds the two equal), and the live tier runs it from the skill.

Part of #1250
Closes #1253

Look at

The screenshots, the patchy dev runs and the saved-file digests are fresh at 0ac096f, on a new pnpm dev up imap that connected the mailbox through #1266's connect form. The flags table is from the earlier run at 2173289; nothing since changes how a download opens or fetches.

The saved files match the source, byte for byte

The imap scenario's invoice inbox imported INBOX through patchy dev and saved its attachments. Each file's sha256, as staged and as read back from the store, against the sha256 of the attachment the scenario's mail server holds:

File Size Source sha256 Staged Stored
factura-2026-0412.pdf 61 001d1549…ebe551e0 same same
INV-88213.pdf 61 58a4e8da…81f29230 same same
Rechnung-7731.pdf 54 d77679de…3155fc10 same same
$ patchy dev agent importAttachments '{"folder":"INBOX","since":"2026-10-01"}'
{ "result": { "imported": 4, "done": true, "stopped": null }, "version": 1 }

$ patchy dev agent savedAttachments
{ "result": [
    { "filename": "Rechnung-7731.pdf", "size": 54, "file": "INBOX.1794003292/4/2",
      "staged": "d77679decb18a011c06bfde1c4fc170ce6059eb696b5ad7fab8c76823155fc10",
      "stored": "d77679decb18a011c06bfde1c4fc170ce6059eb696b5ad7fab8c76823155fc10" },
    … ] }

$ patchy dev agent importAttachments '{"folder":"INBOX","since":"2026-10-01"}'   # again
{ "result": { "imported": 0, "done": true, "stopped": null }, "version": 1 }

The second run starts from the stored checkpoint and finds nothing new.

Published, as a member

The published patch, opened by Priya Raman, a member, after Save attachments. A row shows its sha256 only when the stored bytes match the staged digest:

The published invoice inbox after saving attachments: three files with sizes and matching digests

Recent calls record the size, nothing else

Each stage appears with its duration and size ("54 B"), from the published patch as Priya and from patchy dev. No filename and no Upload is kept; the sentinel test checks recent calls, logs and wide events for both.

The connection's recent calls in #1266's full-width layout: stageAttachment rows from the published patch and from patchy dev, each with its size beside its duration

Nothing on the server changed

Flags read from the scenario's mail server after every download, dev and published:

UID Subject Flags
1 Factura nº 2026-0412 — papel reciclado none
2 Invoice INV-88213: October freight \Recent
3 Reminder: INV-87760 is overdue \Recent
4 Rechnung 7731 für Werkzeuge \Seen \Recent

Messages 1 and 2 had their attachments downloaded and are still unread; message 4 was read before any of this.

How it was verified

  • Files contract, on Postgres and PGlite. Host staging shares the page's quota count, refuses a tier 1 version or a call with no viewer, holds the staged-file bound, adopts once, and an Upload not adopted within the hour fails not_found.
  • Offline, over a scripted mail server. These run there:
    • every byte value under base64, quoted-printable and 8bit, with and without BINARY, in chunks;
    • exactly the bound staged, and one byte past refused with the session destroyed;
    • a container, a missing part, a gone message and another connection's ref, each refused with nothing staged;
    • an abandoned download destroying the session;
    • the attachment places answering busy;
    • a quota refusal handed on, keeping the session.
  • Live, on Dovecot and GreenMail (pnpm test:imap, 20 tests): a PDF in base64, a CSV in quoted-printable, a text file in 8bit and a PNG inside a forwarded message, compared by sha256. On Dovecot also: exactly 20 MiB staged and one byte more refused, and 20 MiB staged through a relay adding 100 ms of round trip in about 4 seconds.
  • The reference importer, live. The live tier takes it from the skill and runs it in real workerd over real tables and files against Dovecot, through each way a run can stop: a stage refused on quota, a message expunged as its page is read, an attachment past the bound kept by name and size, a row write that fails after its file was adopted, and a restart that imports only what arrived since.
  • The dev transport. A stub instance checks that a whole transfer stages, a short or differing one stages nothing, one past the bound is refused, and an instance refusal is handed on. The real door, over a scripted mailbox, streams a part that the daemon stages, and records its size. A client that stops reading a 19 MiB body keeps the process's place until it reads.
  • The sentinel now covers filenames and Upload tokens, through the generated client.
  • flock … pnpm verify. Format, lint, typecheck, synth, browser, cli-smoke, install, tier2-smoke and postgres-concurrency pass. The test lanes failed locally only on suites this PR doesn't touch, for CI to settle:
    • the CLI stub-server suites, where the editor's port probes on this machine reach the stub;
    • the Supervisor and LocalTaskProvider flakes;
    • RequestEvents.test.ts, which saw one extra event line in both full local runs and passes alone 5/5. It runs nothing this PR changes, and looks like the same stray probe request.
  • Not checked: a real company mailbox. Only Dovecot, GreenMail and the dev scenario's server.

Review

Grok 4.7 reviewed feat/imap-attachments at 2173289:

Finding What happened
P1: the dev door drops the attachment place while 20 MiB is still held. The place covered only the download, and the whole buffer then sat in the response until a slow patchy dev client read it, letting further downloads start past the limit. Fixed in e8f5396. The door takes the place into the request's own scope, which the server closes only once the response is written or the client goes, and streams the body 64 KiB at a time as the socket drains. A new placeIn takes the place and registers its release in one step. A test holds a client that stops reading a 19 MiB body: the process's one place stays taken until the body is read, then comes back. With the old code it fails. The published path already held its place through staging.
P2: the skill's description doesn't mention attachments, so agents choosing skills by description miss them. Fixed in 4e17ec3: it now names saving attachments into the patch's own files.

After acceptance (7a64558, f51a365, ea713e1, 58258c0):

  • stagedBytes now sums a request's successful stages instead of keeping the last download's size.
  • The dev daemon checks its local staging quota before asking the door, so a full quota downloads nothing.
  • 58258c0: host staging takes the call's binding as an argument, fixing the runtime build's Effect check.

After the acceptance re-check (11b2770, c81c1a9):

  • Each part carries attachment, decided once in the structure reader. It replaces the body flag an earlier fix added. A part is an attachment when it is attached by disposition, or when it is named and isn't a resource the body embeds (inside multipart/related with a Content-ID, such as a signature logo). The body, its HTML twin, the part it's encrypted in and a forwarded message's container never count; a forwarded message's own files do. hasAttachments is now true exactly when a part is one, so it changes feat(integrations): patches read IMAP folders and messages #1262's reader: a forward with no files, or an HTML body with only an embedded logo, says false.
  • The reference importer, in the skill and the scenario, saves exactly the parts marked attachment. Structure tests cover each edge of the rule, and the live tier now also imports a forward (only its PDF saved, not its text or HTML) and an HTML body with an embedded logo (only its PDF saved). The scenario's mail is plain attached PDFs, so the evidence above is unchanged.
  • A published stage checks staging's quota before it takes a place or logs in. A test holds a full quota to no session and no FETCH, and fails without the check. A quota that others fill during the download is still handed on.

After the second re-check (05b56e4, c2186ea):

  • A signed message's signature never counts. That is the second part of a multipart/signed, an application/pkcs7-signature, application/x-pkcs7-signature or application/pgp-signature, a forwarded message's too. Mail programs show it as a badge, so a signed invoice says hasAttachments only for what it carries, and the importer no longer saves a smime.p7s or .asc.
  • A part of any type other than text counts even with no filename and no disposition, unless it's a resource the body embeds. A nameless text part that isn't the body still doesn't count, so a forward's own text and HTML stay out. A PDF a scanner sends with no name is saved, its filename null; storage names already come from the ref and part.
  • Structure tests add an S/MIME-signed message with a PDF, PGP-signed ones, a forwarded signed message and a nameless PDF in multipart/mixed and alone, each checking that hasAttachments agrees. Each fails with its half of the rule taken out. The live importer adds a signed message (only its PDF saved, not smime.p7s) and a nameless PDF (saved, filename null).
  • c2186ea: a message/* part other than a forwarded message's container counts only when attached by disposition, so a bounce's delivery status and a read receipt's notification never become files; a bounced message's own PDF still counts. Structure tests cover a bounce, an internationalized bounce and a read receipt, and fail without the change.
  • Release impact: this PR and feat(integrations): patches read IMAP folders and messages #1262 ship in one release, and this PR is one-way; see below. feat(integrations): patches read IMAP folders and messages #1262's body says so too.

After the stack acceptance (a53242c):

  • The reference importer passed a whole scan page, up to 100 messages, to getMessages, which takes 25, so any window past 25 messages was refused invalid_request on its first page and never imported. It now reads each page 25 refs at a time, in the skill and the scenario alike, and the skill says why beside it. The live importer test adds a folder of 130 messages, past one scan page and past 25 refs, with a PDF on every tenth. A row write on the second page fails once, the next run imports only that page, and every message is kept once with no gaps. With the old importer that test fails. On a fresh pnpm dev up imap, the published invoice inbox saved all six files from 34 INBOX messages as Priya, reading 25 then 9.

After the scale acceptance (ff525ff):

  • A batch of 25 refs is bounded in refs, not bytes, so long plain-text mail could pass getMessages' 8 MiB answer bound, and the importer then failed on that batch on every run. It now reads a refused batch again in halves. One ref always fits, since a message's answer is at most 1 MiB, so the common case stays one call per 25 refs. The live importer test adds 25 quote-heavy exports sized from runtime.result.bytes (they come to 9,185,458 bytes): the batch is refused once and read in halves, and all 30 UIDs are kept once. Against the previous importer the same test is refused on that batch run after run, keeping nothing.

Decisions worth a look

  • imap.attachments.concurrent (4 per process). Without it, 32 calls at once could each buffer 20 MiB, about 640 MiB. It covers download through staging (or, in dev, until the body is sent); past it a call answers busy.
  • A part past the bound destroys its session, since a chunk may still be in flight. That costs one login.
  • The skill's isPatchyError line was wrong for server code. Server bundles refuse patchy/client, so an action reads a refusal's code; the page narrows with isPatchyError.
  • The live importer test writes its manifest by hand, mirroring the scenario's config: executeConfig can't resolve patchy/config in the scenario folder, which has no installed packages.
  • GreenMail quirks. It drops a text part's last line break from its section, and it answers NO with a ClassCastException of its own for parts inside a forwarded message. The live test stages nested parts on Dovecot, and on GreenMail holds Patchy to relaying the refusal.

Release impact

Tick exactly one.

  • Breaking — requires action from anyone already running this
  • Not breaking — no action required

Upgrading needs no action: one runtime operation, a dev door route, two registry limits, a wide-event field and a nullable column, all additive. The break is the way back, so this PR is one-way.

Ships in the same release as #1262, with no deploy between them. #1262's parts have no attachment flag, so a release with #1262 alone serves importers written against this PR parts they skip.

  • What does a revert leave behind?
    • Migration 0035 adds a nullable bytes column to runtime_calls, with two checks that hold for rows that never set it. Older code names its columns, never writes bytes and never reads it, so its rows pass the checks.
    • Staged uploads and adopted files are the page's own shapes.
    • Rolled back past both PRs, to the release before the stack, a published patch that calls the reads or stageAttachment keeps serving, but each call fails access_denied at the callback gateway. The reference importer fails before its checkpoint, and rolling forward again resumes it without a republish.
    • Republishing such a repo means patchy refresh onto the older release, whose client has no stageAttachment, so its typecheck fails until the call comes out.
  • Does the release before it still work with that? Not if it has feat(integrations): patches read IMAP folders and messages #1262 without this PR. Rolling back past feat(integrations): patches save IMAP attachments into their files #1264 to a release that has feat(integrations): patches read IMAP folders and messages #1262 alone would break importers written against this PR, the skill's reference importer among them, because that release's parts have no attachment flag: if (!part.attachment) continue skips every part, each message's row is saved without its files and the checkpoint moves past them, so rolling forward never imports them and nothing says so; fix forward instead.
  • Migration id. 0035 collides with the open PRs feat(auth): people accept updated terms on their next page #1204 and feat(feedback): Patchy stores requests and feedback #1217, which both still need renumbering past main's 0034. Whichever lands later renumbers.

Built by Claude Opus 5.5 in Claude Code, reviewed by Grok 4.7.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area area:primitives Patch tables and files area:integrations Company connections and integration implementations size:xl Over 1,000 changed lines; review in multiple passes labels Nov 6, 2026
@allisonmahmood allisonmahmood added the one-way Rolling production back past this PR would break the release before it label Nov 6, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Acceptance: PASS with notes

Checked ff525ff48c58cdaa62e81e8b084d2c70c5876b3d (base feat/imap-reads at d05caa3bd4a73f020fea6063945f9e6e7465672b, the stack on main at cbbd767) on imap, by Claude Opus 5.5 in Claude Code.

This extends the PASS with notes at a53242c (folded below) to its one new commit, ff525ff. That verdict's note 1: a batch of 25 refs is bounded in refs, not bytes. So 25 long, quote-heavy text messages answered past getMessages' 8 MiB result bound, and the importer failed on that batch on every run.

The fix holds. On the same kind of mail:

  • the old importer sticks on that batch and stores nothing;
  • the new one reads each refused batch again in halves and imports every message once, byte for byte, in patchy dev and published as Priya through Patchy MCP.

The earlier verdict's note 2 is still open, so this stays PASS with notes.

What ff525ff changes. Three files:

  • The importer wraps each batch of 25 in inHalves. On a whole-answer too_large for more than one ref, it reads each half the same way, recursively. The skill and the scenario's server/importer.ts still hold the same text.
  • The skill says so in one line beside the importer.
  • The live importer test adds 25 long exports and 5 notes, sized from the result bound. It asserts one refusal, of 25 refs, and all 30 messages kept once.

Nothing in the runtime, the wire, migrations or infrastructure changes.

Setup

  • pnpm dev up imap at ff525ff, with the mail server's per-command log turned on.

  • The Acceptance folder: 162 messages. 2 are before the window, one of them with a PDF. 160 are dated 2026-10-01 to 2026-10-07, which makes two scan pages, of 100 and 60:

    UIDs What Escaped text of the batch
    3–27 notes; PDFs at 3, 14 and 27 small
    28–52 note 1's mail: 25 nightly CSV exports sent as text, with rows like "1","2026-10-01","INV-100001","Supplier 2","EUR","7.31","paid","","","","" 100.5% of 8 MiB
    53–77 mixed: 20 exports with every field quoted and empty; invoices with a PDF at 55, 60, 70 and 75; a PDF and a CSV at 65 105%
    78–102 notes; PDFs at 78, 90 and 102 small
    103–127 25 exports with a lighter row, just under the bound 98%
    128–152 25 exports with every field quoted and empty 132%
    153–162 notes; PDFs at 153 and 162, and a 1 MiB PDF at 158 small

    Each export is about 400 KB, so its text is cut at 256 KiB.

  • Two builder repos, as Allison. I made each with patchy init --tier 2 and patchy add imap/invoices --as mail.

    • The new repo takes patchy.config.ts and server/importer.ts unchanged from its generated patchy-imap skill. That skill is byte-identical to the source skill, and its importer to the scenario's.
    • The old repo takes a53242c's importer.
    • Both typecheck as copied.
    • Each has an acceptance-only read, not pushed. It lists every row, and every stored file with the sha256 of its stored bytes. Later I added a tool to the new repo that stages without adopting.

Done means

  • The reference importer brings a date window of a folder into tables and files, now with long text mail: passed.
    • The old importer (a53242c), in patchy dev.

      • Two runs both failed on the second batch: "The 25 messages asked for come to 8448976 bytes, past the 8388608-byte result bound. Ask for fewer refs at a time."
      • The store held no rows and no checkpoint.
    • The new importer (ff525ff), in patchy dev as Allison. It imported 160 in 13.0 s. A second run imported 0.

    • Published, as Priya (member) through Patchy MCP (change_patch). It imported 160 in 8.7 s. A run with a new key imported 0.

    • The count, the same in dev and published:

      • 160 message rows, one for each of UIDs 3–162. None is duplicated, none missing, and none from before the window.
      • 15 attachment rows, each with its file, and 15 store files, each with its row.
      • Each file's staged sha256, stored sha256 and size equal the source's. The files run from 19 B to 1,048,592 B.
      • Priya's import reports stagedBytes: 1098708 in its wide event, the 15 sizes summed.
    • Halved only when refused. The mail server's log is the same for the dev and published runs, and recent calls agree:

      Batches in the mail server's log, and rows per call in recent calls
      page 1  UID FETCH 3:102              summaries
              UID FETCH 3:27               answered
              UID FETCH 28:52              refused
              UID FETCH 28:40, then 41:52  the halves
              UID FETCH 53:77              refused
              UID FETCH 53:65, then 66:77  the halves
              UID FETCH 78:102             answered
      page 2  UID FETCH 103:162            summaries
              UID FETCH 103:127            answered at 98%, not halved
              UID FETCH 128:152            refused
              UID FETCH 128:140, 141:152   the halves
              UID FETCH 153:162            answered
      
      importer          op                rows per call, in order
      old, dev, 2 runs  imap.getMessages  25, too_large (and the run fails)
      new, dev          imap.scanMessages 100, 60 | rerun 0
      new, dev          imap.getMessages  25, too_large, 13, 12, too_large, 13, 12, 25 | 25, too_large, 13, 12, 10
      new, published    the same, as Priya through her agent
      

Recent calls on the connection as Allison, Priya's second page: scanMessages 60 rows, getMessages 25 rows, getMessages FAILED too_large, then 13 rows, 12 rows and 10 rows, three stageAttachment rows with sizes only, and the closing 0-row scan

inHalves itself: passed.

  • It ends. A refused batch of n ≥ 2 refs splits into ceil(n/2) refs and the rest. Both halves are non-empty and smaller, and one ref rethrows.
  • It keeps every ref once, in order. The answers of slice(0, half) and slice(half) are joined in that order.
  • It rethrows anything else. Any other code, or an error without one, is rethrown at once.
  • Per-message errors pass through. A message's { error } is part of an answer, not a throw, so it reaches the importer's "error" in message check.
  • Run, not just read. I lifted inHalves out of the generated skill and gave it a fake read that refuses past a byte bound:
    • 20,000 random batches of 1–25 refs, with bounds that force full depth (up to 49 reads for one batch). Each came back in order, every ref once, with { error } answers in place.
    • A lone ref past the bound is rethrown, not dropped.
    • mailbox_reset, invalid_request, a plain Error, a string and null are each rethrown after one read.
    • An error in the second half surfaces with nothing partial returned.
  • Live, it halves at most once. Cleaned text is cut at 256 KiB and escaping at most doubles it, so 13 refs stay under 8 MiB. The comment's "at most 1 MiB" holds with room to spare.
  • The skill and the scenario stay the same text. Importer.test.ts, the test that holds them equal, passes locally and in CI.

Spot checks of the earlier verdicts

  • Read-only (doveadm): passed.
    • Every folder's status, and every message's flags and modseq in INBOX and Acceptance, are identical from before the first read to after everything here.
    • Acceptance stays at HIGHESTMODSEQ 163, all 162 unseen.
    • Patchy's sessions sent only ID, NAMESPACE, ENABLE, LIST, EXAMINE, FETCH, UID SEARCH, UID FETCH and LOGOUT. Each ended deleted=0 expunged=0.
  • No filename or Upload token in recent calls: passed.
    • I staged 3 parts in dev and 3 as Priya without adopting them, which left 6 live Upload tokens.
    • I searched runtime_calls (277 rows), runtime_invocations, the rollups, the server's log and both dev daemons' logs.
    • None of the tokens appear, and neither do 10 other strings: filenames, a subject, CSV values, a Message-ID and an address part.
  • CI on ff525ff: green. 26 checks pass, including imap-live (the importer case, now with the long exports), rollback-rehearsal, tier2-smoke and browser. attio-live is skipped.

Golden journeys

  • Use a tier 2 tool / Use a tool live: passed by CI (tier2-smoke, browser). I didn't run them on brightline. No other journey is touched.

Rollback answers: they match the diff.

Not run

  • An interrupted import on long text mail. inHalves touches no row or checkpoint. a53242c's verdict checked resuming after a daemon kill and a mail-server stall.
  • A second round of halving, live. The bounds can't produce one, as above; the fake-read check covers it.
  • A remote mail server. Everything here ran on loopback (note 1).
  • Cross-patch adoption, live, and a real company mailbox: as in the earlier verdicts.
  • pnpm test:imap locally: CI's imap-live passes on the head.

Notes

  1. A refused batch is fetched twice.
    • Why. The host reads the whole batch from the mail server before it measures the answer, so the refused read is thrown away and the halves read it all again.
    • Here. On loopback that added well under a second per refused batch, and 160 messages took 9–13 s.
    • The worst case. A page of 100 long exports reads about twice its bytes, around 80 MB, inside the action's 60 s. Only a slow link to a remote mail server would make that matter. The other fix the last verdict offered, 7 refs at a time, never refuses but always makes more round trips.
    • Why it doesn't fail the verdict. It's a trade-off, not a defect, and wide events will show it.
  2. Still open from the earlier verdicts, and untouched by ff525ff.
    • The skill's last bullet on recent calls still says they keep "how many folders or messages it answered", and never mentions a stage's size.
    • A refusal for more than 25 refs still names neither the argument nor the bound.

Carried forward from the earlier verdicts (folded below), not re-run here:

  • The importer reads 25 refs at a time across three scan pages, and resumes after a dev-daemon kill and a mail-server stall with every UID once (a53242c).
  • Host staging trusts only the call's binding: another company, viewer, patch or version is refused. Checked on Postgres and PGlite.
  • Byte fidelity across base64, quoted-printable (all 256 byte values), 8bit, 7bit, a nested PNG, exactly 20 MiB, a 15 MiB PDF and an 18 MiB base64 part. 20 MiB and one byte is kept by name and size.
  • The wire refuses HEADER, .MIME, TEXT, 0 and 1.0, a container part, another connection's ref and a stale UIDVALIDITY.
  • The attachment rule's 23 edge cases. An opaque-signed smime.p7m saves, since it holds the whole message.
  • A full published quota is refused before any IMAP command.
  • stagedBytes sums a request's stages, and the dev daemon checks its quota before downloading.
Earlier verdict at a53242c: PASS with notes

Checked a53242c946bef6b90b018df90fe7ff0e30dd10ff (base feat/imap-reads at d05caa3bd4a73f020fea6063945f9e6e7465672b, the stack on main at cbbd767) on imap, by Claude Opus 5.5 in Claude Code.

This re-checks the FAIL at 0ac096f (folded below) at its one new commit, a53242c. That FAIL was the reference importer passing a whole scan page, up to 100 refs, to getMessages, which takes 25. The fix holds in the skill and in the scenario, in patchy dev and published, across three scan pages and through two interruptions. One note is worth fixing before merge: a batch of 25 is bounded in refs but not in bytes, so a folder of long text mail can still stall the importer (note 1).

What a53242c changes. Four files:

  • The importer reads each page 25 refs at a time. The code is the same in the patchy-imap skill and in the scenario's server/importer.ts.
  • The skill says so once, beside the importer.
  • The live importer test adds a 130-message folder, with a failure part way and a resume.
  • One test is renamed.

Nothing in the runtime, the wire, migrations or infrastructure changes.

Setup

  • pnpm dev up imap at a53242c. I turned on the mail server's per-command log in this environment's container.
  • The Acceptance folder: 263 messages. 3 are before the window, one of them with a PDF. 260 are dated 2026-10-01 to 2026-10-31.
    • 22 plain PDFs sit on both sides of every scan-page and 25-ref boundary: UIDs 4, 28/29, 53/54 … 253/254 and 263.
    • The other cases:
      • a forward with its own text, HTML and PDF;
      • an HTML body with a cid: logo, and a PDF;
      • an S/MIME-signed PDF;
      • a PGP/MIME-signed CSV in quoted-printable;
      • a PDF with no name;
      • two files in one message;
      • UTF-8 text in 8bit with an RFC 2231 name;
      • a 15 MiB PDF (UID 150);
      • a file one byte past 20 MiB (UID 151).
    • Every 7th message is read, and every 31st flagged.
  • The builder's repo, as Allison.
    • I ran patchy init --tier 2, then patchy add imap/invoices --as mail.
    • I copied patchy.config.ts and server/importer.ts unchanged from the repo's generated skill. That skill is the same text as the source skill, and its importer the same as the scenario's. It typechecks as copied.
    • Beside it I added acceptance-only tools, not pushed. One lists every row, and every stored file with the sha256 of its stored bytes. Later I added a size probe and a stage-without-adopting tool.

Done means

  • The reference importer brings a date window of a folder into tables and files, and resumes after a restart: passed.

    • In patchy dev, as Allison.

      • I killed the dev daemon (kill -9) on the second page, while it downloaded UID 150's 15 MiB. The CLI said the outcome was unknown (exit 3).
      • The store then held page 1's 100 rows, UIDs 104–149, and page 1's checkpoint.
      • After patchy dev started again, the next run imported 160, starting from UID 104. A third run imported 0.
    • Published, as Priya (member) through Patchy MCP.

      • I paused the mail server's container for 25 s while UID 150 downloaded. Her agent was told the outcome is unknown and to read what changed before trying again with a new change key.
      • The store held the same 146 rows and one checkpoint.
      • A run with a new key imported 160, starting from UID 104. The next run imported 0.
    • The count, the same in dev and published:

      • 260 message rows, one for each of UIDs 4–263. None is duplicated, none missing, and none from before the window.
      • 32 attachment rows. 31 have their file. UID 151's row keeps its filename and wire size, without a file.
      • Each stored file's sha256 and size equal the source's, as staged and as stored.
      • Not saved: the forward's container, text and HTML; the cid: logo; smime.p7s and OpenPGP_signature.asc; any body; and the PDF from before the window.
      The 31 stored files
      UID Part What Bytes Stored = source, dev and published
      4, 28, 29, 53, 54, 78, 79, 103, 104, 128, 129, 153, 154, 178, 179, 203, 204, 228, 229, 253, 254, 263 2 a plain PDF on each side of a boundary 2,080–5,449 yes, all 22
      60 2.2 the PDF inside a forwarded message 12,029 yes
      61 2 a PDF beside a cid: logo 5,029 yes
      62 1.2 the PDF in an S/MIME-signed message 8,029 yes
      63 1.2 a UTF-8 CSV, quoted-printable, in a PGP/MIME-signed message 70 yes
      64 2 a PDF with no name or disposition (filename null) 7,029 yes
      65 2 and 3 a PDF and a PNG in one message 3,029 and 2,509 yes
      66 2 UTF-8 text in 8bit, with an RFC 2231 name 48 yes
      150 2 a 15 MiB PDF 15,728,670 yes
    • 25 refs at a time. The mail server's log shows each scan page and then its batches:

      • page 1: UID FETCH 4:103, then 4:28, 29:53, 54:78 and 79:103;
      • page 2: 104:203, then 104:128 … 179:203;
      • page 3: 204:263, then 204:228, 229:253 and 254:263.

      The resumes start from the checkpoint, with UID SEARCH UID 104:263. Recent calls agree. No getMessages call holds more than 25 refs, and none is refused:

      Rows per call, from recent calls
      patch                caller   op                 calls  rows, in order
      acceptance-importer  agent    imap.scanMessages  5      100,100,100,60,0
      acceptance-importer  agent    imap.getMessages   15     25 ×14, 10
      (patchy dev)         machine  imap.scanMessages  5      100,100,100,60,0
      (patchy dev)         machine  imap.getMessages   15     25 ×14, 10
      invoice-inbox        session  imap.scanMessages  1      44
      invoice-inbox        session  imap.getMessages   2      25,19
      

      Each interrupted run's last page is counted again in its resume.

  • The scenario's own invoice-inbox, with 44 messages in INBOX: passed.

    • I added 40 messages to INBOX, dated from 2026-10-26. PDFs sit at UIDs 10, 25, 26 and 44, on both sides of the first batch's edge.
    • As Priya in a browser, Save attachments answered in 1.4 s: 7 attachments saved, the scenario's 3 and my 4. Each one's staged and stored sha256 equal its source's.
    • The connection's recent calls show scanMessages with 44 rows, then getMessages with 25 rows and 19 rows.

The scenario's invoice inbox as Priya after Save attachments with 44 messages in INBOX: 7 attachments saved, each with its size and digest

The connection's recent calls as Allison: scanMessages 44 rows, getMessages 25 rows then 19 rows, and seven stageAttachment rows with sizes only

Diff review: passed for refs.

  • These are all the getMessages calls in the skill, the scenario, docs and examples:
    • the importer's, now batched;
    • the skill's first reading example and the scenario's desk.ts, one ref each.
  • docs/product.md, the generated client's notes and the limits tables state the bound, and pass no refs.
  • The comment and the skill's new line say the same thing. The two importers are still the same text; the test that holds them so passes in CI.
  • const read = [] relies on TypeScript's evolving array type. Under the repo template's strict setting the copy typechecks (I ran pnpm typecheck).
  • In bytes it isn't bounded: see note 1.

Spot checks of the earlier verdicts

  • Read-only (doveadm): passed.
    • I snapshotted every message's flags and modseq after seeding, and INBOX's again before the scenario's save. After everything here, both are unchanged, \Recent included.
    • Acceptance stays at HIGHESTMODSEQ 264. INBOX moved by exactly my 40 appends.
    • Patchy's 10 sessions sent only ID, NAMESPACE, ENABLE, LIST, EXAMINE, FETCH, UID SEARCH, UID FETCH and LOGOUT. Each ended deleted=0 expunged=0.
  • No filename or Upload token in recent calls: passed.
    • Priya staged 5 parts without adopting them, which left 5 live Upload tokens.
    • I searched runtime_calls (84 stageAttachment rows), runtime_invocations, the rollups, the server's log and both dev daemons' logs. None of the tokens appear, and neither do 18 filenames, invoice numbers and subject words.
  • Wide events: passed. Priya's resumed import reports stagedBytes: 15791657, exactly the files on pages 2–3. The INBOX save reports 12,377, its seven files summed.
  • CI on a53242c: green. 26 checks pass, including imap-live (with the new 130-message case), rollback-rehearsal, tier2-smoke and browser. attio-live is skipped.

Golden journeys

  • Use a tier 2 tool / Use a tool live: passed by CI (tier2-smoke, browser). I didn't run them on brightline. No other journey is touched.

Rollback answers: they match the diff.

Not run

  • A published run stopped by a failed row write. I stopped the published run with a mail-server stall, and the dev run by killing the daemon. The new live test covers a failed row write.
  • Cross-patch adoption, live, and a real company mailbox: as in the earlier verdicts.
  • pnpm test:imap locally: CI's imap-live passes on the head.

Notes

  1. A batch of 25 is bounded in refs, not in bytes, so the importer can still stall on long text mail.
    • Why. getMessages refuses an answer past 8 MiB (runtime.result.bytes), but each message may answer up to 1 MiB (runtime.row.bytes). So 25 refs can come to far more than 8 MiB.

    • What happens. The importer doesn't catch the refusal, so the run fails before the page's checkpoint. Every later run fails on the same batch. That is the failure the last FAIL saw, but now it needs mail of a rare shape.

    • What I tried. Nightly CSV exports mailed as plain text, 30 per folder, each about 400 KB, so each message's text is cut at 256 KiB. The JSON escapes for quotes and line breaks make each text's answer about 320–330 KB:

      Each CSV row The answer for 25 Share of 8 MiB The importer
      "1","2026-10-01","INV-100001","Supplier 1","EUR","7.31","paid" 7,975,933 B 95% imported 30
      the same, plus ,"","" 8,211,233 B 98% imported 30
      the same, plus ,"","","","" 8,412,133 B 100.3% too_large on the first batch, every run
    • The refusal is clear: "The 25 messages asked for come to 8412133 bytes, past the 8388608-byte result bound. Ask for fewer refs at a time." The skill already tells builders to ask for fewer refs; its importer doesn't.

    • Either fix works:

      • on a batch's too_large, read it again in halves;
      • read 7 refs at a time, which can never pass 8 MiB, at the cost of more round trips.
    • Why it doesn't fail the verdict. It needs 25 messages in one batch, each near the text bound and heavily escaped. Agents copy this importer word for word, though, so it's worth fixing in this PR.

  2. Still open from the last verdict, and untouched by a53242c.
    • The skill's last bullet on recent calls still says they keep "how many folders or messages it answered", and never mentions a stage's size. Since 0ac096f the page also says a stage keeps its size, never its filename or upload token.
    • Its note 1, that a refusal for more than 25 refs names neither the argument nor the bound, still stands.

Carried forward from the earlier verdicts (folded below), not re-run here:

  • Host staging trusts only the call's binding: another company, viewer, patch or version is refused. Checked on Postgres and PGlite.
  • Byte fidelity across base64, quoted-printable (all 256 byte values), 8bit, 7bit, a nested PNG, exactly 20 MiB and an 18 MiB base64 part.
  • The wire refuses HEADER, .MIME, TEXT, 0 and 1.0, a container part, another connection's ref and a stale UIDVALIDITY.
  • The attachment rule's 23 edge cases. An opaque-signed smime.p7m saves, since it holds the whole message.
  • A full published quota is refused before any IMAP command.
  • stagedBytes sums a request's stages, and the dev daemon checks its quota before downloading.
Earlier verdict at 0ac096f: FAIL

Checked 0ac096f33f578dab5efcf86672a47f3519497ddf (base feat/imap-reads at d05caa3bd4a73f020fea6063945f9e6e7465672b, the stack on main at cbbd767) on imap, by Claude Opus 5.5 in Claude Code.

I checked the whole Email (IMAP) stack end to end at its top commit, after the rebase onto #1266's pages. This replaces the PASS with notes at 4e42279, which is folded in at the end.

What the rebase moved. git range-diff 60cf6c4..4e42279 d05caa3..0ac096f shows all 19 earlier commits as identical patches. The ConnectionsView.ts conflict resolved to the same size-in-Took change, at new line numbers. The one new commit, 0ac096f, changes IMAP's recent-calls intro and its test.

Why it fails: the reference importer can't import a date window with more than 25 messages. That breaks the Done means line "The reference importer brings a date window of a folder into tables and files, and resumes after a restart."

  • The cause. The importer hands a whole scan page to getMessages: mail.getMessages(page.messages.map((m) => m.ref)). A page holds up to 100 summaries, but getMessages takes at most 25 refs (imap.getMessages.refs). So the wire refuses the call with invalid_request, and nothing reaches the mail server.
  • It never gets past it. The refusal comes on the first page, before any row or checkpoint is written, so every later run fails the same way.
  • The rebase didn't cause it. It has been there since the importer landed (acb1a80 in the skill, 0ec41b9 in the scenario). The earlier runs used folders of 4 to 23 messages, and the live tier's importer folder holds 10.
  • I saw it twice:
    • The skill's importer. Copied from the generated patchy-imap skill into a fresh repo and run in patchy dev on a folder with 239 messages in the window, it answered Runtime request refused: invalid_request. The last command the mail server saw before the refusal was the first page's summary fetch, UID FETCH 4:103 (…).
    • The scenario's own invoice-inbox. Published, as Priya on the page: once 30 more messages arrived in its INBOX, Save attachments gave the same answer. Read INBOX on the same page still lists all 34. The connection's recent calls show getMessages FAILED invalid_request right after a 30-row scan:

The scenario's invoice inbox as Priya, after 30 more messages arrived: Read INBOX lists them, and Save attachments shows "Runtime request refused: invalid_request."

The scenario connection's recent calls: the importer's getMessages FAILED invalid_request after a 30-row scanMessages; below, the earlier stageAttachment rows show their sizes (54 B, 61 B)

  • The fix. Either way works:

    • read each page in slices of 25, as below (I ran this locally for everything else here);
    • let getMessages take a whole page of 100 refs.

    The test that holds the skill and the scenario word for word means both need the same change. A live-tier case with more than 25 messages in the window would keep it fixed.

    const read = [];
    for (let i = 0; i < page.messages.length; i += 25)
      read.push(...(await mail.getMessages(page.messages.slice(i, i + 25).map((m) => m.ref))));

Everything else passed. For these runs I applied that change in my own test repo only. The scenario's patch kept the shipped text.

Setup

  • pnpm dev up imap at 0ac096f.
  • As Allison (admin), I connected a second mailbox, imap/acceptance, through the new connect form in a browser.
  • As the builder, I ran patchy init --tier 2 and patchy add imap/acceptance --as mail. I took patchy.config.ts and server/importer.ts from the generated skill, and added acceptance-only tools (part flags, stage without adopting, the store listed with each file's sha256). None of this was pushed.
  • I put 242 messages in a new Acceptance folder: 3 before the window (one with a PDF), 230 plain notes through October, and 9 attachment cases. Later I added 4 more.

Done means

  • A tier 2 action saves attachments byte for byte, in patchy dev and published, and records one over 20 MiB by name and size: passed.
    • I ran the importer in patchy dev as Allison, and published as Priya (member) through Patchy MCP. Both stored the same 11 files.

    • For each file, the sha256 Patchy staged and the sha256 of the bytes read back from the store both equal the source's:

      UID Part File Bytes Stored = source
      234 2 a PDF, base64 307,216 yes
      235 2.2 the PDF inside a forwarded message 12,016 yes
      236 2 a PDF beside a cid: logo 5,016 yes
      237 1.2 the PDF in an S/MIME-signed message 8,016 yes
      238 1.2 a UTF-8 CSV, quoted-printable, in a PGP/MIME-signed message 91 yes
      239 2 a PDF with no name or disposition (filename null) 7,016 yes
      240 2 exactly 20 MiB, binary 20,971,520 yes
      242 2 UTF-8 text in 8bit, with an RFC 2231 name, Lieferschein-für-März.txt 42 yes
      243 2 15 MiB PDF, arrived after the first import 15,728,656 yes
      244 2 PDF, arrived after the first import 4,337 yes
      246 2 PDF, arrived later still 65,016 yes
    • Over 20 MiB. UID 241, one byte past 20 MiB, answered too_large after its 21st chunk. The importer kept it as a row with its filename and wire size (28,697,872) and no file.

    • Not saved: the cid: logo, smime.p7s, OpenPGP_signature.asc, the forward's container, text and HTML, and the PDF from before the window. Every store file has its row.

  • The reference importer imports a date window and resumes after a restart: failed, as above. With the local change, everything else here passed:
    • since: "2026-10-01" imported UIDs 4–242 in three pages (100, 100, 39) and skipped UIDs 1–3. It took about 20 s, in dev or published.
    • After a patchy dev stop and start, a second run imported 0.
    • Then three new messages arrived. I killed the dev daemon partway through the 15 MiB download, and the CLI said the outcome was unknown. After patchy dev started again, the next run imported exactly those 3 (UIDs 243–245), byte for byte, with no duplicates or gaps.
    • Published, Priya's runs imported 242, then 1 after one more message arrived, then 0. That left 243 rows, UIDs 4–246.

The attachment rule: passed. Part flags from scanMessages and getMessages, the same in dev and published:

Every part of the nine cases
uid message                          has s/m    part    type                         disp       cid filename                     attachment
234 invoice with a PDF               true/true  1       text/plain                                                               false
                                                2       application/pdf              attachment     ACC-1001.pdf                 true
235 forward: text, HTML and a PDF    true/true  1       text/plain                                                               false
                                                2       message/rfc822               attachment     Invoice 5521.eml             false
                                                2.1.1   text/plain                                                               false
                                                2.1.2   text/html                                                                false
                                                2.2     application/pdf              attachment     fwd-5521.pdf                 true
236 HTML with a cid: logo, and a PDF true/true  1.1     text/plain                                                               false
                                                1.2.1   text/html                                                                false
                                                1.2.2   image/png                    inline     cid logo.png                     false
                                                2       application/pdf              attachment     statement-ink.pdf            true
237 S/MIME-signed, with a PDF        true/true  1.1     text/plain                                                               false
                                                1.2     application/pdf              attachment     signed-invoice.pdf           true
                                                2       application/pkcs7-signature  attachment     smime.p7s                    false
238 PGP/MIME-signed, with a CSV      true/true  1.1     text/plain                                                               false
                                                1.2     text/csv                     attachment     remittance.csv               true
                                                2       application/pgp-signature    attachment     OpenPGP_signature.asc        false
239 nameless PDF, no disposition     true/true  1       text/plain                                                               false
                                                2       application/pdf                                                          true
240 exactly 20 MiB                   true/true  2       application/octet-stream     attachment     drawings-20MiB.bin           true
241 20 MiB and one byte              true/true  2       application/octet-stream     attachment     drawings-over.bin            true
242 8bit UTF-8 text                  true/true  2       text/plain                   attachment     Lieferschein-für-März.txt    true

Spot checks of the earlier verdicts

  • Read-only (doveadm): passed.
    • Flags and modseq. I snapshotted both mailboxes' folder status, and every message's flags and modseq, before any read. After everything here, every message that was there before is unchanged, \Recent included.
    • HIGHESTMODSEQ moved by exactly my own 34 appends.
    • Commands. The mail server's per-command log shows Patchy sending only EXAMINE, FETCH and UID FETCH, UID SEARCH, LIST, STATUS, NAMESPACE, ID, ENABLE and LOGOUT. Every session ended deleted=0 expunged=0.
  • The 20 MiB bound: passed, in dev and published, as above.
  • The published quota check: passed.
    • Priya staged a 42 B part 16 times without adopting it.
    • The 17th stage, and a 20 MiB stage right after it, answered limit_exceeded. Neither left a line in the mail server's log: no login and no command.
    • A read right after them logged as usual.
  • Recent calls: passed.
    • Layout. The merged table spans the page at 1280, 1440 and 1920 px, with no clipped cell.
    • Rows. Reads show rows, stages show sizes (45 ms · 54 B, 20.0 MB), and refusals show their code.
    • IMAP's intro says what's kept: "how much it read: rows, or an attachment's size. Subjects, bodies, addresses, search values, attachment filenames and upload tokens are never logged."
    • bytes is set on successful stages and null on refused ones.
    • No leaks. I searched both connection pages, runtime_calls, the server's log and the dev daemon's log. None of the 16 unadopted Upload tokens appear, and none of the filenames.
    • Wide events. Priya's published import reports stagedBytes: 37043926, the ten stored files' sizes summed.
  • The pause: passed. feat(integrations): patches read IMAP folders and messages #1262's verdict has the details. While the connection was paused, this PR's importer and stages answered auth_failed, published and in dev. After Replace password, a ref made before the password change staged again.

Golden journeys

  • Use a tier 2 tool / Use a tool live: passed by CI on the head (tier2-smoke, browser). I didn't run them on brightline.

Rollback answers: they match the diff.

Not run

  • A published import stopped by a restart: I killed only the dev daemon. For the published patch I checked resume across new mail.
  • Cross-patch adoption, live, and a real company mailbox: as in the earlier verdicts.
  • pnpm test:imap locally: CI's imap-live passes on the head.

Notes

  1. The refusal names nothing. All the builder sees is "Runtime request refused: invalid_request." feat(integrations): patches read IMAP folders and messages #1262's verdict noted this for any argument outside the wire. Here it hides a one-line cause; naming the argument and its bound (refs, at most 25) would have made it obvious.
  2. The skill lags the page's intro. Its last refusals bullet still says recent calls keep "how many folders or messages it answered", and that "subjects, bodies, addresses, search values and the password are never kept". Since 0ac096f the page also says a stage keeps its size, never its filename or upload token, and the skill could say the same.
  3. Not this PR's: at 1024 px the recent-calls table is 32 px wider than its scrolling container, so the Outcome badge's right edge is cut until you scroll. The table is 720 px wide with or without the sizes in Took, so the cause is feat(integrations): admins connect an IMAP mailbox with a password #1266's layout.

Carried forward from the earlier verdicts (folded below), and not re-run here:

  • Host staging trusts only the call's binding: another company, viewer, patch or version is refused, checked on Postgres and PGlite.
  • Byte fidelity across base64, quoted-printable (all 256 byte values), 8bit, 7bit, a nested PNG and an 18 MiB base64 part.
  • The wire refuses HEADER, .MIME, TEXT, 0 and 1.0, a container part, another connection's ref and a stale UIDVALIDITY.
  • The rule's 23 edge cases. Note there: an opaque-signed smime.p7m saves, since it holds the whole message.
  • stagedBytes sums a request's stages, and the dev daemon checks its quota before downloading.
Earlier verdicts at 4e42279 (PASS with notes), 3668972 (FAIL), d6d5458 (FAIL) and a2776e9 (PASS with notes), summarized to fit the comment limit
  • 4e42279: PASS with notes. It re-checked 3668972's FAIL at two commits that changed only the attachment rule, its tests and docs, and the Release impact answers. It established:
    • The Release impact answer holds: feat(integrations): patches read IMAP folders and messages #1262 and feat(integrations): patches save IMAP attachments into their files #1264 ship in one release and this PR is one-way, so a deployer acts correctly whether the two ship together or apart.
    • The rule on 23 messages, the 12 asked for and 11 beyond them: a signature never counts, a nameless PDF does, and a bounce's or read receipt's status part never does. hasAttachments from scanMessages and getMessages agrees with the part flags, and dev and published answered the same.
    • The importer saved the 12 flagged files byte for byte, in dev and published, and a second run imported 0.
    • Read-only by doveadm snapshots. Each stage row keeps its bytes, and no filename appears in recent calls or logs.
    • Its notes: an opaque-signed smime.p7m saves, since it holds the whole message; and feat(integrations): patches read IMAP folders and messages #1262's body says this PR "narrows hasAttachments", though a nameless PDF now widens it.
  • 3668972: FAIL, on the Release impact answer. A rollback to a release with feat(integrations): patches read IMAP folders and messages #1262 but not this PR would make the importer skip every part silently. 4e42279 fixed it. It established:
    • attachment and hasAttachments agree on 13 cases, dev and published; encrypted wrappers never count.
    • A full published quota (16 uploads, or 100 MiB) is refused limit_exceeded before any IMAP command, by the mail server's own log.
    • None of 21 Upload tokens, and no filename, in recent calls or logs.
  • d6d5458: FAIL, on the importer saving a forward's own text and HTML and a cid: logo. The attachment flag fixed it at 3668972. It established:
    • Host staging takes the call's binding. Another company, viewer, patch, version or a decoy binding is refused, by a scratch contract case on Postgres and PGlite, and an Upload adopts once.
    • stagedBytes sums a request's stages, and the dev daemon checks its quota before downloading.
  • a2776e9: PASS with notes. It established:
    • byte fidelity across base64, quoted-printable (all 256 byte values), 8bit, 7bit, a nested PNG, an RFC 2231 name, exactly 20 MiB and 18 MiB of base64;
    • 20 MiB + 1 refused too_large;
    • the wire's refusals: HEADER, .MIME, TEXT, 0 and 1.0, a missing part, another connection's ref and a stale UIDVALIDITY;
    • the staging quota;
    • a dev-daemon kill mid-import resuming with no duplicates.

allisonmahmood added a commit that referenced this pull request Nov 7, 2026
…1266)

## What changed

Plenty of companies keep their mail with a plain hosting provider: an
IMAP mailbox with a username and password, and no Google or Microsoft
API. Patchy had no way to connect one. Now an admin connects a mailbox
by its server, port, username and password. Patchy logs in once on a
fresh session to check it, keeps the mailbox's folders, and refuses a
mailbox that falls short by naming the requirement it misses. A builder
runs `patchy add imap/<handle>` and gets the declaration and a context
listing the folders.

Patches can't read mail through it yet. That's #1262 (reads) and #1264
(attachments), stacked on this branch; all three ship in one release.

Part of #1250. Closes #1251.

## Look at

**The pages: mock A, trimmed to match the other integrations**
(Allison's pick from the
[mocks](https://post.patchyhq.com/d/b7f3rv4gdtx0)). They are the shared
connect frame and the shared connection page that Postgres, PostHog and
Attio use, with IMAP filling in only its own words and fields. There's
no new layout and no new component.

The connect page is the shared walkthrough. It shows what a mailbox
needs, then the login, then how to use it. Port and security are one
choice, because the security follows the port. A short Company-wide
access note sits beside the fields:

![The IMAP connect page: what a mailbox needs, the login form with one
port choice, and using
it](https://github.com/user-attachments/assets/0243cb54-5fa0-4242-b4d2-8a07d81ccf4c)

A failed Test re-renders the form with the refusal under its field,
keeping everything typed except the password. A certificate that doesn't
name the host lists the names it does carry:

![The certificate refusal under Server, naming the certificate's
names](https://github.com/user-attachments/assets/4b9c322c-394c-465e-9c25-2f67ed29c4de)

The connected page shows the server and username, the folder count and
first folders, and recent calls:

![The connected imap/invoices
page](https://github.com/user-attachments/assets/a9a67af4-5a5f-40fd-b063-5e2df15d8a93)

**A refused password pauses the connection.** The page keeps a notice
with the two ways out, Replace password and Test again, and a Paused
tag. The connection counts under Needs attention on the index:

![A paused connection: the notice with Replace password and Test
again](https://github.com/user-attachments/assets/4bbda0eb-5547-43f4-a031-80058f2c8ea8)

![The index: 1 connection needs attention, imap/invoices is
paused](https://github.com/user-attachments/assets/6f38ab7d-b832-4486-865a-e36b5f2cb93a)

<details><summary>The way out: the shared Replace password page, then
the resumed connection</summary>

![Replace the password for
imap/invoices](https://github.com/user-attachments/assets/9d1f8fb4-c65b-4801-85c4-f2c83001a507)

![Password replaced and tested, the pause
gone](https://github.com/user-attachments/assets/802d1b65-ada6-4fcc-8c86-3ddd4dae10a8)

</details>

**Two fixes on the shared connection page, for every integration.**

- The recent-calls table clipped its Outcome column at desktop width:
six columns with a 720px minimum sat in the roughly 620px beside the
facts. Recent calls now span the page below the reads and the facts.
Before and after, on the same page at 1280px:

![Before: Outcome cut off at the right
edge](https://github.com/user-attachments/assets/84190eba-6bff-4592-9490-d03d500971ad)

- The intro above recent calls was Postgres's wording on every page.
Each integration now says what its calls keep and never keep. IMAP's:
"Each call keeps its operation, who made it, when, how long it took and
how much it read; subjects, bodies, addresses and search values are
never logged."

**The transport** (`imap/Source.ts`, `imap/Network.ts`):

- The host resolves, and every address must be public.
- The session dials only the checked address.
- TLS 1.2 or later is verified against the typed host, with SNI.
- Port 993 is TLS and 143 requires STARTTLS; any other port is refused.
- CAPABILITY must name IMAP4rev1 or IMAP4rev2 and allow a password login
before the password is sent.
- A `PREAUTH` greeting is refused, since the password would never be
checked.
- Referrals are never followed.

Test names each failure: the name doesn't resolve, a private address,
the port, TLS, an untrusted certificate, a certificate for another name,
no STARTTLS, not IMAP4, login disabled, no password asked, the
credentials refused, or no INBOX.

**The login pause** (`SqlConnectionStore.ts`):

- Only a `NO` to `LOGIN` or `AUTHENTICATE` pauses, coded
`AUTHENTICATIONFAILED`, `AUTHORIZATIONFAILED`, `EXPIRED` or uncoded.
ImapFlow's `authenticationFailed` is never read.
- The pause is recorded on the connection's row, so no host process logs
in with it until an admin's Test, Replace password or Reconnect works.
- A refusal that lands after a later login of the same password worked
and was saved pauses nothing.
- `patchy list connections` marks a paused mailbox, with the way out
instead of an add hint.

**Loopback mailboxes are a layer, never configuration.**
`apps/server/src/start.ts` launches with production's network. The dev
runner's own entrypoint, `scripts/dev/src/server.ts`, launches with the
loopback one for its local mailboxes.

## How it was verified

| Done means (#1251) | Shown by |
| --- | --- |
| An admin connects a mailbox on Dovecot or GreenMail by host, port,
security, username and password | `pnpm test:imap` connects, tests,
refreshes and deletes a mailbox on Dovecot over TLS and STARTTLS, and on
GreenMail (5 passed, about 18 s). `pnpm dev up imap` connects one
through the connect page above, in a browser |
| A mailbox that misses a requirement fails its Test, which names it |
Offline over a scripted IMAP server on loopback (`imap/Source.test.ts`,
Node and Bun): every refusal before login with nothing sent, DNS
rebinding, a certificate for another name with its names listed, an
untrusted CA, a TLS 1.1 server, 143 without STARTTLS, `PREAUTH`, no
IMAP4, login disabled, no INBOX, parser and byte bounds. Live: 143 on
GreenMail, a certificate for another name, and a wrong password on both
servers |
| A wrong password pauses the connection until it's replaced, without
further logins | `imap/Connections.test.ts`: a refused login pauses, and
a second process neither hands out the password nor logs in. Replace
password and Test unpause it. `NO [UNAVAILABLE]`, `NO [REFERRAL]`, `BAD`
and a throttle don't pause. A stale refusal after another admin's
successful Test doesn't pause (red without the fix, green with it) |
| `pnpm dev up imap` gives a connected local mailbox | Shown in the
screenshots, which are of that environment |

- `pnpm build`, `pnpm typecheck` (uncached) and `pnpm lint` passed.
`pnpm check` passed format, lint, typecheck and synth; its offline tests
passed except suites that fail only on this machine:
  - the CLI's stub-server tests, which fail from a stray `GET /` probe;
- the installer tests, which can't find npm beside this machine's
`node`;
  - one execution test under load.
Each passed rerun alone except the installer's, whose files this PR
doesn't touch.
- The connections API lists an IMAP row only to a caller that decodes
IMAP, so CLIs from before never see one. The release before IMAP's store
hides IMAP rows.
- The screenshots are `pnpm dev shot` and Playwright captures of this
worktree's `imap` environment, which holds scenario data only. `pnpm dev
compare` can't show them, because main has no IMAP pages and the pause
needs a refused login. Before and after for the calls table are the same
page before and after the fix commit. At phone width the table scrolls
inside its wrapper, as before.
- `pnpm verify` ran locally at `0084d76`: format, lint, typecheck,
synth, postgres-concurrency, tier2-smoke and browser passed. test, test
(bun), cli-smoke and install failed for this machine's reasons:
- the CLI suites hit the stray `GET /` probe, and a Supervisor test
timed out under load;
- test (bun) passed all 2,596 tests, and its 3 errors are that probe's
empty body;
- cli-smoke and install fail because this machine's `node` has no npm
beside it.

  CI passes all four on its runners.
- Not checked: a real public mail host, and a pause on a real server
(the test servers keep one password).
- Locally, `pnpm dev up` fails to install the environment's CLI because
the repo-pinned npm 12 refuses the instance's tarball (`EALLOWREMOTE`).
I ran the runner directly with Bun.

## Release impact

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required

This is a new integration with no migration. The connections API adds
`imap` rows only for callers that ask for them, and the new `paused`
fields are optional. `DeclarationMetadata.imap` defaults to empty for
older generations.

**One-way: production can't roll back past this release while any patch
version declares an IMAP connection.** The release before can't decode a
manifest that declares `kind: "imap"`, so it can't serve those versions.
The only recovery is rolling forward, as with Attio's #967.

- **What does a revert leave behind?** IMAP connection and snapshot rows
in the existing `connections` and `connection_snapshots` tables, each
password sealed under the keyring, and any patch version that declares
`imap`. Nothing in anyone's mailbox is changed.
- **Does the release before it still work with that?** No, for patches
whose version declares IMAP: they need this release to serve. Everything
else works: the release before reads only the integrations it ships
(#657), so IMAP rows stay hidden from its pages, CLI and lookups.
Rolling back past this PR would break any patch version that declares
`imap`, so fix forward instead.

## Review

Grok 4.7 reviewed the backend at `a4deaa8` and found no P1s. Its three
P2s are fixed in `08626e4`: a stale refusal could re-pause after a
success, the CLI hid a pause, and `PREAUTH` skipped the login. Grok then
reviewed the pages at `0084d76`: no P1s and no UI-consistency findings.
Its one P2 is fixed in `f9897e7`: a posted security that disagreed with
the port answered 422 with no visible error, because the form has no
security control. The refusal now sits under Port, and a page test
covers it (red without the fix).

Built by Claude Opus 5.5 in Claude Code, reviewed by Grok 4.7.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
allisonmahmood added a commit that referenced this pull request Nov 7, 2026
Stacked on #1266 (`feat/imap-connections`, #1251's connections and
pages). Review only this PR's diff.

Rebased onto #1266 at `f9897e7`; the commit ids below are the rebased
ones. It ships in the same release as #1264 (see Release impact).

## What changed

An admin can connect a company mailbox (#1251), but no patch could read
it. Now a tier 2 action reads it through `ctx.connections.<alias>`. It
can list folders, import a folder from a given day in resumable pages,
list newest first, search, and read messages with their text and parts.
Patchy builds every command, opens folders with EXAMINE and fetches with
BODY.PEEK, so nothing a patch does changes the mailbox or marks mail as
read. `patchy dev` reads the real mailbox the same way, and admins see
every call in the connection's recent calls.

How it works:

- **Reads.** The generated `imap` client has six typed reads:
`listFolders`, `folderStatus`, `scanMessages`, `listMessages`,
`searchMessages` and `getMessages`, in actions only. They follow through
the wire, runtime dispatch, the callback gateway, the guest runtime,
client error decoding, generation, the dev door, `docs/API.md`,
`docs/product.md`, the glossary and a new `patchy-imap` skill.
- **Sessions and gates.** Each host process keeps logged-in sessions per
connection and credential revision. A call waits at three gates, in
arrival order: 2 calls per mailbox, 8 per mail server and 32 per
process. If they stay full, it answers `busy` with nothing sent. A
session goes back to the pool only when its call finished cleanly. A
deadline, an interrupt, a parser or byte bound, or a broken socket
destroys it instead. A read that loses its session is retried once on a
fresh one.
- **Pages and refs.** Scans and searches walk UID windows within a
budget, so a page can be empty and still not `done`. Cursors and
checkpoints are bound to their call, folder and UIDVALIDITY. A ref is `{
connection, folder, uidValidity, uid }`, and anything made before a
folder was reset fails `mailbox_reset`.
- **Message text.** Text is the body made plain: HTML converted to text,
and hidden content, tag characters and bidi overrides removed, at most
256 KiB. No raw source, headers or HTML leave Patchy.
- **Refused logins.** A refused login pauses the connection (#1251's
pause), and calls fail `auth_failed` until an admin's Test or Replace
password succeeds.
- **Bounds.** Every bound is in the limits registry and
`docs/limits.md`.
- **Dev scenario.** `pnpm dev up imap` now publishes an `invoice-inbox`
patch that reads the scenario's mailbox.

Part of #1250
Closes #1252

## Look at

The evidence below was captured at `0c7ef0f`, before the review fixes.
None of those fixes changes what it shows.

### Reading in `patchy dev`

The scenario patch's agent tools, called through `patchy dev` against
the scenario's mail server. Trimmed.

```console
$ patchy dev agent readInbox '{"since":"2026-11-01"}'
{
  "result": {
    "folders": ["Projekte", "Projekte/Überweisungen", "Statements", "Invoices", "Invoices/2026",
                "Drafts", "Junk", "Sent", "Trash", "INBOX"],
    "messages": [
      { "uid": 2, "from": "Accounts", "subject": "Invoice INV-88213: October freight",
        "received": "2026-11-02T15:40:00.000Z", "attachments": true, "unread": true },
      { "uid": 3, "from": "Accounts", "subject": "Reminder: INV-87760 is overdue",
        "received": "2026-11-04T08:05:00.000Z", "attachments": false, "unread": true },
      { "uid": 4, "from": "Kai Becker", "subject": "Rechnung 7731 für Werkzeuge",
        "received": "2026-11-05T11:22:00.000Z", "attachments": true, "unread": false }
    ]
  },
  "version": 1
}
Server build 1 answered as Allison Mahmood via patchy dev.

$ patchy dev agent searchInbox '{"text":"INV-88213"}'
{
  "result": {
    "matches": [
      { "uid": 2, "from": "Accounts", "subject": "Invoice INV-88213: October freight",
        "received": "2026-11-02T15:40:00.000Z", "attachments": true, "unread": true }
    ],
    "first": {
      "subject": "Invoice INV-88213: October freight",
      "text": "Please find attached invoice INV-88213 for October's three pallet deliveries. Total 3,412.50 GBP, due 30 November.",
      "parts": ["text/plain", "INV-88213.pdf"]
    }
  },
  "version": 1
}
Server build 1 answered as Allison Mahmood via patchy dev.
```

### Published, as a member

The published patch, opened by Priya Raman, a member. First its import
since 25 October, then a search with the found message's text and parts.

![The published invoice inbox listing four messages since 25
October](https://github.com/user-attachments/assets/c660597b-fd59-444d-a730-95635246f96b)

![The published invoice inbox after searching "Rechnung", showing the
message's text and its
parts](https://github.com/user-attachments/assets/91a56f0e-f7e8-4c0e-ab38-a7c54c5e271b)

### Nothing on the server changed

FLAGS read from the scenario's mail server after every read above:

| UID | Subject | Flags after the reads |
| --- | --- | --- |
| 1 | Factura nº 2026-0412 — papel reciclado | none |
| 2 | Invoice INV-88213: October freight | `\Recent` |
| 3 | Reminder: INV-87760 is overdue | `\Recent` |
| 4 | Rechnung 7731 für Werkzeuge | `\Seen \Recent` |

Message 2's text was read in dev and is still unread. Message 4 was
already read before any of this: the dev read above answered `"unread":
false` for it.

### Recent calls

Each read is recorded with its operation, who it ran as, how long it
took and how many folders or messages it answered. Dev reads carry the
Dev badge. No subject, body, address or search value is kept: a sentinel
test checks recent calls, logs and wide events for them.

![The connection's recent calls in #1251's earlier layout: four reads
from the published patch as Priya Raman, then four marked Dev as Allison
Mahmood](https://github.com/user-attachments/assets/f56d6332-699a-4c54-aba0-fa6332173b42)

This is the connection page's earlier layout, captured before the
rebase. #1266 has since fixed both flaws it shows: recent calls span the
page, so Outcome isn't clipped, and their intro is IMAP's own instead of
Postgres's line about query text. #1264's evidence shows the new layout.

## How it was verified

- **Offline.** 142 tests in 15 files run over a scripted IMAP server
through the network seam. They cover:
- the exact commands each read sends, never a write or a non-peek fetch,
and never `n:*`;
  - refusals before anything is sent;
  - the session pool and its gates;
  - the login pause;
  - parser and byte bounds destroying a session;
  - an interrupt at the login, at the recheck and mid-command;
- a reused cursor, `since` with and without ESEARCH, and an expunge
mid-scan;
  - 25 bodies of about 1 MB read in one FETCH.
- **Live.** `pnpm test:imap`, the `IMAP live` workflow's suite, passes
15 tests on Dovecot (TLS and STARTTLS) and GreenMail. The reads' tests
check `\Seen` unchanged after every read on a non-ASCII folder, a 25-ref
page ending in a `not_found`, `since` with no matches answering an empty
`done` page, an expunge mid-scan, search paging across 1,090 deleted
UIDs, and a UIDVALIDITY reset answering `mailbox_reset`.
- **From a tier 2 action.** A sentinel goes through a real action and is
found nowhere in recent calls, logs or wide events.
- **Charsets on every runtime.** CI's first run caught Node 22.22.0
reading windows-1252's bytes 0x80–0x9F as C1 controls, for `latin1`,
`iso-8859-1`, `us-ascii` and the other labels WHATWG maps there.
`0afc4f2` decodes windows-1252 itself. The read modules' tests pass on
Node 22.22.0, 22.23.4, 24.20.0 and 26, and on Bun.
- **`pnpm check`.** Format, lint, typecheck and infrastructure synth
pass. These local test failures aren't this PR's, and CI should settle
them:
- the CLI stub-server suites (`cli`, `cliPublish`, `cliLifecycle`,
`cliLook`, `cliLogs`, `cliRepo`), where a stray `GET /` from the
editor's port probes on this machine reaches the stub;
- `install.test.ts` and `cli-smoke`, which find a `node` with no npm
beside it on this machine;
  - the `LocalTaskProvider` flake;
- the `Supervisor` flake ("does not reap active calls as idle…"), which
fails the same way with this PR's one change in that path reverted.
- **Not checked:** a real company mailbox. Only Dovecot, GreenMail and
the dev scenario's server have been read.

## Review

Grok 4.7 reviewed `feat/imap-reads` at `0c7ef0f`. Each finding was
checked against the code:

| Grok's finding | What happened |
| --- | --- |
| A logged-in session could leak when a call is interrupted
(`Sessions.ts`) | **Fixed** in `e3795d2`. The path Grok named was
covered, because `onError` runs on interruption. Three nearby windows
weren't: inside `open` after the login, between `open` returning and the
recheck, and between the recheck and the call's own exit handler. A try
now runs masked, only the login and the call's work can be interrupted,
and one exit decides whether the session goes back or is closed. A test
interrupts during a held LOGIN and at the recheck, and checks the server
has no session left. Each half fails with its close removed. |
| P2: a gate's waiters can starve | **Fixed** in `e3795d2`. A waiter
used to take and give back a permit, then race newcomers for it. The
gates now hand a freed permit straight to the call that has waited
longest. Only the waiting is interruptible, and a waiter handed a permit
as it's interrupted passes it on. A test checks arrival order, and that
an interrupted waiter holds nothing. |
| P2: a failed pause write is swallowed | **Fixed** in `f1db477`. The
write is retried once. A failure that remains is logged at error level,
and the wide event gets `imapPauseFailed: true`. The caller still gets
`auth_failed`. |
| P2: the skill's `since` line is wrong without ESEARCH | **Fixed** in
`498a075`. The skill and `docs/product.md` now say an empty page that
isn't `done` means keep following `cursor`. The code already behaved
this way. |
| P1: grouped text fetches overflow the parser | **Dismissed.**
ImapFlow's `maxResponseSize` bounds one assembled untagged response and
resets when that response completes. Each message of a multi-UID FETCH
comes back as its own `* n FETCH` response, so each message's text, at
most 1 MiB, is checked alone against the 4 MiB literal and 8 MiB
response bounds. 25 such messages plus their summaries come to about 25
MB, inside the call's 32 MiB. `c722fbc` adds a test that reads 25 bodies
of 1,000,000 bytes through one FETCH. |

## Release impact

Tick exactly one.

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required

Additive: six runtime operations, two error codes (`auth_failed`,
`mailbox_reset`), new limits and a wide-event field. No migration and no
configuration change.

**Ships in the same release as #1264, with no deploy between them**:
#1264 adds each part's `attachment` flag and redefines `hasAttachments`
to match it, and an importer written against #1264 silently skips every
attachment on a release that has this PR alone.

- **What does a revert leave behind?**
- No schema, and no rows in a new shape. The pause and recent-call rows
these reads write are #1251's.
- Rolling back to `feat/imap-connections` alone, a published patch whose
actions call these reads stays up and keeps serving. Each read fails
`access_denied` ("The handler kind cannot use this callback
operation."), and its page shows whatever the action does with that
refusal.
- Republishing such a repo would mean `patchy refresh` onto #1251's
release, whose generated client has no reads. Its typecheck fails until
the IMAP calls come out.
- Rolling forward again restores published patches without a republish.
- **Does the release before it still work with that?** Yes. It reads
every row this PR writes, and it serves patches that declare a mailbox.
It just refuses their reads.

Built by Claude Opus 5.5 in Claude Code, reviewed by Grok 4.7.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Base automatically changed from feat/imap-reads to main November 7, 2026 13:07
allisonmahmood and others added 9 commits November 7, 2026 14:07
…call

An integration that hands an action a file, such as an IMAP attachment, needs
to stage bytes the host fetched, not bytes a page sent. Files' staging core now
backs both: the page's staging route and a new internal entry point,
FileStaging in runtime core, which stages for the call's viewer, patch and
loaded version under the same reservation, quotas, one-hour expiry and
single-use adoption. Only the Upload crosses into workerd.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ile store

stageAttachment({ ref, part }) checks the part against the message's current
BODYSTRUCTURE, refusing raw sections at the wire and a forwarded message's
container, then downloads it through the call's session: decodeText off, BINARY
where the server offers it, chunks of imap.download.chunk (1 MiB, held within
imap.parser.literal), and ImapFlow's byte bound one past files.stage.bytes, so a
part past 20 MiB answers too_large and is never staged cut. The bytes stage
through host staging and only the Upload, with the true size and sha256, goes
back to the action, which adopts it with ctx.files.<store>.put.

A process holds at most imap.attachments.concurrent attachments buffered at once,
from download to staging. A part past the bound or an abandoned download
destroys the session; refusals found before a download keep it.

Recent calls gain a bytes column (migration 0035), which a staged attachment
fills with its size and nothing else: never the filename or the Upload's token.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The dev door gets a private byte transport for imap.stageAttachment: the instance
downloads the part as a published stage does, under the dev read's authority,
slots, deadline, rate limit and recent calls, and answers its bytes, at most
files.stage.bytes, with their size, sha256, media type and filename in a header.
The dev daemon reads no more than the bound and stages the bytes in its local
store only once they match what the instance stated, so a transfer that ends
short, differs or runs over stages nothing. JSON results keep their 8 MiB bound,
and the generated client calls the same stageAttachment in dev and published.

The door's read and the attachment share one pipeline: logged before anything is
checked, rechecked once a slot is held, finished with the outcome and, for an
attachment, its size.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…o log or event

The IMAP journey stages an attachment through the generated client and checks
its true size and sha256 come back with the Upload. Its filename carries the
sentinel: recent calls record the stage by its size alone, and neither the
filename nor the Upload's token reaches recent calls, a log line or a wide event.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… and GreenMail

The live tier stages a PDF in base64, a CSV in quoted-printable, a text file in
8bit and a PNG inside a forwarded message, compared by sha256, on Dovecot (which
offers BINARY) and GreenMail (which doesn't). On Dovecot it stages a part of
exactly 20 MiB and refuses one byte more, and stages 20 MiB through a relay
adding 100 ms of round trip in about 4 seconds, inside the 15-second deadline.

GreenMail can't serve a forwarded message's own parts: it answers NO with a
ClassCastException of its own, which the test holds Patchy to relaying as the
server refusing. It also drops a text part's final line break from its section,
so the test's text files end without one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ts files

invoice-inbox gains the reference importer: one action that imports INBOX from a
day into messages and attachments tables, saving each attachment's file into its
documents store by ref and part, and resumes from the checkpoint of the last
page it finished. A read-only action lists the saved files with the digest each
was staged with and the digest of the bytes stored now, and the page and the
patch's agent tools offer both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r that runs live

The patchy-imap skill says how an action stages an attachment and adopts it into
the patch's own file store: the answer, the refusals, the staging limits, names
from the ref and part, the filename as display text only, and what a failed
write after adoption leaves. It carries one complete importer, word for word the
imap scenario's (a test holds the two equal), which brings a date window of a
folder into tables and files and resumes from the checkpoint of the last page it
finished.

The live tier runs that importer from the skill in real workerd over real
tables and files against Dovecot: a stage refused on quota, a message expunged
as its page is read, an attachment past the staged-file bound kept by name and
size, a row write that fails after its file was adopted, and a restart that
imports only what arrived since.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lities and ADR-0013

The product's Email (IMAP) sections describe stageAttachment: the part checked
against BODYSTRUCTURE, the download through the call's session with BINARY or
decoding, the 20 MiB bound one past which nothing stages, host staging's quotas
and expiry, the process's attachment places, names by ref and part, the dev
door's byte transport, and recent calls recording a stage's size. The IMAP
operation glossary entry, the SDK's capability list, ADR-0013's door and the
scenario README follow. The skill adds the attachment refusals and timing, and
says server code reads a refusal's code where the page narrows with
isPatchyError.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…vers under load

It sets up a scripted server and a connection for each transfer encoding with
BINARY and without, which ran past vitest's five-second default while the whole
suite ran in parallel.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
allisonmahmood and others added 13 commits November 7, 2026 14:07
…sent

The dev door held one of the process's imap.attachments.concurrent places only
around the download, then answered the whole buffer as one body. A patchy dev
client that read slowly let the next downloads start while earlier buffers were
still being sent, past the bytes the limit bounds on the cloud process.

The door now takes the place into the request's own scope, which the server
closes only once the response is written or the client goes, and streams the
body 64 KiB at a time as the socket drains. Sessions gains placeIn for a holder
whose buffer outlives one effect; its take and its finalizer are one step. A
test holds a client that stops reading a 19 MiB body: the process's one place
stays taken until the body is read, then comes back. The published path already
held its place through staging.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Agents choose skills by their description, which said only reading folders,
messages and text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The wide event's stagedBytes was set on each download, so a request that staged
several attachments kept only the last one's size, and a stage refused at the
quota reported bytes it never staged. It's now added once a stage succeeds,
summed over the request, and a test holds two stages to their sum and a refused
one to nothing. The other per-call byte and wait fields already add.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…carries

The importer saved only parts with disposition attachment, so a named PDF some
mail clients send inline wasn't imported, and agents copying the importer would
copy the filter. Each part now says whether it's the message's body: its text,
a rendering of it such as an HTML twin, or the part it's encrypted in, as the
structure reader already knows. The importer saves every part that isn't the
body and isn't a forwarded message's container, a forward's own parts included,
in the skill and the scenario alike. The live importer test imports a named PDF
sent inline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…loads

With the dev daemon's local staging full, the instance still downloaded the
part, up to 20 MiB, and its recent calls showed the stage succeeded while the
action got limit_exceeded. Host staging gains admits, which refuses as a stage
would without reserving anything, from the same quota query the reservation
runs. The daemon asks it before the door, so a full count downloads nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eeds nothing of callers

Both FileStaging methods required Binding from their callers' environment,
which the Effect checker refuses in a service's interface: a requirement every
caller must meet belongs to the layer, not the methods. The Binding is the
call's, not the layer's, so stage and admits now take it as their first
argument, and Files checks it as the page's staging route does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… downloads

A call past its viewer's staging quota was refused only after it took an
attachment place, logged in and fetched the part. It now asks staging
first, so a full quota sends no FETCH. A stage can still be refused after
the download if others fill the quota meanwhile; that refusal is handed on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…saves only those

`body` left the importer to work out what a file is, and it saved a
forward's own text and HTML as nameless files and an HTML body's cid:
logo, while hasAttachments said false. Each part now carries
`attachment`, decided once in the structure reader: attached by
disposition, or named and not a resource the body embeds (inside
multipart/related with a Content-ID); never the body or a forwarded
message's container, while a forward's own files count. hasAttachments
is true exactly when a part is one. The reference importer, in the skill
and the scenario, saves exactly those parts, and the live tier imports a
forward and an embedded signature logo alongside them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s files do

A signed message's signature part arrives attached, so every signed
message said hasAttachments and the importer saved its smime.p7s or
.asc, which mail programs show as a badge. The signature part of a
multipart/signed (pkcs7-signature, x-pkcs7-signature or pgp-signature)
now joins the body on the never list.

A PDF with no filename and no disposition was skipped, though mail
programs list it. A part of any type other than text now counts like a
named one, unless it's a resource the body embeds; nameless text that
isn't the body still doesn't, so a forward's own text and HTML stay out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tachment

Counting every part that isn't text made a bounce's delivery status and a
read receipt's notification attachments, so each would become a junk
file in every importer. Any message/* leaf now counts only when attached
by disposition; message/rfc822 stays a container whose own parts follow
the rule, so a bounced message's PDF still counts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ver its filename

#1266 gave each integration's recent calls an intro saying what its
calls keep. Stages now record a size, so IMAP's says how much each call
read, rows or an attachment's size, and that attachment filenames and
upload tokens are never logged, beside subjects, bodies, addresses and
search values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s of 25

A scan page holds up to 100 messages and getMessages takes at most 25,
but the importer passed the whole page, so any window past 25 messages
was refused invalid_request on its first page and never imported. It
now reads each page 25 refs at a time, in the skill and the scenario
alike, and the skill says why beside it.

The live importer test adds a folder of 130 messages, past one scan
page and past 25 refs, with a PDF on every tenth. A row write on the
second page fails once, and the next run imports only that page: every
message is kept once, with no gaps. The workerd plumbing test that read
three messages no longer claims to import.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… 8 MiB

A batch of 25 refs is bounded in refs, not bytes, and getMessages
refuses a whole answer past 8 MiB. Long plain-text mail with escaped
quotes can pass it, and the importer then failed on that batch on every
run. It now reads a refused batch again in halves; one ref always fits,
since a message's answer is at most 1 MiB, so the common case stays one
call per 25 refs. The skill and the scenario change together, and the
skill says why beside the importer.

The live importer test adds long quote-heavy exports sized from
runtime.result.bytes so 25 answer past it: the first batch is refused
once and read in halves, and every message is kept once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood merged commit 17b1ad8 into main Nov 7, 2026
25 checks passed
@allisonmahmood
allisonmahmood deleted the feat/imap-attachments branch November 7, 2026 13:35
allisonmahmood added a commit that referenced this pull request Nov 7, 2026
…nts (#1293)

## What changed

This adds release 39's What's new entry, written from `17b1ad8`. It
covers everything merged since release 38's `through` (`1d59c40`), and
sets the `patchy` release to `0.39.0` in `packages/patchy/package.json`
and `CURRENT_RELEASE`.

| Change | PRs |
| --- | --- |
| New: Patches can read a company mailbox | #1266, #1262 |
| New: Patches can keep email attachments | #1264 |
| Improved: Recent calls fit a connection's page | #1266 |
| Behind the scenes: a refused mailbox password pauses the connection
after one try | #1266, #1262 |

#1247 is release 38's own entry. The range is exactly the Email (IMAP)
stack, which ships as one release.

## Look at

- **The entry**, at the top of `releases` in
`packages/core/src/whatsNew.ts`.
- **Rollback safety, from the live commit `cbbd767` (release 38) to this
PR's merge:**
- **#1266 is `one-way`.** It adds the `imap` integration kind. Release
38 can't decode a manifest that declares `imap`, so after a rollback,
patches published with an Email (IMAP) connection would fail. No
migration.
- **#1264 is `one-way`.** Its parts carry an `attachment` flag that
#1262 alone doesn't have. That only matters for a rollback to a release
holding #1262 without #1264, and none exists, because the three ship
together here.
- **#1264 adds migration `0035_runtime_calls_bytes`,** a nullable column
that release 38 ignores. Its `rollback-rehearsal` check passed.
- **No new configuration or infrastructure.** Hosts already allow
outbound connections, so mail servers on ports 993 and 143 are
reachable.
- **Open PRs #1204 and #1217 also claim migration id 35.** Whichever
lands next must renumber to 36; the migration ledger test fails until it
does.

**Rollback line:** Rolling back past #1266 would break patches that
declare an Email (IMAP) connection, because release 38 can't read a
manifest that declares `imap`; fix forward instead.

## How it was verified

- **Tests.** The `packages/core` What's new test and the `packages/api`
suites pass (69 tests).
- **The range.** Each of #1266, #1262 and #1264:
- had Grok 4.7 reviews, with every finding fixed or answered in writing;
- had acceptance verdicts (PASS with notes), the last run end to end
across the stack, with 260 messages imported, resumed and saved byte for
byte against a local mail server;
- had all 18 required checks green on the head it was squash-merged
from.
- **The stacked merges.** #1262 and #1264 were rebased onto `main`
between merges. Each rebased tree was identical to the head its verdict
was given on.
- **Deploy state.** The live commit, pinned from `/healthz/deep`, is
`cbbd767` (release 38). The Deploy run updated last succeeded, and none
is unfinished.

## Release impact

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required

Text and version numbers only. Like every release, the `0.39.0` bump
tells CLIs and patch repos installed before this deploy to upgrade. The
release it announces is `one-way`; see the rollback line.

- **What does a revert leave behind?** Nothing.
- **Does the release before it still work with that?** Yes.

Built by Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, through T3
Code.

Co-authored-by: Claude Opus 5.5 <[email protected]>
allisonmahmood added a commit that referenced this pull request Nov 8, 2026
## What changed

The switcher (#1091) needs to know which patches a person can jump to,
and nothing could tell a browser that yet. `GET /switcher.json` now
answers a signed-in person's browser with their company's live patches,
with their own open times, and the patches other companies shared with
them that they can open now. Another company's public patch never
appears, including a shared one while it is public. Nothing calls the
route until #1270.

Closes #1269

## Look at

**The public filter.** A guest grant outlives its patch going public and
back (`Guests.test.ts`), so `GuestGrants.sharedWith` now carries each
patch's current `scope`, and the list leaves out shared rows that are
public or that the guest can't open now. Home's use of `sharedWith` is
unchanged. Here it is on a local `guests` environment: Jo works at Pine
Studio and has both Harbor Works patches shared with them. Ben is a
Harbor Works member. Ada flips Site notes public and back with the CLI:

```
$ patchy share --patch 4ylw24ddt1xf public
jo: ["visit-log"]   ben: ["site-notes","visit-log"]
$ patchy share --patch 4ylw24ddt1xf company
jo: ["site-notes","visit-log"]   ben: ["site-notes","visit-log"]
```

**Who gets an answer.** Any request whose `Sec-Fetch-Site` isn't
`same-origin`, and any request with an `Authorization` header, is
refused before authentication, so it can't start a Clerk handshake.
Every refusal is JSON with `private, no-store`, never the sign-in page
or a redirect. Once Clerk has read the session, every answer carries the
cookies Clerk set, as a page's does. That way a session Clerk refreshed
server-side, from an expired session cookie plus its refresh cookie,
stays refreshed in the browser. A handshake still answers
`session_refresh_required` without the handshake's cookies, because a
script can't follow that redirect. Same environment:

```
Jo, Sec-Fetch-Site: cross-site             403 application/json {"code":"access_denied"}
Jo, Sec-Fetch-Site: same-site              403 application/json {"code":"access_denied"}
Jo, Sec-Fetch-Site: none                   403 application/json {"code":"access_denied"}
Jo, no Sec-Fetch-Site                      403 application/json {"code":"access_denied"}
signed out, same-origin                    401 application/json {"code":"session_expired"}
Ada's machine token, same-origin           403 application/json {"code":"access_denied"}
```

That machine token gets `200` from `/api/me`.

**The final shape, for #1270.** Close to the issue's sketch:

```ts
// 200, cache-control: private, no-store
{
  viewer: { id, companyId, role: "member" | "admin" },
  company: { handle, name },
  whatsNewUnseen: number,  // What's new changes since the viewer last looked
  // The company's live patches the viewer can open, public ones included: their own first, then by name.
  // openedAt (ISO) and score (the halving open score Home's Your usual ranks by) only once they've opened it.
  patches: [{ id, name, title, tier, mine, openedAt?, score? }],
  // Shared with them, openable now, not public: by company name, then patch name.
  shared: [{ id, company: { handle, name }, name, title, tier }]
}

// Refusals: { ok: false, code, error }, cache-control: private, no-store
// After Clerk reads the session, any answer may also carry its Set-Cookie directives.
// 403 access_denied             Sec-Fetch-Site not same-origin (missing and none included), any Authorization
//                               header, no membership, or deactivated
// 401 session_refresh_required  Clerk wants a handshake, or the session token expired
// 401 session_expired           signed out
// 503 unavailable               Clerk or the database failed
```

The session codes are the runtime stream's own, so the script can follow
`stream.ts`'s refresh pattern. `title` is as published and may be blank,
so the client falls back with core's `patchTitle`. The payload type is
`SwitcherList.SwitcherList` in `@patchy/portal`. If #1270's browser
script wants the type, lift it into core there. Core now exports
`monogramTint`, the mark's tint picker, so the menu's marks match the
portal's. `monogram` renders the same markup as before.

## How it was verified

- `PortalPages.test.ts` › "the switcher's list", four cases:
- A member, the owner and an admin each get the full body: their own
patches first, `mine` set, and only the member's own open. A retired
patch, a disabled patch and another company's company-scope and public
patches are all absent.
- A guest gets shared rows only. One patch goes public and back on the
same grant and drops out, then returns. A revoked grant goes, then a
disabled patch. A retired shared patch and the host company's own public
patch never appear.
- Refusals: cross-site, same-site, `none` and missing `Sec-Fetch-Site`,
with a valid, a stale and no session, all `403` before authentication. A
live machine token, with and without a session, gets `403`. A stale
session gets `401 session_refresh_required`, signed out `401
session_expired`, no membership and deactivated `403`. All are JSON with
`private, no-store`.
- Clerk's server-side refresh: an expired session cookie plus Clerk's
suffixed refresh cookie gets `200` with the refreshed `__session` and
refresh cookies. The portal suite's sessions now use a stub Clerk
backend for this. Over the first commit's route, the same request got
`200` without the cookies, which was Sol's finding.
- The tests bite. Dropping the public filter fails the guest case, and
dropping the `Sec-Fetch-Site` check fails the refusal case (`expected
200 to equal 403`).
- The stream's refresh rule moved into `Session.refreshable` so both
routes share it. `RuntimeStreamApi.test.ts` and the browser suite's
stream refresh tests still pass.
- `pnpm check`: format, lint, typecheck and synth pass. `pnpm verify`
(under the shared lock): postgres-concurrency and tier2-smoke pass.
`test`, `test (bun)`, `cli-smoke`, `install` and `browser` failed only
for two local machine reasons:
- A stray `GET /` reaches the tests' stub servers on local ports. That
broke the CLI stub-log tests and `LocalTaskProvider` in `test`, and one
`tier1.spec.ts` case whose "foreign origin" stub saw `"/"`. In `test
(bun)` every file passed (256/256) and the probe only threw uncaught
JSON parse errors in `devExecution.test.ts`'s stubs.
- `/usr/bin/node` has no `npm` beside it. That broke `install.test.ts`,
`install` and `cli-smoke`'s install line.

Both reasons fail the same way on `origin/main`. The same four files
there fail 12 tests, with the same stray `"/"` and `npm is not on PATH`.
Rerun alone, the full tier 1 browser suite passed (85/85). After
rebasing onto #1264: typecheck passes, and `PortalPages`,
`RuntimeStreamApi`, `GuestGrants`, `Guests` and `core/html` pass (129
tests).
- After the cookie fix: `pnpm check` passes format, lint, typecheck and
synth. Its tests failed only for the stray `GET /`, `npm is not on
PATH`, and timeouts under a load average of 43. The nine suites that
timed out or that this touches pass when run alone: `McpDoor`, `Tables`,
`SdkApi`, `QuerySnapshot`, `InvocationLocal`, `RequestEvents`,
`RuntimeStreamApi`, `Guests` and `Session` (110 tests). The whole portal
suite passed in that run. I didn't rerun `pnpm verify`: the fix touches
only this JSON route and its test, which none of verify's acceptance
suites exercise.
- Not checked: CI on Linux, which doesn't have either machine issue.

Hit every surface:
- **Wire contract:** doesn't apply. The route is Portal-owned and
session-only, not in `packages/api`, so there's no CLI command and no
`docs/API.md` change.
- **Vocabulary:** Portal's `GLOSSARY.md` gains **Switcher list**.
`docs/product.md` waits for #1270, when people can see something.
- **Served pages:** no rendered HTML changes.
- **CLI, dev loop, migrations, company resources, reverse states, repo
layout:** none apply.

## Release impact

Tick exactly one.

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required

A new browser-only route that nothing calls yet. No migration, no CLI or
API change.

- **What does a revert leave behind?** Nothing. No rows, schema or
configuration change, and nothing calls `/switcher.json` before #1270.
- **Does the release before it still work with that?** Yes.

Built by Claude Opus 5.5 (xhigh) in Claude Code, orchestrated from T3
Code.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
allisonmahmood added a commit that referenced this pull request Nov 8, 2026
## What changed

Every open of a patch added a full point to that person's score for it,
and Home's **Your usual** sorts by that score. The coming switcher
(#1091) makes it easy to flip between two patches all day, and each flip
would add another point, so those two would crowd everything else off
the shelf. Now an open adds its point only when it comes at least 10
minutes after the person's last open of that patch. An open inside the
window still moves the last-open time, so a patch reopened every few
minutes counts about once. The score now counts separate returns, not
raw opens.

Closes #1267

## Look at

**The conflict branch of `upsertOpen`**
(`packages/patches/src/Patches.ts`). Only the incoming open's term is
gated, on `abs(EXCLUDED.last_opened_at − patch_opens.last_opened_at) ≥
10 minutes`. `GREATEST`, both decay terms, the current-version and
serving predicate and the `xmax = 0` first-open check are unchanged:

```sql
score = patch_opens.score * halving(latest - patch_opens.last_opened_at)
  + CASE WHEN abs(extract(epoch FROM EXCLUDED.last_opened_at - patch_opens.last_opened_at)) >= 600
    THEN halving(latest - EXCLUDED.last_opened_at) ELSE 0 END,
last_opened_at = latest
```

The `abs` keeps the existing late-arrival case working: an open stamped
a week earlier that arrives late still adds its age-correct half point.
The rule goes by arrival order, as the issue accepts. Opens at minutes
0, 18 and 9, arriving in that order, count twice, because the row keeps
only the last open.

**The new and changed tests, red then green.** I put `origin/main`'s
`Patches.ts` back under the new tests (`git restore --source=origin/main
-- packages/patches/src/Patches.ts`):

```
× remembers each member's opens of live patches, halving every week
    AssertionError: expected 2 to be close to 1 +/- 1e-9
× counts reopens within 10 minutes of the last open once
    AssertionError: expected 1.9993137356513948 to be close to 0.9993137356513948 +/- 1e-9
× lets exactly one of a member's racing opens be their first
    AssertionError: expected 3 to be close to 1 +/- 1e-9
```

With the change:

```
✓ remembers each member's opens of live patches, halving every week
✓ counts reopens within 10 minutes of the last open once
✓ reads a decade-old open as nearly nothing and still counts the next one
✓ lets exactly one of a member's racing opens be their first
```

The new test covers four things:
- An open 9:59 after the last adds nothing and still moves
`last_opened_at`.
- A second open 9:59 after that one also adds nothing, because the
window is measured from the last open, not the last one that counted.
- An open exactly 10:00 after the last counts.
- An earlier open that arrives late inside the window adds nothing and
leaves the last open where it was.

The week-late case, first-open attribution and the simultaneous-insert
race keep their tests. Their expected scores drop where their opens land
in one instant: the racers now total 1, not 3. Two mutations are also
caught: `>` in place of `>=` fails the exact-10:00 step, and dropping
`abs` fails the week-late case.

## How it was verified

- `pnpm exec vitest run` over `packages/patches/src/Patches.test.ts`,
`packages/portal/src/PortalPages.test.ts` and
`packages/serving/src/Pages.test.ts` (the suites that record or read
opens): 173 passed.
- `pnpm check`: format, lint, typecheck and synth pass.
- `pnpm verify` (on the previous base, before the docs-only #1264 and
#1293): `postgres-concurrency`, `tier2-smoke` and `browser` (85
Playwright tests) pass.
- Failing locally, and failing the same on `origin/main`:
- The `test`, `test (bun)`, `cli-smoke` and `install` steps hit two
known causes on this machine. CLI stub servers get a stray `GET /`, and
npm is missing beside `/usr/bin/node`, which stops the installer tests
and the install line in the packed e2e.
- `Supervisor` and `PatchesApi` each timed out once under load and pass
when run alone.
  - CI is the arbiter for these.
- Not checked: Home visibly reordering with real usage. This change only
alters scores; no page's markup changes, so there are no screenshots.
The new test shows the "Done means" behaviour at the score: reopening
every few minutes counts once, and an open 10 minutes or more after the
last, including a late one, still counts.

**Hit every surface:** only *Vocabulary and product shape* applied. The
**Open** entry in the Patches glossary and the **Your usual** entry in
the Portal glossary say how reopens count, and so do the `Open.score`,
`recordOpen` and `REOPEN_WINDOW` comments. `docs/product.md` still holds
("opened most in the last 30 days"). Nothing changes in the API, the
CLI, the dev loop, migrations, company resources, the markup of served
pages, or the repo layout.

## Release impact

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required

This changes how a score is computed. There is no schema change, and no
API or CLI change.

- **What does a revert leave behind?** Scores already written under the
new rule, lower for patches reopened in quick succession. They stay as
written, in the same columns and shape.
- **Does the release before it still work with that?** Yes. It reads and
writes the same `patch_opens` rows. During a rollout, old servers still
count every open, which only inflates scores the way they did before.

Built by Claude Opus 5.5 (xhigh) in Claude Code, orchestrated from T3
Code.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area area:integrations Company connections and integration implementations area:primitives Patch tables and files area:server Touches the server area one-way Rolling production back past this PR would break the release before it size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(integrations): patches save IMAP attachments into their files

1 participant