Skip to content

feat(integrations): patches read IMAP folders and messages - #1262

Merged
allisonmahmood merged 17 commits into
mainfrom
feat/imap-reads
Nov 7, 2026
Merged

allisonmahmood merged 17 commits into
mainfrom
feat/imap-reads

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Nov 6, 2026 •

Copy link
Copy Markdown
Owner

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 (feat(integrations): admins connect an IMAP mailbox with a password #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.

$ 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

The published invoice inbox after searching "Rechnung", showing the message's text and its parts

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

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
  • 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 feat(integrations): admins connect an IMAP mailbox with a password #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 feat(integrations): admins connect an IMAP mailbox with a password #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.

@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:integrations Company connections and integration implementations area:ui Portal and first-party browser pages, shared rendering and styles size:xl Over 1,000 changed lines; review in multiple passes labels Nov 6, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Acceptance: PASS with notes

Checked d05caa3bd4a73f020fea6063945f9e6e7465672b (base feat/imap-connections at f9897e71e12dbd4b289a7dd4c815d2e9aa04a503, 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, 0ac096f (#1264's head), after the rebase onto #1266's pages. That commit carries this PR's 17 commits unchanged. This replaces the PASS with notes at 1a4a96c, which is folded in at the end.

What the rebase moved. git range-diff 08626e4..60cf6c4 f9897e7..d05caa3 shows all 17 commits as identical patches. Only the base moved: it gained #1266's two new commits, IMAP's connect and connection pages on the shared frame, and a security that disagrees with the port shown under Port. Before the rebase, the only commit after 1a4a96c was 60cf6c4 (now d05caa3), the skill's too_large line.

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, and added acceptance-only read tools. None of this was pushed.
  • I put 242 messages in a new Acceptance folder, then 4 more: 3 before 1 October, 230 notes through October, a forward, a cid: logo, S/MIME- and PGP/MIME-signed mail, a nameless PDF, an RFC 2231 filename and two 20 MiB files.
  • I called the tools in patchy dev as Allison, and published as Priya (member) through Patchy MCP. I also used the scenario's invoice-inbox page as Priya.

Done means

  • Lists folders: passed.

    • The scenario mailbox's 10 folders, Projekte/Überweisungen decoded, in patchy dev and on the published page.
    • The new mailbox's 6 folders, at connect and in patchy list connections imap/acceptance.
  • Imports a folder from a date in resumable pages: passed, in dev and published.

  • Lists newest first: passed. listMessages paged 100, 100 and 46, from UID 246 down to 1, strictly descending, in dev and published.

  • Searches: passed. As Priya through Patchy MCP, newest first:

    • a body token: 1 match;
    • from: 2 matches;
    • a non-ASCII subject, für März: 1 match;
    • since a day: 4 matches;
    • a body phrase in 230 messages, paged from UID 233 down to 4.

    On the scenario's page, a search for "Rechnung" found its message and read its text.

  • Reads messages with their text and parts: passed.

    • getMessages answered text and parts for every case, the same in dev and published.
    • A forward lists its container (2) and the parts inside it (2.1.1, 2.1.2, 2.2).
    • An RFC 2231 filename reads decoded.
  • None of this changes the mailbox: passed.

    • Flags and modseq. I snapshotted both mailboxes' folder status, and every message's flags and modseq (doveadm), before any read. After everything here, the pause included, every message that was there before is unchanged, \Recent included. HIGHESTMODSEQ moved by exactly my own 34 appends.
    • Unread stays unread. Mail whose text and attachments were read is still unread.
    • 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 pause across the stack: passed.

  • The setup. I changed the mailbox's password on the mail server, then waited for Patchy's pooled sessions to log out.
  • One refused login, then a pause. Priya's next read through the published patch failed with "mail.fernhill.test refused this username and password. Check both, or make an app password if the host has them." The mail server logged exactly one refused login ("auth failed, 1 attempts"). patchy list connections then showed imap/acceptance as "paused, its password was refused".
  • Nothing reaches the server while paused. Four later calls each answered auth_failed with not one line in the mail server's log: the importer and a search as Priya (published), and a folder status and the importer in patchy dev. Each said "This connection is paused…", and recent calls recorded each one as auth_failed.
  • Replace password restores it. Allison used Replace password on the connection page ("Test and replace password"), and the pause cleared. Priya's reads and importer worked again, and a ref made before the change still staged in patchy dev.
  • Test is the other way out. The rotation also refused the scenario's other mailbox on the same server, which paused on its next read. Restoring that password and pressing Test again cleared it.

imap/acceptance paused: "Paused: the mail server refused the password", with Replace password and Test again

After Replace password: Connected, "Password replaced and tested. Patches keep reading the same mailbox."

Recent calls: passed.

  • Layout. The merged table spans the page at 1280, 1440 and 1920 px, with no clipped cell.
  • Rows. Reads show their rows (36 ms · 30 rows), dev reads carry the Dev badge, and calls through Patchy MCP say "Priya Raman via acceptance".
  • IMAP's intro is its own, saying what a call keeps.
  • No leaks. Neither connection page, nor runtime_calls, the server's log or the dev daemon's log, holds a subject, sender address, search value or filename from this run.

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

  • Search paging through empty windows: it needs hundreds of thousands of UIDs. The live tier covers it.
  • The gates' busy, and interrupted sessions: the offline suite covers them.
  • pnpm test:imap locally: CI's imap-live passes on the head.
  • A real company mailbox: none available, as before.

Notes

  1. The stack's release waits on feat(integrations): patches save IMAP attachments into their files #1264's FAIL.
    • feat(integrations): patches save IMAP attachments into their files #1264's reference importer hands a whole scan page, up to 100 refs, to getMessages. Its 25-ref bound is this PR's, so any window with more than 25 messages fails invalid_request on its first page.
    • It fails that way in patchy dev and published, the scenario's own patch included.
    • None of this PR's own claims break, but the two ship together. One way to fix it, letting getMessages take a page's 100 refs, would land here.
  2. Out-of-wire arguments still get a generic refusal (earlier note 4). "Runtime request refused: invalid_request." names no argument and no bound, and it's what made feat(integrations): patches save IMAP attachments into their files #1264's importer failure hard to read.
  3. Earlier note 2 is fixed. The skill now says one message answers too_large only when what Patchy returns for it passes 1 MiB. Earlier note 3 (a cursor goes back with its call's starting arguments) stands as designed: the skill and the error both say so.
  4. Not this PR's: at 1024 px, feat(integrations): admins connect an IMAP mailbox with a password #1266's recent-calls table is 32 px wider than its scrolling container, so the Outcome badge's right edge is cut until you scroll.
Earlier verdict at 1a4a96c: PASS with notes

Checked 1a4a96c (base 08626e4) on imap, by Claude Opus 5.5 in Claude Code (T3 Code).

The head moved while I worked. I ran the whole check at 7e5fbfb, then rechecked at 1a4a96c what its one new commit touches (charset decoding): the read tests on Node 22.22.0 and 26, live reads of differently encoded mail, and the earlier messages again. CI on 1a4a96c was still running when I posted. Everything at 7e5fbfb passed except test (22), which 1a4a96c fixes.

I didn't replay the demo patch. I added thin probe actions over each read, plus an importer that stores rows and then its checkpoint, to the environment's copy of invoice-inbox. I seeded the scenario's mailbox with three new folders: Bulk (260 messages; UIDs 1–20 dated September, and UID 150 with an older date than its neighbours), Rich (attachments, non-ASCII subject, HTML-only, a forward, a 1.9 MB message) and Quotes (bodies that double in JSON). I called the probes through patchy dev agent, and published as Priya over Patchy MCP and on the page.

Done means

  • Lists folders: passed. 13 folders, including ones made after the snapshot; Projekte/Überweisungen decoded; Projekte and Invoices selectable: false; special-use flags kept. folderStatus matches doveadm, and a parent-only or missing folder fails not_found.
  • Imports a folder from a date in resumable pages: passed, in dev and published.
    • scanMessages({ folder: "Bulk", since: "2026-10-01" }) answered 3 pages (100, 100, 40), UIDs 21–260, and included UID 150 despite its older date.
    • Mail appended after page 1 wasn't chased: the scan still ended at 260. A scan after its checkpoint answered exactly the 3 new messages, and the next one answered an empty done page, not UID 263 again.
    • Published, Priya's agent ran the importer (change_patch) four times: one page, then a resume from the stored checkpoint, then one new message, then nothing new. That left 246 rows, UIDs 21–266, with no duplicates or gaps.
  • Lists newest first: passed. listMessages paged 100/100/63, strictly descending, 263 down to 1.
  • Searches: passed. Every count matched the seed: a body token (3), a subject prefix (10), from (37), a date window (16), unseen: false (52), four criteria combined (14), plus non-ASCII terms (für, Factura nº, 請求書, Zoë).
  • Reads messages with their text and parts: passed. In one batch of 9 refs, answered in order:
    • text/plain won over its HTML twin.
    • HTML-only mail lost script, style, display:none and hidden content, its bidi overrides and its tag characters, kept ZWJ, and rendered a link as text (url).
    • A forward's attached notes.txt and inner body didn't become the body, and its nested message/rfc822 parts (3.1, 3.2) were listed.
    • A missing UID answered { error: "not_found" } in place.
    • Text over 256 KiB was cut to exactly 262,144 bytes, marked truncated.
    • 15 heavy messages passed; 16 were refused too_large, naming the 8 MiB bound and saying to ask for fewer refs.
  • None of this changes the mailbox: passed. Before any read I snapshotted every folder's per-UID flags and HIGHESTMODSEQ with doveadm, then compared after the dev reads, after the published reads and after the rechecks at 1a4a96c:
    • All 270 pre-existing UIDs kept identical flags, and every UID added since did too.
    • Unread mail stayed unread after its text was read (INBOX unseen=3 throughout).
    • \Recent survived, so nothing ever SELECTed.
    • HIGHESTMODSEQ moved only by my own appends.
    • Dovecot logged every session out with deleted=0 expunged=0.

Refusals

  • Stale refs after a folder was deleted and recreated (mailbox_reset): passed. An old ref and an old checkpoint both fail mailbox_reset with details.folder. The recreated folder's UID 1 is a different message, and it was never served as the old one.
  • Reused cursors and checkpoints (invalid_cursor): passed. Each of these is refused:
    • a cursor with since dropped, changed, or on another folder;
    • a scan cursor given to listMessages, or the reverse;
    • a search cursor with other criteria;
    • a tampered cursor;
    • another folder's checkpoint.
  • A foreign ref (invalid_request): passed, with "A ref names another connection".
  • A refused login (auth_failed): passed. I broke the mailbox's password in the throwaway Dovecot.
    • Patchy tried one login, then paused the connection, and patchy list connections showed it paused.
    • The next calls failed auth_failed without another login reaching the server.
    • After the password was restored, reads stayed paused until the admin's Test, then worked.
  • Recent calls and logs: passed.
    • Recent calls record the operation, who ran it (a viewer's session, or "Priya Raman via acceptance"), the duration and the row count.
    • Neither recent calls nor the server log contained any searched value, subject, body text, sender address or the password.
    • Wide events show 82 pooled sessions to 2 opened.

Golden journeys

  • Use a tier 2 tool and Use a tool live: not run by me. This diff touches their path only additively: the callback allowlist, the guest's alias list and two new error codes. CI's packed tier 2 journey and its Chromium tier 1/2 pages passed at 7e5fbfb. The published invoice-inbox page ran its actions for Priya without browser errors:

The published invoice inbox as Priya: INBOX since 25 October, then a search for "Rechnung" with the message's text and parts

Rollback answers: they match the diff.

  • No migration, no apps/infra, and no rows in a new shape.
  • At the base, the callback schema takes any op, so a published patch's IMAP reads reach the allowlist and fail access_denied, "The handler kind cannot use this callback operation.", as the PR says.
  • No one-way label is needed.

Not run

  • Search paging through empty windows: needs more than 32 UID windows, hundreds of thousands of UIDs. The live tier covers it.
  • The gates' busy and interrupted sessions: covered by the offline suite, not reproduced here.
  • pnpm test:imap locally: CI's imap-live passed at 7e5fbfb, and is pending at 1a4a96c.
  • A real company mailbox: none available, as in the PR.

Notes

  • test (22) failed at 7e5fbfb, and 1a4a96c fixes it. The failure was this PR's own Text.test.ts, on the required check, not a flake.
    • Node 22.22.0, the repo's minimum and CI's pin, decodes latin1, iso-8859-1 and windows-1252 as ISO-8859-1, so 0x93 reads as U+0093.
    • I reproduced the failure locally on 22.22.0. At 1a4a96c all 94 IMAP read tests pass on Node 22.22.0 and Node 26.
    • Live at 1a4a96c, windows-1252, iso-8859-1, no charset over 8-bit bytes, us-ascii over 8-bit bytes, UTF-8 and HTML &#147;…&#148; &#128; all read correctly, for example “Quoted” € 5 – dash café.
    • CI on 1a4a96c was still running when I posted.
  • The skill's per-message too_large line misleads. patchy-imap says "A message past 1 MiB answers { error: "too_large" } alone". But the bound is on the encoded answer (summary, text of at most 256 KiB, and parts), not the message's size: a 1.9 MB message with an attachment read normally. That's the better behaviour, but an importer author would expect big-attachment mail to fail. Suggest "a message whose answer passes 1 MiB".
  • A cursor must come back with its call's starting arguments. My first importer resumed with after and then followed { folder, cursor }, and its second page failed invalid_cursor. The skill and the error say so, and storing rows before the checkpoint meant the next run lost nothing. Still, the cursor already binds the call, so accepting it alone would remove a trap an importer is likely to fall into.
  • Out-of-wire arguments get a generic refusal. 26 refs, an empty refs, a 300-character search value, a since that isn't a day and UID 0 all answer only "Runtime request refused: invalid_request.", without naming the argument or bound. It's the runtime's generic message, so a nit.

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]>
Base automatically changed from feat/imap-connections to main November 7, 2026 12:53
allisonmahmood and others added 16 commits November 7, 2026 13:53
The pure half of IMAP reads (#1252), offline-tested and not yet wired:

- body structures as parts, numbered as IMAP sections, with nested
  message/rfc822 parts, bounded at depth 10 and 500 nodes;
- body text selection through alternative, mixed, related and signed,
  with attached files and forwarded messages never the body, and S/MIME
  and PGP reported as encrypted;
- text cleaning: HTML to inert text, invisible and bidi characters
  stripped, transfer and charset decoding of a partial fetch, and a cut
  at 256 KiB on a character boundary;
- scan, list and search planners over injected UID-window commands,
  with the since lower bound, a per-call scan budget and no n:* range;
- cursors and checkpoints bound to the call and the folder's
  UIDVALIDITY;
- getMessages refs checked before upstream, and answers held to the row
  and result bounds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`uidSet` compacts the UIDs a page fetches into ascending runs such as
3:5,9, never `*`, for the wiring's `UID FETCH`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The second pure part of IMAP reads (#1252):

- summaries from ImapFlow's fetch: addresses as { name, address }
  bounded in count and bytes, the subject cleaned, dates as ISO, flags,
  Message-IDs, and References read from a bounded header, so a page of
  the most hostile summaries still fits the result bound;
- a mixed body reads on through every later inline text part, joined
  by a blank line, with one raw-fetch budget across the parts;
- a message for getMessages: the summary, replyTo, text, truncated,
  parts and its encryption, and answerGetMessages answers whole
  messages;
- with no charset, or one the runtime doesn't know, text reads as
  UTF-8, else latin1.

Invisible characters in the sources are now written as braced escapes:
the formatter rewrites a \uXXXX escape of a bidi or format character
into the character itself, which had left literal bidi overrides in
the earlier commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Wires the IMAP read planners into the runtime: the wire schemas and
error codes, the limits, a session pool with its gates, the six
operations as tier 2 integration handlers, the dev door, the generated
client and the guest's alias plumbing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The scripted IMAP server now holds folders of mail and answers EXAMINE,
STATUS, UID SEARCH (RETURN (MIN) with ESEARCH), FETCH and UID FETCH,
logs every command line, and can change the mailbox, wait or drop the
connection between commands. The reads' tests over it cover the exact
commands sent (never a write or a non-peek fetch), refusals before
upstream, mailbox_reset, a reused cursor, since with and without
ESEARCH, an expunge mid-scan, the pool, a dropped session's one retry,
the login pause, the caller's recheck, the byte budget, interruption
and busy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The generated client reads a scripted mailbox through the callback
gateway, and a tier 2 action in workerd imports a date window through
ctx.connections. A sentinel in a subject, a body, an address and a
search value never reaches runtime_calls, a log line or a wide event,
and nor does the password. The gateway runs IMAP only in actions,
read-only ones included, and caps its arguments; generation holds the
patchy client's types to the wire; a literal past the parser's bound
destroys its session.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A mail client seeds each folder; every read leaves every message unseen.
Both servers: folders, status, a since scan in pages with its checkpoint,
newest first, search, a 25-ref read with a not_found, since with no
matches, an expunge mid-scan, a search across UID gaps, and
mailbox_reset after a folder is deleted and recreated.

folderStatus now opens the folder first: Dovecot answers STATUS of a
folder the session had open from that view, so a recreated folder kept
its old UIDVALIDITY there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each live read's answer is decoded by its operation's output schema,
so the test types what a patch receives and checks it fits.

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

The patchy-imap skill now carries the six reads, refs and mailbox_reset,
the page cursor against the stored checkpoint, the import window and
its throughput facts, the read-only promise and mail as untrusted data.
The product's Email (IMAP) section gains Reading Email (IMAP); the API
docs, limits, glossary, ADR-0004, ADR-0013, patchy-loop, patchy-server,
sdkCapabilities and every integration summary name IMAP's reads.

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

Invoice inbox, a tier 2 patch over imap/invoices, lists the folders,
reads INBOX since a day page by page, searches it and reads the first
match's text and parts, in read-only actions its agent tools also
offer. A day in the patchy client is now a plain string the wire
checks, so a patch passes t.text() arguments without a cast.

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

It overrides every integration's argument bound to make a small body
too large; runtime.imap.bytes joins them, so the batch bound stays the
largest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…, and gates admit in order

A call now owns its session from the moment it's logged in or taken from the
pool: the try runs masked, only the login and the call's own work run under
restore, and the session's one exit decides whether it goes back to the pool
or is closed. An interrupt between the login and the call's first command no
longer leaves a logged-in session open until the server drops it.

The gates were Semaphores waited on by taking and giving back a permit, then
racing to take it again, so a waiter could lose a free permit to a call that
had just arrived and answer busy. They 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.

The scripted server counts sessions logged in and still open, for the tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… logged, not swallowed

The pause write after a refused login was ignored on failure, so the connection
stayed unpaused with no trace. It's now tried once more; a failure that remains
is logged at error level and marks the wide event `imapPauseFailed`. The caller
still hears auth_failed, and the next call may log in once more and pause it
then.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lowing the cursor

Without ESEARCH, the walk to the first message since a day stops at its share
of windows or time like any page, so it can answer an empty page with a cursor
that isn't done. The skill and the product doc said only that nothing since the
day answers an empty done page; they now say both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
getMessages groups messages whose text fetch is the same into one UID FETCH.
ImapFlow bounds each untagged response on its own and resets its count when
one completes, and every message comes back as its own FETCH response, so
the group never adds up against the parser's bounds. The test reads 25
messages of 1,000,000 bytes each through that one fetch, within the call's
32 MiB.

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

Node 22.22's TextDecoder reads bytes 0x80 to 0x9F as C1 controls for every
label WHATWG maps to windows-1252 (`latin1`, `iso-8859-1`, `us-ascii`,
`windows-1252` and the rest), where Node 24, Node 26 and Bun read curly quotes,
the euro sign and the rest. A message without a valid charset, or one that
declares any of those labels, read differently by runtime.

Patchy now decodes windows-1252 itself: each byte its own code point, and 0x80
to 0x9F by the table HTML character references already used, which moves to
its own module. A declared label whose decoder reports windows-1252 goes the
same way. The other labels' decoders agree across runtimes apart from a few
bytes of Node 22's older ICU tables.

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

The skill and the docs said a message past 1 MiB answers too_large. The bound
is on what Patchy returns for the message, its summary, text and parts list,
encoded; attachments' bytes are never returned, so mail with a large attachment
reads normally. The skill's size line, its too_large summary, the product doc
and the wire's description now say so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood merged commit 8a28a83 into main Nov 7, 2026
26 checks passed
@allisonmahmood
allisonmahmood deleted the feat/imap-reads branch November 7, 2026 13:07
allisonmahmood added a commit that referenced this pull request Nov 7, 2026
…1264)

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 |

```console
$ 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](https://github.com/user-attachments/assets/415cdb5b-5ce2-46a7-b063-7ee7b29e0716)

### 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](https://github.com/user-attachments/assets/5d3a0ce6-f2eb-42b3-858c-b69cbf4887e0)

### 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 #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 #1262 ship in one release, and this PR is
`one-way`; see below. #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.

- [x] **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
#1262 without this PR. Rolling back past #1264 to a release that has
#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 #1204 and #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.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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]>
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:server Touches the server area area:ui Portal and first-party browser pages, shared rendering and styles 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 read IMAP folders and messages

1 participant