Repository navigation
feat(integrations): patches read IMAP folders and messages - #1262
Conversation
60cf6c4 to
d05caa3
Compare
Acceptance: PASS with notesChecked I checked the whole Email (IMAP) stack end to end at its top, What the rebase moved. Setup
Done means
The pause across the stack: passed.
Recent calls: passed.
Golden journeys
Rollback answers: they match the diff.
Not run
Notes
Earlier verdict at
|
…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:  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 connected page shows the server and username, the folder count and first folders, and recent calls:  **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:   <details><summary>The way out: the shared Replace password page, then the resumed connection</summary>   </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:  - 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]>
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]>
d05caa3 to
c64cb29
Compare
…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:  ### 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.  ### 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]>
…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]>



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 devreads the real mailbox the same way, and admins see every call in the connection's recent calls.How it works:
imapclient has six typed reads:listFolders,folderStatus,scanMessages,listMessages,searchMessagesandgetMessages, 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 newpatchy-imapskill.busywith 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.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 failsmailbox_reset.auth_faileduntil an admin's Test or Replace password succeeds.docs/limits.md.pnpm dev up imapnow publishes aninvoice-inboxpatch 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 devThe scenario patch's agent tools, called through
patchy devagainst the scenario's mail server. Trimmed.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.
Nothing on the server changed
FLAGS read from the scenario's mail server after every read above:
\Recent\Recent\Seen \RecentMessage 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": falsefor 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.
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
n:*;sincewith and without ESEARCH, and an expunge mid-scan;pnpm test:imap, theIMAP liveworkflow's suite, passes 15 tests on Dovecot (TLS and STARTTLS) and GreenMail. The reads' tests check\Seenunchanged after every read on a non-ASCII folder, a 25-ref page ending in anot_found,sincewith no matches answering an emptydonepage, an expunge mid-scan, search paging across 1,090 deleted UIDs, and a UIDVALIDITY reset answeringmailbox_reset.latin1,iso-8859-1,us-asciiand the other labels WHATWG maps there.0afc4f2decodes 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:cli,cliPublish,cliLifecycle,cliLook,cliLogs,cliRepo), where a strayGET /from the editor's port probes on this machine reaches the stub;install.test.tsandcli-smoke, which find anodewith no npm beside it on this machine;LocalTaskProviderflake;Supervisorflake ("does not reap active calls as idle…"), which fails the same way with this PR's one change in that path reverted.Review
Grok 4.7 reviewed
feat/imap-readsat0c7ef0f. Each finding was checked against the code:Sessions.ts)e3795d2. The path Grok named was covered, becauseonErrorruns on interruption. Three nearby windows weren't: insideopenafter the login, betweenopenreturning 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.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.f1db477. The write is retried once. A failure that remains is logged at error level, and the wide event getsimapPauseFailed: true. The caller still getsauth_failed.sinceline is wrong without ESEARCH498a075. The skill anddocs/product.mdnow say an empty page that isn'tdonemeans keep followingcursor. The code already behaved this way.maxResponseSizebounds one assembled untagged response and resets when that response completes. Each message of a multi-UID FETCH comes back as its own* n FETCHresponse, 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.c722fbcadds a test that reads 25 bodies of 1,000,000 bytes through one FETCH.Release impact
Tick exactly one.
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
attachmentflag and redefineshasAttachmentsto match it, and an importer written against #1264 silently skips every attachment on a release that has this PR alone.feat/imap-connectionsalone, a published patch whose actions call these reads stays up and keeps serving. Each read failsaccess_denied("The handler kind cannot use this callback operation."), and its page shows whatever the action does with that refusal.patchy refreshonto 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.Built by Claude Opus 5.5 in Claude Code, reviewed by Grok 4.7.