Преглед на файлове

docs: ctx.* protocol surface design (mail, ftp/sftp, pop3, webdav)

Four independent design passes, each given a different lane and not shown
the others' work: the JS-facing surface, the libcurl host integration,
security and tenancy, and IMAP/SMTP semantics. Assembled unedited behind a
cover review.

DESIGN ONLY - nothing is approved and no code exists. Recorded now because
three of its findings are actionable today and one is about shipped code.

Three corrections to the agents' conclusions, in the cover:

- The ~2 s HTTP wall budget they reasoned from is the DEFAULT, not this
  host: prod runs 15000 ms for HTTP and 60000 for jobs, read from the
  runner's own /health. So "interactive mail is impossible" is not
  supported and the budget design needs re-deriving. The underlying point
  survives: a blocking call cannot be interrupted, and anything unbounded
  belongs in a job.
- ctx.env exposing stored secrets was reported as a gap in what exists. It
  is the documented purpose of ctx.env; the admin-API rule that no GET
  returns a value is a different rule. The forward-looking half survives:
  a mail password must be nameable without being readable.
- The wildcard finding IS real and verified in src/apikey.cpp: pattern "*"
  is a zero-length prefix match, so it matches the reserved _files too.
  An intent mismatch today, but it must be fixed before anything builds
  _conn: entries on the same machinery, where it would be an escalation.

Five decisions are left to the product owner rather than decided here,
including one that contradicts the instruction given: the curl lane
recommends linking Debian's libcurl rather than vendoring it, because SFTP
drags in libssh2 and vendoring makes us CVE owner for two upstreams.

Also records the three claims most likely to be wrong, all answerable with
the fake-IMAP harness written during the database export work, and all of
which should be answered before the spec is accepted.
fszontagh преди 1 месец
родител
ревизия
932e40321d
променени са 1 файла, в които са добавени 4351 реда и са изтрити 0 реда
  1. 4351 0
      docs/superpowers/specs/2026-10-08-ctx-protocols-design.md

+ 4351 - 0
docs/superpowers/specs/2026-10-08-ctx-protocols-design.md

@@ -0,0 +1,4351 @@
+# ctx.* protocol surface - design
+
+**Status: DESIGN, not approved. No code has been written.** Mail (`ctx.mail`)
+is the first consumer need; the surface is meant to generalise to FTP, FTPS,
+SFTP, POP3 and possibly WebDAV, because the product goal is that tenant
+JavaScript stays SMALL.
+
+## Provenance, and how much to trust each part
+
+Four independent design passes, each given a different lane and deliberately
+NOT shown the others' work, so where they agree that agreement means
+something. Their documents follow unedited as Parts 1-4. I have reviewed the
+decisions, not every line - where I have checked a claim against the code or
+against production, I say so below. Treat the parts as argued proposals, not
+as settled fact.
+
+## Corrections I have already applied to their conclusions
+
+**The wall-budget premise is wrong for production, and it changes a product
+answer.** Part 4 concludes that mail "almost certainly does not fit the ~2 s
+HTTP wall budget" and therefore belongs only in job runs. 2000 ms is the
+DEFAULT ceiling; prod is configured at **15000 ms for HTTP runs** and 60000
+for jobs (read from the runner's own `/health` during the 0.8.1 window). TLS
+plus AUTH at 200-500 ms is a small fraction of 15 s, so an interactive mail
+listing is probably viable on this host. The underlying point still stands -
+a blocking call cannot be interrupted by the JS interrupt handler, mail is
+the slowest thing we would ever call, and anything unbounded belongs in a
+job - but "interactive mail is impossible" is not supported. Re-derive the
+budget design against 15 s, and against the per-host setting rather than the
+default.
+
+**`ctx.env` exposing stored secrets is not a defect.** Part 3 reports that
+`functionEnvFor()` exports every stored secret into `ctx.env`, framed as a
+gap in what exists. Verified: it does, and that is the documented PURPOSE of
+`ctx.env` - secrets exist so functions can read them, and "no GET ever
+returns a value" is a rule about the admin HTTP API. The forward-looking half
+is real and survives: a mail PASSWORD must be nameable without being
+readable, which is a new requirement rather than a fix.
+
+**The `*` wildcard finding is real and is already queued.** Verified in
+`src/apikey.cpp:39-43`: a trailing-`*` pattern is a prefix match, and for the
+pattern `*` the prefix is zero-length, so `*` matches everything including
+the reserved `_files`. Today that is an intent mismatch rather than a
+vulnerability. It MUST be fixed before any `_conn:` scheme is built on the
+same machinery, because there a `*` rule silently granting every mail account
+would be a genuine escalation - sending mail as a tenant's owner is not the
+same class of act as reading a collection.
+
+## Decisions that need the product owner, not me
+
+1. **Vendor libcurl, or link Debian's?** The instruction was to vendor from
+   curl's git at the latest stable. Part 2 recommends AGAINST it and the
+   argument deserves a hearing: SFTP pulls in libssh2, so vendoring makes us
+   the CVE owner for two upstreams, and a statically linked curl is invisible
+   to `apt` on a customer box. It proposes keeping the vendored pin behind a
+   flag, default off, and gates the whole decision on one measurement -
+   whether trixie's libcurl ships `sftp`. If it does not, vendoring is the
+   only option and the argument is moot.
+2. **A separate `netd` helper process, or in-process?** Part 3 recommends a
+   separate process from v1, mainly because only its own systemd unit can
+   carry kernel-enforced `IPAddressDeny`, and because a hung protocol call
+   becomes killable instead of pinning a pooled runtime. That is a bigger
+   change than "add a capability".
+3. **POP3: ship it or not?** Part 4 recommends not shipping it at all - it is
+   the only path where a local MIME parser becomes unavoidable, and its id
+   model does not fit.
+4. **WebDAV.** If curl is built with HTTP disabled (Part 2's proposal, for
+   attack surface), WebDAV is out of the first slice. Note CalDAV/CardDAV
+   already work today through `ctx.fetch`, verified on the wire, so nothing
+   is lost by deferring.
+5. **Effort.** Part 2 sizes the IMAP response parser alone at 2.5-3 weeks
+   plus a long tail, and argues it should be its own slice before any JS
+   surface exists. That is the number to accept or reject before anything
+   starts.
+
+## Where the four agreed without conferring
+
+- Named connections defined by an admin, with the tenant naming a connection
+  rather than a host. Parts 1 and 3 arrived at this separately; it removes by
+  construction most of what an SSRF guard exists to do.
+- The product owner's switchable-PEEK requirement generalises to a
+  three-level resolution (builtin safe default <- connection <- per-call,
+  `undefined` means inherit), reusing the `resolveEmbedding()` pattern.
+  Options are named POSITIVELY - never `notMarkRead`.
+- Bytes never pass through the JS heap; a call returns a reference.
+- An unsupported option is refused BY NAME. Part 1 proposes a test asserting
+  the prelude's option list equals its payload key list, because that
+  inequality is exactly how `embedTimeoutMs` was silently dropped for a
+  release.
+- Idempotent send via a caller key stored as a DOCUMENT ID, so a repeat is an
+  atomic duplicate-id conflict rather than a read-then-write race.
+
+## The three things most likely to be wrong
+
+Part 4 flags these against Part 2's lane, and they are unresolved:
+1. Whether curl handles a synchronizing-literal continuation inside a
+   `CUSTOMREQUEST`. This gates non-ASCII IMAP SEARCH.
+2. Whether curl reliably delivers untagged SELECT response codes to the write
+   callback. This gates the per-command UIDVALIDITY check, which is the whole
+   basis of the id-staleness guarantee.
+3. The budget question above, now re-opened by the 15 s correction.
+
+All three are answerable with the fake-IMAP-server harness already written
+during the database export work, and should be answered BEFORE the spec is
+accepted rather than during implementation.
+
+---
+
+
+# Part 1
+
+# Spec part 1 - the JS-facing protocol surface (IMAP/SMTP/POP3/FTP/FTPS/SFTP/DAV)
+
+Design only. Nothing here is implemented. Written against the conventions in
+`runner/src/host_prelude.js`, `runner/src/host_context.cpp`, `api/llms.txt` and
+the "Function runtime" section of `CLAUDE.md`.
+
+The transport is libcurl. Abortability of an in-flight transfer (progress
+callback) is another agent's design; this document assumes every host call made
+here is abortable and bounded, and specifies only what the author sees.
+
+---
+
+## 0. What problem the surface solves, and the one test it must pass
+
+The stated goal is **small tenant JavaScript**. That is the acceptance test for
+every choice below: if a reasonable consumer task cannot be written in a handful
+of lines, the surface failed, regardless of how clean it looks from the host
+side.
+
+The reference task (the first consumer need) is:
+
+```js
+// read unseen invoices from a mailbox, store each attachment, mark handled
+const box = ctx.mail.connect({ url: 'imaps://mail.example.com', user: ctx.env.MAIL_USER,
+                               pass: ctx.env.MAIL_PASS, markSeen: false });
+const page = box.search({ folder: 'INBOX', unseen: true, since: '2026-10-01', limit: 50 });
+for (const m of page.items) {
+  const msg = box.fetch(m.uid, { parts: 'headers+text' });
+  for (const att of msg.attachments) {
+    box.fetchPart(m.uid, att.partId, { to: { file: 'inv/' + m.uid + '-' + att.filename } });
+  }
+  box.flag(m.uid, { add: ['\\Seen'] });
+  box.move(m.uid, 'Processed');
+}
+```
+
+Everything in this document exists to make that read the way it reads above.
+
+---
+
+## 1. One generic surface, or several named ones?
+
+### Recommendation: SEVERAL named surfaces over ONE shared kernel
+
+Ship three author-facing namespaces:
+
+| namespace | schemes | shape |
+|---|---|---|
+| `ctx.mail` | `imap`, `imaps`, `pop3`, `pop3s` (read) and `smtp`, `smtps` (send) | mailbox session + sender |
+| `ctx.ftp` | `ftp`, `ftps`, `sftp` | remote-filesystem session |
+| `ctx.dav` | `http(s)` + WebDAV/CalDAV/CardDAV verbs | collection/resource session (phase 2, see §9) |
+
+They share **one host kernel**: one connection descriptor, one option-resolution
+rule (§4), one timeout rule (§5), one source/sink model for bytes (§6), one
+cursor model (§7), one error-slug family (§8). The namespaces differ only in the
+verbs they expose and the per-protocol options they accept.
+
+### Why not one generic surface
+
+A single `ctx.protocol('imaps://...')` / `ctx.transfer(...)` with a scheme
+argument is cheaper for us and strictly worse for the stated goal. Mail is not a
+file transfer with a different scheme:
+
+- IMAP's unit of work is a **message with a part tree**, addressed by a UID that
+  is only meaningful within a folder and a `UIDVALIDITY`. A generic `get(path)`
+  would make the author build `FETCH 123 (BODY.PEEK[2.1])` strings - protocol
+  knowledge pushed straight back into tenant JS, which is the thing we are
+  trying to delete.
+- IMAP search is a server-side expression language; FTP has no search at all.
+- `flag`, `move`, `folders`, `append` have no FTP analogue; `mkdir`, `rename`,
+  `chmod` have no IMAP analogue. A union surface would be mostly
+  "unsupported for this scheme" refusals at runtime - and since this project
+  refuses unsupported options **by name**, a union surface converts a
+  compile-time-obvious mistake into a runtime 422.
+- The one honest generic surface is "give me a curl handle", and that is an
+  SSRF and credential-handling liability with no size benefit.
+
+### Why not one namespace per protocol (`ctx.imap`, `ctx.pop3`, `ctx.smtp`)
+
+Rejected for mail specifically. POP3 is a strict subset of what the mailbox
+session already does (list, fetch, delete, no folders, no flags, no search);
+giving it its own namespace would make a consumer migrating a mailbox from POP3
+to IMAP rewrite working code. Instead the scheme is in the connection URL and
+the session reports what it can do:
+
+```js
+box.capabilities  // { folders:false, flags:false, search:false, move:false, append:false, idle:false }
+```
+
+A verb the connection cannot support throws `protocol_unsupported` **422**,
+naming the verb and the scheme. That refusal is a one-time integration error,
+not something that can appear in production on a connection that worked
+yesterday - and the author can branch on `box.capabilities` to avoid it.
+
+`ctx.ftp` likewise covers FTP/FTPS/SFTP in one namespace: the verb set is
+genuinely the same, only `ftps`'s TLS mode and SFTP's key auth differ, and both
+are connection-time options.
+
+### Rejected alternative worth recording
+
+`ctx.mail` as a **thick** surface that also parses MIME, decodes
+quoted-printable, normalises `Date:` headers and classifies attachments. Mostly
+accepted (see §3.1: part trees and decoded headers come from the host, because
+a MIME parser in tenant JS is both large and a correctness hazard), but with a
+line drawn: the host does **not** do HTML-to-text conversion, charset
+transliteration beyond UTF-8 decoding, or spam scoring. Those are opinions, and
+an opinion baked into the SDK cannot be overridden by the tenant.
+
+---
+
+## 2. Connections
+
+### Recommendation: an explicit handle the function opens, uses and closes
+
+```js
+const box  = ctx.mail.connect(descriptor);   // IMAP/POP3 session
+const out  = ctx.mail.sender(descriptor);    // SMTP session
+const site = ctx.ftp.connect(descriptor);    // FTP/FTPS/SFTP session
+```
+
+The handle is a plain object of methods, built in `host_prelude.js` exactly as
+`ctx.collections(name)` builds a ref: the prelude validates argument SHAPE and
+accumulates connection defaults, the host owns the socket and every decision.
+The handle carries an opaque host-side session id; it is **not** transferable,
+serialisable, or usable after `.close()`.
+
+Lifetime:
+
+- `connect()` does **not** necessarily open a socket. It validates the
+  descriptor (including the egress guard on the host, §8) and returns a handle;
+  the connection is established lazily on the first verb. Rationale: a function
+  that opens a mailbox and then takes an early `return` on an empty payload
+  should not pay a TLS handshake, and `connect()` failing for a network reason
+  at a line that looks like configuration is confusing.
+- Every verb on a handle reuses the established connection. This is the main
+  reason for a handle at all: an IMAP TLS handshake plus `LOGIN` plus
+  `SELECT` is hundreds of milliseconds, and the reference task in §0 makes
+  ~150 calls. Per-call connections would blow the HTTP wall budget (~2 s) on
+  handshakes alone.
+- `handle.close()` is available and advisory. The host closes every open
+  session when the run ends, success or failure - a function cannot leak a
+  socket by forgetting, and must not be able to hold one past its lease.
+- Handles do **not** survive a run. No cross-run connection pooling in this
+  phase: pooled authenticated mail sessions keyed by tenant credentials is a
+  cross-tenant-leak surface, and the win is small next to a job run's wall
+  budget. Noted as a possible later optimisation, deliberately out of scope.
+- A run may hold at most `kMaxSessionsPerRun` handles (proposed **4**), and at
+  most 1 per distinct descriptor is reused automatically if the same descriptor
+  is connected twice. Exceeding it is `too_many_sessions` **422**. Reason: each
+  session is a socket and a buffer held for the whole run; unbounded is a
+  denial-of-service on the runner's own file descriptors.
+
+### The descriptor
+
+```js
+{
+  url:      'imaps://mail.example.com:993',  // required; scheme decides the protocol
+  user:     ctx.env.MAIL_USER,               // optional
+  pass:     ctx.env.MAIL_PASS,               // optional
+  // sftp only
+  privateKey: ctx.env.SFTP_KEY,              // PEM text, or { base64: '...' }
+  passphrase: ctx.env.SFTP_KEY_PASS,
+  knownHostKey: 'ssh-ed25519 AAAA...',       // see §8, host-key policy
+  // TLS
+  tls:      'require',                       // 'require' (default) | 'implicit' | 'none'
+  caBundle: { file: 'ca/corp.pem' },         // optional, from the project file store
+  // connection-time defaults for per-call options (§4)
+  markSeen: false,
+  passive:  true,
+  overwrite: false,
+  timeoutMs: 15000
+}
+```
+
+Notes and deliberate choices:
+
+- **One `url`, not host/port/scheme fields.** It is what a consumer already has
+  in their existing config, it is what libcurl takes, and it leaves exactly one
+  place for the egress guard to look. Port is optional and defaults per scheme.
+- **Credentials are arguments, not stored connection profiles.** They come from
+  `ctx.env` (project secrets, already the project's secret channel). A named
+  server-side connection profile (`ctx.mail.connect('mailbox-main')`) is
+  attractive - it keeps credentials out of the run entirely and lets an admin
+  rotate them - but it is a new management surface (routes, UI, policy) and
+  belongs in its own spec. **Unsure / deferred**, and I recommend the descriptor
+  shape above be designed so a profile can later be accepted in its place:
+  `connect('name')` with a string argument is reserved for that.
+- `tls: 'none'` is permitted (plaintext `ftp://` to an internal appliance is a
+  real case) but it is a per-call explicit act, never a default, and
+  `function_egress_allow_private` still governs whether the destination is
+  reachable at all.
+
+### Rejected: implicit, per-call connections
+
+`ctx.mail.search({ url, user, pass, ... })` on every call. Rejected: it makes
+the handshake cost invisible and per-call, it repeats credentials at every call
+site (so a credential rotation is an N-line edit in tenant code), and it leaves
+nowhere to put connection-time option defaults, which §5 of the brief requires.
+
+---
+
+## 3. Operations
+
+Conventions shared by all of them:
+
+- Calls are **synchronous** host calls returning values, like every existing
+  `ctx.*` call. `await` on a non-promise is a no-op, so the documented examples
+  may use `await` and consumers' habits survive.
+- Every method takes an options object as its last argument. **Every unknown
+  option key is refused by name**, with the list of accepted names in the
+  message, exactly as `writeOptions()` and `ctx.jobs.enqueue()` do today. This
+  is not negotiable in this project: the `embedTimeoutMs` incident (accepted,
+  silently dropped, a consumer told a bound was in force that was not) is the
+  precedent.
+- Every method accepts `timeoutMs` (§5).
+- Bytes never cross the boundary implicitly (§6).
+
+### 3.1 `ctx.mail` - mailbox session (IMAP, POP3)
+
+```js
+box.folders()                       -> [{ name, delimiter, flags:[], messages, unseen }]
+box.select(folder)                  -> { folder, messages, unseen, uidValidity, uidNext }
+box.list(options)                   -> Page (§7) of MessageSummary
+box.search(options)                 -> Page (§7) of MessageSummary
+box.fetch(uid, options)             -> Message
+box.fetchPart(uid, partId, options) -> Transfer (§6)
+box.raw(uid, options)               -> Transfer (§6)   // the whole RFC822 source
+box.flag(uid, { add:[], remove:[] })-> { uid, flags:[] }
+box.move(uid, folder)               -> { uid, folder, uid2 }   // uid2: new UID, if the server reports it
+box.copy(uid, folder)               -> { uid, folder, uid2 }
+box.delete(uid, options)            -> { uid, deleted }        // { expunge: false } default
+box.append(folder, message, options)-> { uid, folder }
+box.capabilities                    -> { folders, flags, search, move, append, idle }
+box.close()                         -> undefined
+```
+
+`MessageSummary` (what a listing returns - cheap, no body):
+
+```js
+{ uid: 1234, folder: 'INBOX', messageId: '<...>', subject, from: {name, address},
+  to: [{name, address}], cc: [], date: 1760000000000,   // epoch ms, UTC, like everything else
+  flags: ['\\Seen'], size: 84213, hasAttachments: true, snippet: 'first 200 chars of text' }
+```
+
+`Message` (what `fetch` returns) adds `headers` (an object; repeated headers
+become arrays), `text`, `html` and `attachments`:
+
+```js
+attachments: [{ partId: '2.1', filename: 'invoice.pdf', contentType: 'application/pdf',
+                size: 820144, contentId: null, inline: false }]
+```
+
+Note what is **absent**: attachment *bytes*. An attachment is described in the
+listing and retrieved with `fetchPart` into a sink (§6). `fetch` options select
+how much comes inline:
+
+- `parts: 'summary' | 'headers' | 'headers+text' | 'full'` (default
+  `'headers+text'`). `'full'` still does not inline attachment bytes; it means
+  all text/* parts plus the full part tree.
+- `maxInlineBytes` (default 256 KiB, hard ceiling 1 MiB - the same ceiling
+  `ctx.files.get()` already enforces, and for the same reason: base64 inflation
+  against a 64 MiB heap). Text beyond it is truncated and the message carries
+  `textTruncated: true`. Truncation is **reported, never silent** - the
+  `scan_capped` precedent.
+
+`search` options are a declarative subset, translated by the host into IMAP
+SEARCH (and emulated by header scanning on POP3 only if `capabilities.search`
+is false - **no**, see below):
+
+```js
+{ folder: 'INBOX', unseen: true, seen: false, flagged: true, answered: false,
+  from: 'billing@', to: '', subject: '', bodyContains: '',
+  since: '2026-10-01', before: '2026-11-01',   // date-only strings, or epoch ms
+  largerThan: 0, smallerThan: 0,
+  headers: { 'X-Tenant': 'acme' },
+  uidRange: '1200:*',
+  limit: 50, cursor: null, order: 'uid' | '-uid' | 'date' | '-date',
+  markSeen: false, timeoutMs: 15000 }
+```
+
+Decision: on POP3, `search` throws `protocol_unsupported` rather than being
+emulated by downloading every message and filtering. Emulation would turn a
+one-line call into an unbounded download that blows the wall budget, and it
+would make `search` mean something different depending on the scheme. POP3
+users call `list()` and filter in JS over summaries.
+
+`append(folder, message, options)` takes either a sink-style **source** (§6) for
+a pre-built RFC822 blob, or the same structured message object `send()` takes
+(§3.2) - the host builds the MIME. Structured is the expected path; nobody
+should be assembling MIME in tenant JS.
+
+### 3.2 `ctx.mail` - sender (SMTP)
+
+```js
+const out = ctx.mail.sender(descriptor);
+out.send(message, options) -> { messageId, accepted: ['a@b'], rejected: [], deduped: false }
+out.verify(options)        -> { ok: true }   // connect + EHLO + auth, send nothing
+out.close()
+```
+
+`message`:
+
+```js
+{ from: { name: 'Acme', address: 'billing@acme.example' },
+  to: ['a@b.example'], cc: [], bcc: [],
+  replyTo: null, subject: 'Invoice 42',
+  text: 'plain body', html: '<p>...</p>',
+  headers: { 'X-Tenant': 'acme' },
+  inReplyTo: '<...>', references: ['<...>'],
+  attachments: [ { filename: 'invoice.pdf', contentType: 'application/pdf',
+                   from: { file: 'inv/42.pdf' } },          // §6 source: the project file store
+                 { filename: 'note.txt', text: 'hello' },
+                 { filename: 'sig.png', base64: '...', inline: true, contentId: 'sig' } ] }
+```
+
+`options`: `{ idempotencyKey, timeoutMs, envelopeFrom, requireTls, dsn }`.
+
+**`idempotencyKey` is REQUIRED on `send()`.** Not defaulted, not optional.
+Job delivery is at-least-once and a reclaimed stale lease re-runs the function;
+an email sent twice is a visible customer-facing defect, and an author cannot be
+expected to remember a safety argument they did not read. Omitting it is
+`idempotency_key_required` **422** at the prelude, before any socket. The key is
+a non-empty string of at most 512 characters (the `dedupeKey` bound, reused on
+purpose). Scope of the dedupe record is `project + function_id + key`; a second
+send with a key already recorded returns the first result with
+`deduped: true` and sends nothing.
+
+How long the record is kept, and where it lives, is an implementation question
+for part 2 - but the surface commits to: it outlives the run, it is not
+best-effort within one process, and `deduped: true` is a normal success, never
+an error. Open question flagged in §9.
+
+`verify()` exists so a consumer can health-check credentials from a cron
+function without emitting mail - which is what people otherwise do by sending
+test messages to themselves.
+
+### 3.3 `ctx.ftp` - remote filesystem (FTP, FTPS, SFTP)
+
+```js
+site.list(path, options)       -> Page (§7) of Entry
+site.stat(path, options)       -> Entry | null            // null is an answer, like ctx.files.get
+site.get(path, options)        -> Transfer (§6)
+site.put(path, source, options)-> { path, size, overwritten: false }
+site.delete(path, options)     -> { path, deleted }
+site.mkdir(path, options)      -> { path, created }       // { parents: false } default
+site.rmdir(path, options)      -> { path, deleted }       // { recursive: false } default
+site.rename(from, to, options) -> { from, to }
+site.capabilities              -> { rename, mkdir, stat, append, resume, chmod, recursiveDelete }
+site.close()
+```
+
+`Entry`: `{ name, path, type: 'file'|'dir'|'link'|'other', size, modified, mode, target }`.
+`modified` is epoch ms or `null` - FTP `LIST` output frequently has no year and
+the host must not invent one. `mode` is `null` on plain FTP.
+
+Per-call options worth naming: `get` takes `to` (sink), `offset`, `maxBytes`;
+`put` takes `overwrite` (default **false**), `append`, `mkdirParents` (default
+false), `mode`; `list` takes `limit`, `cursor`, `pattern`, `details` (false ->
+names only, which is cheap on servers that support `NLST`).
+
+Path rule: paths are interpreted by the remote server, and the host passes them
+through **after** rejecting NUL bytes, CR and LF (command injection into
+FTP's line protocol) and refusing a path that is not a single logical path. A
+`..` segment is **not** refused here - unlike `/fn/{project}/*`, where `..` is
+hostile input against our own routing. A remote server's namespace is the
+tenant's own and `../outgoing` is a legitimate relative path. This asymmetry is
+deliberate and should be stated in `llms.txt`, because it looks like an
+inconsistency otherwise.
+
+`chmod` is listed in `capabilities` but **not** in the verb table above: I am
+not convinced it earns surface area in phase 1. Flagged as open.
+
+### 3.4 `ctx.dav` - WebDAV / CalDAV / CardDAV
+
+Deferred to phase 2, surface sketched so phase 1 does not paint it into a
+corner:
+
+```js
+const dav = ctx.dav.connect(descriptor);
+dav.list(path, options)        -> Page of DavEntry        // PROPFIND depth 1
+dav.props(path, options)       -> { href, props: {} }     // PROPFIND depth 0
+dav.get(path, options)         -> Transfer (§6)
+dav.put(path, source, options) -> { href, etag }
+dav.delete(path, options)
+dav.mkcol(path, options)
+dav.move(from, to, options) / dav.copy(from, to, options)
+dav.lock(path, options) / dav.unlock(path, token)
+// CalDAV/CardDAV
+dav.report(path, query, options) -> Page of { href, etag, data }   // calendar-query / addressbook-query
+```
+
+Reasoning for deferring: DAV's value is in the *typed* layers (iCalendar and
+vCard parsing), and shipping `report()` that hands back raw iCalendar text is
+the "generic surface" mistake in a different costume - the tenant then needs an
+ICS parser in JS, which is exactly the code size we are trying to remove. Doing
+DAV properly means an iCalendar/vCard model in the host. That is a bigger
+commitment than mail and should be priced separately. If a consumer needs only
+file-like WebDAV (upload/download to a Nextcloud share), note that `ctx.ftp`'s
+verb set already fits and the cheapest honest move is to let `ctx.ftp.connect()`
+accept `dav(s)://` URLs for the file-like subset, with `capabilities.search`
+false. **Recommended**: do that, and keep `ctx.dav` for the calendar/contacts
+work.
+
+---
+
+## 4. "Safe default, settable at connection time, overridable per call"
+
+The product owner's requirement, verbatim: *"'not mark mail read' must be
+switchable, and must be configurable on connection time too, so consumer can
+safely overwrite it"*.
+
+### The general pattern: three-level resolution, last level wins
+
+Every option of this class resolves as:
+
+```
+builtin safe default  <-  connection descriptor  <-  per-call options
+```
+
+with **last stated wins**, and `undefined`/absent meaning "inherit", never
+"false". The resolution is a pure function on the host side (the project's
+`resolveEmbedding()` / `resolveWallBudget()` pattern), so precedence is
+unit-tested without a socket:
+
+```
+resolveTransferOptions(builtin, connection, call) -> effective
+```
+
+The handle exposes the resolved connection level for debugging:
+`box.defaults  // { markSeen: false, timeoutMs: 15000 }`.
+
+### The register of such options
+
+| option | surface | builtin default | why that default is the safe one |
+|---|---|---|---|
+| `markSeen` | mail read | **false** | reading a mailbox must not mutate it; a failed run that already marked 50 messages seen has destroyed the consumer's own backlog signal |
+| `expunge` | mail delete | **false** | `\Deleted` is reversible, expunge is not |
+| `overwrite` | ftp put, dav put | **false** | an overwrite destroys data the function did not create |
+| `parents` | mkdir | **false** | silently creating a tree hides a path typo |
+| `recursive` | rmdir | **false** | the single most dangerous verb in the set |
+| `passive` | ftp | **true** | active mode asks the server to dial back into the runner, which the egress model has no story for |
+| `tls` | all | **'require'** | plaintext credentials are opt-in, never inherited |
+| `followSymlinks` | sftp get/list | **false** | a symlink is a remote-controlled redirect |
+| `requireTls` | smtp | **true** | an opportunistic-STARTTLS downgrade is silent |
+
+Naming rule, explicitly: **options are named positively and default to the safe
+value.** `markSeen: false`, never `notMarkRead: true` or `peek: true`. A negated
+boolean default-true is unreadable at the call site (`notMarkRead: false` means
+mark it read) and this project has already decided that an option's meaning must
+be legible where it is written.
+
+### The one class of option this pattern does NOT cover
+
+**Timeouts, and anything else that protects the operator rather than the
+tenant's data, stay NARROWING ONLY.** This is the existing rule for per-project
+embedding timeouts (`min(project, global)`): a tenant override that could RAISE
+a bound would let one tenant hold a pooled runtime and a shared socket longer
+than the operator allowed. So:
+
+- `timeoutMs` at any level can only shorten (§5).
+- Egress policy (`function_egress_blocked_cidrs`, allow-private) is never
+  settable from JS at any level.
+- `tls: 'none'` is a tenant-data choice about the tenant's own server, so it IS
+  overridable - but a global setting may forbid `tls: 'none'` outright, and when
+  it does, the per-call override is refused by name with `tls_required` **403**,
+  not ignored. Refusal over silence, as everywhere.
+
+### Rejected alternative
+
+A single `safeMode: true/false` switch flipping all of these together. Rejected:
+it bundles unrelated decisions, so a consumer who needs `overwrite: true` gets
+`markSeen: true` as a side effect, and no one can tell from a call site what is
+in force. Also unversionable - adding a new option to the bundle changes the
+meaning of existing tenant code.
+
+---
+
+## 5. Timeouts
+
+Every method on every handle accepts `timeoutMs`, following `embedTimeoutMs`:
+
+- **Validated, not coerced.** A non-integer or non-positive value is
+  `validation` **422** naming the option. (The `embedTimeoutMs` precedent again:
+  "silently accepted and ignored" shipped for a release and is treated as a
+  serious defect.)
+- **Narrowing only**, resolved as
+  `min(call, connection, remaining wall budget, operator ceiling)`. It can ask
+  for less time than the run has; never more.
+- **Resolves in WHOLE SECONDS with a 1 second floor per phase**, because the
+  value is split between a connect phase and a transfer phase and handed to a
+  client that treats 0 as "no timeout". This is the existing
+  `resolveEmbedBudget()` arithmetic and it must be reused rather than
+  re-derived: available ms is rounded **up** to seconds, connect gets at most
+  **half** of it, each phase has a 1 second floor. **Consequence to document in
+  `llms.txt` rather than hide: with less than 2 s available the floors dominate
+  and a call can overrun its stated budget by up to 1 s.** A session that does
+  several round trips (SELECT then SEARCH then FETCH) applies the resolved
+  budget per host call, so a `timeoutMs` is a per-call bound, not a
+  per-session one.
+- Exceeding it is **504**, with a slug that distinguishes *your bound* from *the
+  run ran out*: `transfer_timeout` when the call's own `timeoutMs` was the
+  binding constraint, `deadline_exceeded` **503** when the run's wall budget
+  was. Different remedies, so different slugs - the `embedding_timeout` vs
+  budget distinction, applied here.
+- An unbounded transfer is impossible: with no `timeoutMs` anywhere, the
+  effective value is the remaining wall budget, which for an HTTP-kind run is
+  ~2 s. **Practical consequence, stated loudly in the docs: mail and FTP work
+  belongs in a `job` trigger.** A 50 MB SFTP download cannot fit an HTTP route's
+  ceiling and should not be attempted there.
+
+---
+
+## 6. Large payloads: sources and sinks, bytes never land in the heap
+
+A 64 MiB JS heap, a 1 MiB per-run file load cap, an 8 MB attachment and a 100 MB
+FTP file. The rule:
+
+> **Bytes move host-side between a source and a sink. A transfer returns a
+> reference and a size, not content. Inlining content is an explicit, capped
+> opt-in.**
+
+### Sink shapes (where downloaded bytes go)
+
+```js
+{ file: 'inv/42.pdf' }                 // the project file store, §6.1
+{ file: 'inv/42.pdf', overwrite: true }
+{ url: 'https://...', method: 'PUT', headers: {} }   // SSRF-guarded relay, §6.2
+{ inline: { maxBytes: 262144, as: 'text' | 'base64' } }   // explicit opt-in, hard cap 1 MiB
+{ discard: true }                      // "does it exist / how big is it", checksums only
+```
+
+### Source shapes (where uploaded bytes come from)
+
+```js
+{ file: 'inv/42.pdf' }    // the project file store
+{ text: '...' }           // short, UTF-8
+{ base64: '...' }         // short, validated in the prelude like every base64 today
+{ url: 'https://...' }    // SSRF-guarded fetch, streamed straight out
+```
+
+### `Transfer`, the return shape
+
+```js
+{ bytes: 8403221, contentType: 'application/pdf', sha256: '...',
+  to: { file: 'inv/42.pdf' },     // echoes the sink that was used
+  truncated: false,               // true only for an inline sink that hit its cap
+  body: null, bodyEncoding: null  // populated ONLY for an inline sink
+}
+```
+
+`truncated` is the `scan_capped` discipline: a short answer says it is short.
+
+### 6.1 Evaluating "stream to the project file store and return a reference"
+
+This is the right primary sink, with three consequences that must be designed,
+not discovered:
+
+1. **`ctx.files` is currently READ ONLY, deliberately** - "writing a tenant's
+   asset is a management act and the HTTP route requires project-manage". A
+   `{ file: ... }` sink breaks that invariant. Recommendation: do not widen
+   `ctx.files`. Instead, writing via a transfer sink requires a **separate
+   capability** on the function policy - a `write` op on the reserved `_files`
+   pseudo-collection, which `requireCapabilityCore` already evaluates. A
+   function with read-only `_files` access gets `forbidden` **403** on the sink
+   before any socket opens. This keeps the one-implementation rule
+   (`requireCapabilityCore` decides, nothing else) and leaves `ctx.files`
+   read-only as documented.
+2. **`max_file_bytes` is 2 MiB by default.** A 100 MB FTP file does not fit a
+   file-store sink under default settings, and must be **refused up front where
+   possible** (`stat()`/`SIZE` is usually available) and aborted mid-transfer
+   when the size was unknown, with `file_too_large` **422** - the existing slug.
+   A partial file must not be left behind: the host writes to a staging buffer
+   and publishes through `FileStore::put` (upload-first, then delete the
+   previous records - the existing semantics) only on complete success.
+   The database's own `storage.files.max_file_size_mb` (default 500) is the
+   outer wall.
+3. **The 1 MiB `kCtxFileMaxBytes` cap is about LOADING into a run, not storing.**
+   A transfer sink does not load, so it is bounded by `max_file_bytes`, not by
+   1 MiB. Two caps answering two different questions, which is already this
+   project's stated position - it just needs saying again here, because a reader
+   will otherwise assume the 1 MiB figure applies.
+
+So: a 100 MB file is **not** a file-store case under default settings. The
+honest answers for it are the `{ url }` relay sink (§6.2) or raising
+`max_file_bytes` as an operator decision. The surface should not pretend
+otherwise.
+
+### 6.2 The relay sink / source
+
+`{ url }` streams host-to-host without buffering the whole payload: FTP ->
+object storage, or a provider's pre-signed upload URL -> SMTP attachment. It
+goes through the **same** SSRF guard as `ctx.fetch`, with the same
+`set_hostname_addr_map` pinning (one resolution, one classification - re-resolving
+is the rebinding window). `egress_blocked` **403** on refusal.
+
+This is the only shape that makes a 100 MB transfer expressible from a function,
+and it is also the shape that makes a function a potential data-exfiltration
+pipe - which is already true of `ctx.fetch`, governed by the same policy, so it
+adds no new class of risk.
+
+### 6.3 Rejected alternatives
+
+- **Returning bytes with a large cap** (say 8 MiB base64). Rejected: 8 MB of
+  attachment is ~11 MB of base64 plus the JSON string plus the engine's copy,
+  against a 64 MiB heap shared with the tenant's own data. One message is
+  survivable; a loop over a page of 50 is an OOM, and an OOM poisons the runtime
+  and costs the pool a slot.
+- **A JS stream/iterator over chunks** (`for (const chunk of site.read(path))`).
+  Rejected: host calls here are synchronous and the engine's job queue belongs
+  to the runtime, not the context - a generator suspended mid-transfer across an
+  interrupt is exactly the state the poisoning rule exists to avoid. It also
+  pushes a retry/backpressure protocol into tenant JS, which is the code size we
+  are removing.
+- **A sink into a collection document.** Rejected for binary. A document is
+  JSON; bytes would be base64 inside a row, and the transport has a
+  `message_too_large` limit that a repeated PATCH can push a document past until
+  it can no longer be read back. Metadata about a transfer belongs in a
+  collection; the bytes do not.
+
+---
+
+## 7. Pagination and iteration
+
+One `Page` shape for every listing:
+
+```js
+{ items: [...], nextCursor: 'opaque-string' | null, complete: true,
+  truncated: false, scanned: 1200 }
+```
+
+- `limit` defaults to **50** on mail listings and **200** on FTP/DAV listings,
+  with a hard ceiling of **1000** per page. A larger `limit` is refused by name,
+  not clamped - clamping is the silent-drop failure this project treats as a
+  defect.
+- `nextCursor` is an **opaque host-side string**. For IMAP it encodes
+  `folder + uidValidity + last uid`, and a cursor presented after the folder's
+  `UIDVALIDITY` changed is refused `cursor_invalid` **409**, because silently
+  restarting would re-deliver messages the function already processed. For
+  FTP/DAV it encodes an offset into the host's single read of the directory
+  listing plus a listing fingerprint.
+- `complete: false` means the server has more; `truncated: true` means the
+  **host** stopped early (a directory with 200k entries, a scan cap). The two
+  are different facts and are reported separately, following
+  `VectorSearchResult::scanCapped` - "a filter that merely matches fewer rows
+  than `top_k` is correctly reported as complete rather than crying wolf".
+- A cursor does **not** outlive the run or the session handle. It is tied to the
+  handle; using one from a previous run is `cursor_invalid`. A function that must
+  walk a 200k-entry directory across runs paginates on its own durable state (a
+  stored `last_uid`, a stored path prefix) and enqueues the next job - which is
+  the existing pattern for long work, and keeps the host from holding a cursor's
+  server-side state between runs.
+- Convenience: `page.next()` on a page re-issues the same call with
+  `cursor: page.nextCursor`, returning `null` when `nextCursor` is null. Four
+  lines in the prelude, and it removes the most common five-line loop from every
+  tenant function. No auto-iterating `for await`: an unbounded implicit loop
+  inside a wall budget is a trap.
+
+FTP honesty note: FTP and SFTP have **no server-side pagination**. The host
+reads the whole directory listing (bounded by a host cap) and pages over it in
+memory. So `limit` on `ctx.ftp.list` bounds what crosses into the heap, not what
+the server does, and a genuinely enormous directory is `truncated: true`. Stated
+rather than implied, because a consumer will otherwise assume paging reduces
+server load.
+
+---
+
+## 8. Error model
+
+Everything throws an `ApiError`-shaped JS `Error` with `code` (slug), `status`
+and optional `details`, as `throwApiError` already does. Message text is never
+to be matched; slugs are the contract.
+
+### Shared across all protocol surfaces
+
+| slug | status | meaning |
+|---|---|---|
+| `validation` | 422 | an argument's shape, including an out-of-range `limit` |
+| `unknown_option` | 422 | **an option refused BY NAME**, with the accepted list in the message |
+| `unsupported_combination` | 422 | two options that cannot both be honoured (existing slug) |
+| `protocol_unsupported` | 422 | the verb is meaningless for this scheme (POP3 `search`, FTP `flag`) |
+| `egress_blocked` | 403 | the SSRF guard refused the destination (existing slug) |
+| `tls_required` | 403 | `tls:'none'`/`requireTls:false` forbidden by operator settings |
+| `connect_failed` | 503 | DNS, TCP or TLS handshake failure |
+| `auth_failed` | 401 | credentials rejected by the remote server |
+| `host_key_mismatch` | 403 | SFTP host key did not match `knownHostKey` |
+| `transfer_timeout` | 504 | the call's own `timeoutMs` was the binding bound |
+| `deadline_exceeded` | 503 | the run's wall budget ended it (existing slug) |
+| `transfer_failed` | 503 | the connection broke mid-transfer |
+| `remote_error` | 502 | the server answered, and refused; `details.serverCode` carries e.g. `550` or an IMAP `NO`/`BAD` |
+| `not_found` | 404 | no such folder / path / uid (existing slug) |
+| `already_exists` | 409 | a put/mkdir/rename refused because the target exists and `overwrite` is false |
+| `too_large` | 422 | the payload exceeds a cap; `file_too_large` when the cap was the file store's |
+| `too_many_sessions` | 422 | more than `kMaxSessionsPerRun` handles |
+| `session_closed` | 422 | a verb on a closed handle |
+| `cursor_invalid` | 409 | a stale page cursor (UIDVALIDITY changed, listing changed, wrong run) |
+| `forbidden` | 403 | the function policy denies the capability (e.g. `_files` write for a file sink) |
+
+### Mail-specific
+
+| slug | status | meaning |
+|---|---|---|
+| `idempotency_key_required` | 422 | `send()` without one (§3.2) |
+| `mailbox_readonly` | 403 | the server selected the folder read-only and a mutating verb was asked |
+| `quota_exceeded` | 507 | the server refused an `append`/`put` for quota; distinct from `too_large` because the remedy is the operator's, not the payload's |
+| `recipients_rejected` | 422 | every recipient refused; a partial refusal is a **success** carrying `rejected: [...]`, because the accepted mail was sent and cannot be unsent |
+| `message_invalid` | 422 | the structured message could not be built (no recipient, no body, bad address) |
+
+### FTP/SFTP-specific
+
+| slug | status | meaning |
+|---|---|---|
+| `not_a_directory` / `is_a_directory` | 422 | the path's type does not fit the verb |
+| `not_empty` | 409 | `rmdir` on a non-empty directory with `recursive: false` |
+| `path_invalid` | 422 | NUL/CR/LF in a path (command injection), or an empty path |
+
+### The refuse-by-name rule, concretely
+
+Two layers, both mandatory:
+
+1. The **prelude** builds every host payload from an explicit allow-list of keys
+   and refuses an unlisted key by name. The hazard is already documented in
+   `host_prelude.js`: a payload built from an explicit key list silently
+   discards anything missing from the list, which is exactly how `embedTimeoutMs`
+   got lost. So every option in this document must appear in both the
+   allow-list check **and** the payload construction, and a test must assert
+   that the two lists are equal.
+2. The **host** refuses an option it does not implement for the resolved scheme,
+   by name, even if the prelude accepted it as well-shaped. `markSeen` on a POP3
+   connection is the live example: POP3 has no `\Seen` flag, so accepting the
+   option would tell a consumer a bound is in force that is not. It is
+   `protocol_unsupported` **422** naming the option and the scheme - and this is
+   worth calling out, because `markSeen: false` is the *safe* value, so the
+   temptation to accept it silently on POP3 is strong. Refuse it anyway: the
+   author needs to know POP3 cannot promise it.
+
+### SFTP host keys - open decision
+
+`knownHostKey` as shown is explicit pinning, which is the correct default
+posture but is operationally hostile (a server rekey breaks every function). The
+alternatives are a per-project known-hosts file in the file store, or
+trust-on-first-use recorded server-side. **Unsure.** My recommendation is
+explicit pinning in phase 1 with `host_key_mismatch` **403**, plus
+`site.hostKey` on the handle so a function can report the key it saw and an
+operator can pin it - never a `verifyHostKey: false` escape hatch, since that
+is MITM-by-option on a credentialed connection.
+
+---
+
+## 9. Idempotency for anything that sends
+
+Job delivery is at-least-once. The affected verbs are `mail.send`,
+`mail.append`, `ftp.put`, `dav.put`, and arguably `ftp.rename`/`delete`.
+
+- `mail.send`: `idempotencyKey` **required** (§3.2). Non-negotiable - the side
+  effect is irreversible and externally visible.
+- `mail.append`, `ftp.put`, `dav.put`: naturally idempotent **by name** when
+  `overwrite: true` (writing the same bytes to the same path twice is one
+  outcome), so no key is required. With `overwrite: false` a replay is
+  `already_exists` **409**, which an author can catch - and should be documented
+  as the intended replay signal rather than an error.
+- `ftp.delete`, `rmdir`: idempotent in effect; a replay is `not_found` **404**,
+  again a documented replay signal.
+- `ftp.rename`: **not** idempotent and has no natural key. Flagged: I do not
+  think it earns a dedupe ledger, and the honest surface note is "a replayed
+  rename fails with `not_found`; make the target name derivable from the source
+  so the replay is detectable."
+
+Open questions on the ledger, for part 2 to settle:
+
+- Where the record lives. A reserved per-project collection
+  (`<project>:vectorapi_outbox`, following the `vectorapi_` reserved prefix and
+  the `vectorapi_secrets` precedent of being invisible to the documents API) is
+  the obvious answer, and it gives operators an audit trail of what was sent.
+- Retention. A TTL (the documents layer already has `ttl_seconds`) of something
+  like 7 days, long enough to cover any plausible stale-lease reclaim.
+- Whether the record is written **before** the send (claim, then confirm) so a
+  crash between send and record cannot produce a duplicate. It should be, which
+  means a third state (`in_flight`) and a decision about what a key in
+  `in_flight` from a dead run means. I flag this as the hardest unresolved part
+  of the whole design: it is the difference between "usually not duplicated" and
+  at-most-once, and the brief's at-least-once delivery makes it load-bearing.
+
+---
+
+## 10. Authorization
+
+Protocol access is **not** a collection, so `requireCapabilityCore` needs
+something to evaluate. Recommendation: reserved pseudo-collections, following
+the `_files` precedent exactly (leading underscore, unshadowable because
+collection-create rejects `_`-prefixed names):
+
+- `_mail` - ops `read` (list/search/fetch/folders), `write` (flag/move/delete/
+  append), `send` (SMTP).
+- `_net` - ops `read`/`write` for `ctx.ftp` and `ctx.dav`.
+- `_files` - gains a `write` op, used only by a transfer's file sink (§6.1).
+
+`builtinDefaultFunctionPolicy()` grants **nothing**, and that floor must hold
+here: an unreviewed function must not be able to send mail as the tenant or
+write to their SFTP server until an admin says so. A test should assert the new
+pseudo-collections are absent from the default, the same way the current floor
+is asserted.
+
+Destination allow-listing is a separate question from the capability: a policy
+that grants `_mail.send` grants sending via *any* server the egress guard
+permits. Whether the function policy should also carry a host allow-list is an
+open product question. My view: yes eventually, and it belongs with the stored
+connection profiles of §2 (a profile is the natural unit to grant), which is
+another reason to design the descriptor so profiles can slot in.
+
+---
+
+## 11. Summary of recommendations
+
+1. **Several named surfaces** (`ctx.mail`, `ctx.ftp`, `ctx.dav`) over one host
+   kernel. Reject a generic `ctx.protocol(scheme)`; reject one namespace per
+   wire protocol. Scheme lives in the connection URL; `handle.capabilities`
+   reports the differences; an impossible verb is refused by name.
+2. **Explicit, lazily-connected, run-scoped handles** from `connect()` /
+   `sender()`. Reject implicit per-call connections. No cross-run pooling.
+3. Verb sets per §3, with mail returning **summaries and part trees**, never
+   attachment bytes.
+4. **Three-level option resolution** (builtin safe default <- connection <-
+   per call, last wins), positively-named options defaulting to the safe value,
+   resolved by a pure host function. Timeouts and operator-protecting options
+   stay **narrowing only**. Reject a `safeMode` bundle.
+5. `timeoutMs` everywhere, **validated not coerced**, narrowing only, resolving
+   in whole seconds with a 1 s floor per phase - and that overrun documented in
+   `llms.txt`.
+6. **Sources and sinks**: bytes move host-side, calls return a `Transfer`
+   reference; inlining is an explicit capped opt-in (hard ceiling 1 MiB). The
+   file-store sink needs a new `_files` write capability and is bounded by
+   `max_file_bytes`, not by the 1 MiB load cap. A 100 MB transfer is the
+   `{ url }` relay sink's job, or an operator settings change - not something
+   the surface should pretend to do by default.
+7. One `Page` shape, opaque host cursors, `complete` and `truncated` reported
+   separately, cursors scoped to the handle, `page.next()` but no implicit
+   iteration. FTP paging is host-side and says so.
+8. Slug table in §8; refusal by name enforced in **both** the prelude allow-list
+   and the host, with a test asserting the prelude's allow-list and its payload
+   key list are equal.
+9. `idempotencyKey` **required** on `mail.send`; other writes made idempotent by
+   `overwrite`/`not_found` semantics; the ledger's claim-then-confirm design is
+   the biggest open item.
+
+### Explicitly unsure / out of scope here
+
+- Stored named connection profiles (credentials and host allow-listing out of
+  tenant code). Recommended eventually; `connect('name')` reserved for it.
+- `ctx.dav` typed CalDAV/CardDAV (iCalendar/vCard model in the host). Deferred;
+  file-like WebDAV folded into `ctx.ftp`.
+- SFTP host-key policy beyond explicit pinning.
+- `chmod` in the FTP verb set.
+- The idempotency ledger's storage, retention and in-flight state.
+- Whether `mail.append` should accept only structured messages and drop the
+  raw-RFC822 source shape (one fewer way to be wrong, at the cost of refusing a
+  legitimate "copy this exact message" case).
+
+
+# Part 2
+
+# Spec part 2: the libcurl host integration
+
+Scope: the C++ side. How curl is built, which layer owns it, how a handle lives
+and dies, how a call is bounded, who parses IMAP, how a failure becomes an
+`ApiError`, and what reaches the journal. The JS-facing shape of `ctx.mail.*`
+and the tenancy/credential model are other agents' lanes; where a decision here
+constrains theirs it is marked **[hand-off]**.
+
+Two facts set the shape of everything below, and both come from measurement
+rather than from the docs:
+
+1. Every IMAP read must go through `CURLOPT_CUSTOMREQUEST`, because curl's
+   convenient URL form issues `UID FETCH n BODY[]` and that **marks mail read**.
+   `;SECTION=TEXT` is still `BODY[TEXT]`, still not PEEK. So is SEARCH, STORE,
+   MOVE, LIST and BODYSTRUCTURE. **curl is a connection and command pipe, and we
+   own the IMAP response parser.** That is the single largest piece of work in
+   this project and section 5 is honest about it.
+2. curl always sends `SELECT <mailbox>` from the URL path before the custom
+   request, and SELECT is read-write. Read-only access therefore means **keeping
+   the mailbox out of the URL** and issuing `EXAMINE` ourselves as the first
+   custom request on the handle. That turns a single mail read into at least two
+   `curl_easy_perform` calls on one handle, which is why section 3 is about a
+   per-run session rather than a per-call handle.
+
+---
+
+## 1. Build and vendoring
+
+### Recommendation
+
+**Link Debian's libcurl for the shipped `.deb`s. Offer the vendored FetchContent
+pin behind `SVAPI_VENDOR_CURL=ON`, default OFF.** The product owner's "latest
+stable from their git repo" is available with one cmake flag and is the right
+default on the dev host; it is the wrong default for a package published to an
+outward-facing apt repo.
+
+The tradeoff stated plainly, because it is the whole decision:
+
+- **Distro libcurl.** Debian's security team tracks curl CVEs and backports
+  fixes to stable. A `libcurl4t64` security update reaches every deployed box
+  through unattended-upgrades without us rebuilding or republishing anything.
+  Cost: we get whatever version and whatever protocol set trixie built, and a
+  feature that needs a newer curl has to wait for the next Debian.
+- **Vendored libcurl.** We get exactly 8.22.0 and exactly the protocols we
+  choose. Cost: **we own curl CVE tracking.** curl ships security advisories
+  with most releases, on a roughly 8-week cadence, and a statically linked curl
+  inside our binary is invisible to the distro's tooling, so a vulnerable
+  version sits on a customer box until somebody here notices and republishes.
+  Worse, **SFTP needs libssh2**, which the vendored path must also fetch and
+  pin, so the obligation is two upstreams, not one. libssh2 has had remotely
+  reachable issues and is far less watched than curl.
+
+Three people maintain this service. Taking on a standing security-tracking
+obligation that Debian already discharges for us, in exchange for features we
+have not yet shown we need, is a bad trade. If the owner wants vendoring anyway,
+it is defensible, but only with the three obligations named in "the price of
+vendoring" below written down and accepted, not assumed.
+
+### Before the decision is final: measure trixie
+
+Nothing here should be settled from memory. Run, in the packaging base image:
+
+```
+dpkg-query -W -f='${Version}\n' libcurl4-openssl-dev libcurl4t64
+curl-config --version --protocols --ssl-backends
+```
+
+The decision hinges on one question only: **does trixie's libcurl build include
+`imaps`, `smtps`, `pop3s`, `ftps` and `sftp`?** `sftp` is the one at risk, since
+it depends on the maintainers enabling libssh2. If `sftp` is missing, the choice
+narrows to vendoring, dropping SFTP from the surface, or shipping SFTP through a
+separate libssh2-backed path. Record the measured output in the build file next
+to the option, the way the httplib pin records its reasoning.
+
+### The vendored pin, when it is used
+
+curl's git tags are underscored. The pin is `curl-8_22_0`.
+
+```
+set(SVAPI_CURL_TAG "curl-8_22_0" CACHE STRING "curl git tag to vendor")
+```
+
+Following the `cmake/Dependencies.cmake` convention, **the pin comment must
+record, as a decision rather than a default**:
+
+- the tag, its release date (2 Sep 2026) and the next release date (14 Oct
+  2026), so the review cadence is explicit rather than aspirational;
+- **that vendoring moves CVE tracking from Debian to us**, with a named owner;
+- which protocols this project actually relies on, so a reviewer can judge an
+  advisory against our reachable surface rather than against its severity score.
+  This is the same discipline the httplib pin uses, and the same discipline that
+  correctly ruled the `RegexMatcher` overflow out of scope there;
+- the full disable list below, because that list *is* the attack surface of the
+  pin, and an advisory in HTTP/3, proxy handling, NTLM or Kerberos is not our
+  exposure if those are compiled out;
+- that the vendored build is **static** and therefore invisible to `apt`, so a
+  fix means a rebuild and a republish of both binaries.
+
+### What to disable, and why
+
+```
+BUILD_SHARED_LIBS            OFF   # static into both binaries; nothing new in the .deb
+BUILD_CURL_EXE               OFF   # we need the library, not the tool
+BUILD_TESTING                OFF
+CURL_DISABLE_INSTALL         ON    # curl must not land in our .deb, as with quickjs
+ENABLE_CURL_MANUAL           OFF
+
+CURL_USE_OPENSSL             ON    # one TLS backend, the one everything else here uses
+CURL_USE_LIBSSH2             ON    # the only reason sftp exists
+CURL_USE_LIBPSL              OFF   # a cookie-domain concern; we have no cookies
+CURL_USE_GSSAPI              OFF
+CURL_DISABLE_NTLM            ON
+CURL_ENABLE_SSL              ON
+ENABLE_THREADED_RESOLVER     ON    # see "threading" below
+USE_NGHTTP2 / USE_NGTCP2 ... OFF   # no HTTP/2, no HTTP/3
+
+CURL_DISABLE_HTTP            ON    # see the WebDAV note
+CURL_DISABLE_PROXY           ON
+CURL_DISABLE_COOKIES         ON
+CURL_DISABLE_NETRC           ON
+CURL_DISABLE_ALTSVC          ON
+CURL_DISABLE_HSTS            ON
+CURL_DISABLE_FILE            ON
+CURL_DISABLE_DICT            ON
+CURL_DISABLE_GOPHER          ON
+CURL_DISABLE_LDAP            ON
+CURL_DISABLE_LDAPS           ON
+CURL_DISABLE_MQTT            ON
+CURL_DISABLE_RTSP            ON
+CURL_DISABLE_SMB             ON
+CURL_DISABLE_TELNET          ON
+CURL_DISABLE_TFTP            ON
+CURL_DISABLE_WEBSOCKETS      ON
+```
+
+The reasoning behind the ones that are not obvious:
+
+- **`CURL_DISABLE_PROXY`.** `ctx.fetch` is safe from proxy hijack today only
+  because httplib reads no `http_proxy` environment variable. curl reads
+  `*_proxy` and `ALL_PROXY` by default, and `runner.env` is a file an operator
+  edits. A proxy variable that nobody intended to apply to mail would silently
+  reroute an SSRF-approved destination to an unapproved one and break the
+  address pinning in section 4's sibling lane. Compiling proxy support out is
+  stronger than remembering to set `CURLOPT_PROXY` to the empty string on every
+  handle, and it cannot be undone by a future patch that forgets.
+- **`CURL_DISABLE_NETRC`.** Otherwise curl can read credentials from a file on
+  disk. Credentials come from project secrets and nowhere else. **[hand-off:
+  security agent]**
+- **`CURL_DISABLE_COOKIES` / `ALTSVC` / `HSTS`.** Each is persistent
+  cross-request state, which is precisely the thing a multi-tenant pool must not
+  accumulate (section 3). Removing the feature is better than scrubbing it.
+- **`CURL_DISABLE_HTTP`.** curl is not used for HTTP here; `ctx.fetch` is
+  httplib, with its own guard, its own pinning and its own budget, and two HTTP
+  clients with two sets of outbound defaults is exactly how the two drift.
+  **Consequence, stated rather than discovered later: WebDAV is out of slice 1.**
+  WebDAV is HTTP, so shipping it means either re-enabling HTTP in curl and
+  extending `applyOutboundDefaults`-equivalent discipline to it, or implementing
+  WebDAV over httplib. Both are real work. The "maybe" in the brief should
+  become a "no" for now. If this is contested, note that re-enabling HTTP also
+  brings back redirects, which then need `CURLOPT_REDIR_PROTOCOLS_STR` set
+  separately from `CURLOPT_PROTOCOLS_STR` and `CURLOPT_FOLLOWLOCATION` off, and
+  the httplib pin comment already records why redirects on a credentialed
+  request are a problem.
+- Per-handle `CURLOPT_PROTOCOLS_STR` is set **as well**, to the single scheme the
+  call needs (`"imaps"`, not `"imap,imaps"`). Belt and braces: the build-time
+  list bounds the binary, the per-handle list bounds the call, and the second is
+  what catches a URL that got past validation.
+
+### Threading
+
+Two things are mandatory in a runner that is a thread pool, and both are easy to
+forget because a single-threaded test never shows the problem:
+
+- **`CURLOPT_NOSIGNAL = 1` on every handle.** Without it, curl uses `SIGALRM`
+  for name resolution timeouts, which is unsafe off the main thread and can
+  cause a longjmp out of a worker. With `ENABLE_THREADED_RESOLVER` and
+  `CURLOPT_RESOLVE` doing the resolution for us, the timeout path is clean.
+- **`curl_global_init(CURL_GLOBAL_DEFAULT)` exactly once, from the runner's
+  `main`, before any worker thread starts**, and `curl_global_cleanup` at
+  shutdown. `curl_global_init` is not thread-safe and a lazy first-use
+  initialisation from two pool threads is a real race.
+- **Verify thread safety at boot and refuse to start otherwise.**
+  `curl_version_info()` reports `CURL_VERSION_THREADSAFE`. A runner whose curl
+  lacks it should fail to start with a clear message, in the same spirit as the
+  runner refusing to start with no token on a non-loopback bind. Fail closed, at
+  boot, where it is cheap.
+
+### Packaging interaction
+
+- **Distro path (recommended).** `packaging/Dockerfile.base` adds
+  `libcurl4-openssl-dev` to the existing `apt-get install` line. `control.server`
+  and `control.runner` gain `libcurl4t64` in `Depends` (confirm the exact
+  package name from the measurement above; trixie renamed the t64 ABI packages).
+  No FetchContent, no new network fetch at configure time, nothing new to track.
+  Only `control.runner` strictly needs it if the server never speaks these
+  protocols, which is the likely shape, but the scheduler and event watcher live
+  in the server and may want to validate a mail account; decide once the JS
+  surface is settled. **[hand-off]**
+- **Vendored path.** No new `Depends`, because it is statically linked, but
+  `Dockerfile.base` still needs `libssh2-1-dev` and `zlib1g-dev` headers unless
+  those are vendored too, and the configure step gains a git fetch. Note the
+  precedent and the objection: `BUILD_RUNNER` is **OFF by default precisely
+  because it vendors QuickJS from GitHub at configure time and an ordinary build
+  must not start depending on a network fetch.** The same rule applies here, so
+  the vendored option cannot become the default without changing that principle.
+- **`build.sh --local` on the Void dev host** works either way; Void has
+  libcurl. The host build (`scripts/host-build.sh`) should print
+  `curl-config --protocols` on startup, because a dev host missing `sftp` will
+  otherwise produce a failure that looks like a code bug.
+- **`--rebuild-base` is required when `SVAPI_CURL_TAG` or the libcurl dev
+  package moves**, for exactly the reason the `DB_CLIENT_VERSION` note gives:
+  the version is baked into the base image, and bumping only the variable leaves
+  the release compiling against the old headers. Add it to the existing note
+  rather than writing a second one.
+
+### The price of vendoring, if the owner insists
+
+Write these down and get them accepted; do not assume them.
+
+1. A **named owner** subscribed to `curl-announce` and to libssh2 releases, who
+   reviews each advisory against the disable list above.
+2. A **rebuild-and-publish SLA** for a reachable high-severity advisory, with
+   "reachable" judged the way the httplib pin judges it: against what this
+   service actually reaches, not against the CVSS score.
+3. A note in the release checklist that a curl fix means republishing **both**
+   the server and the runner `.deb`, and that the apt repo drops superseded
+   versions on publish, so the old `.deb`s must be kept for rollback.
+
+### Rejected alternatives
+
+- **git submodule instead of FetchContent.** The repo has one vendoring
+  mechanism and it is FetchContent. A second one for one dependency is churn.
+- **System curl with a minimum-version check.** The check either passes
+  everywhere, in which case it is noise, or it fails on trixie, in which case we
+  are vendoring anyway. The protocol-set check above is the useful one.
+- **`curl_multi` in slice 1.** See section 4.
+
+---
+
+## 2. Which layer
+
+### Recommendation: a new fourth library, `runner_net`
+
+The three-layer split exists so that each layer can be tested where it can be
+built: `runner_core` has no database, `runner_protocol` has no transport and no
+database (which is why its 30 tests run on the dev host), `runner_host` links
+`vectorapi_core` and therefore the whole world.
+
+A curl-backed protocol host does not fit any of the three:
+
+- **Not `runner_core`.** That is the QuickJS engine. Linking a network stack
+  into it destroys the property that makes it useful: that it is the piece with
+  no I/O.
+- **Not `runner_protocol`.** Its defining constraint is "no transport".
+- **`runner_host` is where it would land by default, and that is the wrong
+  answer**, because `runner_host` links `vectorapi_core` and the database
+  client, and therefore **cannot be built or tested on the dev host**. Putting
+  the IMAP parser there would make the largest, most defect-prone, most
+  obviously unit-testable piece of this project the one piece only the Docker
+  path can compile. That is backwards.
+
+So:
+
+```
+runner_core      QuickJS engine + pool. No I/O.
+runner_protocol  /run, /validate, /health as JSON in, JSON out. No transport, no DB.
+runner_net       NEW. libcurl + the IMAP parser + the budget split + the error map.
+                 Links: libcurl, OpenSSL, nlohmann_json, spdlog, and the pure
+                 server sources it needs compiled in directly
+                 (src/functions/net_guard.cpp, the same trick runner_protocol
+                 already uses for functions/timezone.cpp).
+                 Does NOT link vectorapi_core or the database client.
+runner_host      The ctx.* surface. Links vectorapi_core AND runner_net.
+                 Holds only the JS binding glue for ctx.mail.* etc.
+```
+
+`runner_net` builds and tests on the Void dev host. That is the point of the
+split, and it is why it is worth adding a fourth target rather than widening an
+existing one.
+
+The division of labour at the `runner_host` boundary is strict: `runner_host`
+converts JS values to a plain request struct and converts a plain result struct
+back, and does nothing else. No curl call, no IMAP knowledge, no timeout
+arithmetic above the line. Same shape as the existing `hostdetail` namespace,
+which exists so "the policy decision and the request/response shaping" are
+testable without an engine, a resolver or a database.
+
+### What can be unit-tested with no network
+
+Most of it, which is the strongest argument for the layering:
+
+| Piece | Test without a network? |
+|---|---|
+| Budget arithmetic (`resolveTransferBudget`) | Yes, pure integers. No curl header needed. |
+| IMAP tokenizer, s-expression reader, FETCH/SEARCH/LIST/BODYSTRUCTURE interpreters | Yes, bytes in, structs out. The bulk of the test suite. |
+| Mailbox-name encoding (modified UTF-7), command construction, argument quoting and literal framing | Yes, pure. Also the injection boundary, so it gets adversarial tests. |
+| `CURLcode` plus response code to `ApiError` mapping | Yes. Synthetic `CURLcode` values; links curl only for the enum. |
+| URL construction, `CURLOPT_RESOLVE` string construction | Yes. |
+| xferinfo callback abort decision | Yes, if the decision is a pure function of (deadline, now, bytes, cap) and the callback is a thin shim over it. Design it that way. |
+| An actual IMAP conversation | No. A loopback fake-IMAP fixture, as already used by hand to establish the BODY.PEEK facts. |
+
+The fake-server fixture is worth building properly and committing, because the
+facts in the brief were established with one and the next person will need to
+re-establish something similar. Two notes on it: it must be a plain TCP listener
+in-process on an ephemeral port with canned scripted responses, and **the SSRF
+guard blocks loopback by default**, so the test has to inject a policy that
+permits it rather than relying on `function_egress_allow_private`. Keep that
+override inside the test fixture and never reachable from a settings path.
+**[hand-off: security agent]**
+
+---
+
+## 3. Handle lifecycle
+
+### Recommendation: one handle per (run, account), destroyed at the end of the run. No cross-tenant reuse, no `CURLSH`.
+
+A per-`curl_easy_perform` handle is wrong, because fact 2 means a read-only IMAP
+read is already two or more performs (`EXAMINE`, then `UID SEARCH`, then one or
+more `UID FETCH`), and a fresh handle per perform means a fresh TCP connect, TLS
+handshake and LOGIN per command. That is both slow and the thing that gets an
+account throttled or locked.
+
+A process-wide cache is also wrong, for slice 1. What can leak through a reused
+curl handle or a shared `CURLSH` is not theoretical:
+
+- the **connection cache**, which is where an *already authenticated IMAP
+  session* lives. A reused connection is a reused login. If the cache key is
+  ever wrong, by one field, a function in project A issues commands inside
+  project B's mailbox session. That is not a mis-sorted list, it is a
+  cross-tenant mail breach, and it is the same class of risk the file store
+  note calls out.
+- **TLS session tickets**, which are a cross-tenant linkability channel and also
+  bypass a full handshake, so a certificate that has since been revoked can be
+  resumed against.
+- the **DNS cache**, which would defeat the one-resolution-one-classification
+  rule that the SSRF guard depends on. `CURLOPT_RESOLVE` is set per handle; a
+  shared DNS cache is a second source of truth for an address.
+- leftover `CURLOPT_*` values. `curl_easy_reset()` resets options but **does not
+  flush the connection cache**, so "reset and reuse" is exactly the unsafe
+  middle ground: it looks like scrubbing and leaves the dangerous part behind.
+
+So the rule is **destroy, do not scrub**. Concretely:
+
+- The handle lives in a `MailSession` object owned by the run's `HostContext`,
+  keyed in a small map by `(scheme, host, port, username, credential digest)`.
+  The digest is a SHA-256 of the credential material, so two accounts that
+  differ only in password are different sessions and a changed password cannot
+  silently reuse the old authenticated connection.
+- `HostContext` is per-lease. When the lease ends the map is cleared, every
+  handle is `curl_easy_cleanup`'d, and curl sends the protocol's own teardown
+  (`LOGOUT`, `QUIT`) as part of closing. **No handle outlives a lease, so no
+  state crosses tenants, so no key correctness argument has to hold.** That is
+  the property worth paying for.
+- Also destroy a handle **immediately on any error**, rather than retrying on
+  it. A handle whose last perform failed mid-literal has an unknown amount of
+  unread response data queued, and the next command's response would be parsed
+  against the previous command's tail. This is the single most likely source of
+  baffling parser bugs, and destroying on error removes the whole class.
+- A poisoned-session concept, mirroring the QuickJS runtime's `poisoned()`: if a
+  response cannot be parsed, the session is not merely failed, it is unusable,
+  because the stream position is unknown. Mark it and refuse further commands on
+  it within the run.
+- Cap the sessions per run (2 or 3). A run that wants ten mail accounts is doing
+  something that belongs in ten job runs.
+
+### The login-cost objection, answered honestly
+
+IMAP login is expensive and some servers throttle repeated logins. With a per-run
+session, a cron function that polls a mailbox every minute logs in every minute.
+That is normal mail-client behaviour and no provider objects to it. What
+providers object to is a login per *message*, which the per-run session already
+prevents.
+
+The sharper problem is the **HTTP wall ceiling of about 2 s**. A remote TLS
+handshake plus LOGIN can plausibly consume 300 to 800 ms of that, which makes an
+`http`-triggered mail read fragile for reasons that have nothing to do with the
+work. The right answer is not a cross-run connection cache, it is a convention:
+**mail work belongs on `job` and `cron` triggers**, whose ceiling is far higher
+and which hold no socket. The budget model in section 4 already distinguishes
+the two kinds, and `RunService::run` already takes the kind as a parameter. Say
+this in the function docs loudly enough that nobody builds a mail route first
+and discovers it second. **[hand-off: JS surface agent]**
+
+### If a cross-run cache is ever needed, slice 2 and not before
+
+Preconditions, all of them:
+
+1. **Measurement first.** The per-protocol counters and the login-time histogram
+   from section 7 ship in slice 1 precisely so this decision has data. Build the
+   cache when the histogram says it matters, not before.
+2. Owned by the runner, outside any `HostContext`, with the key being the full
+   tuple above including the credential digest **and the project**, and the
+   project compared first.
+3. An idle TTL well under the server's own, since a server-closed connection
+   discovered at command time is indistinguishable from a protocol error.
+4. A hard cap on entries, with LRU eviction, so it cannot become an unbounded
+   holder of authenticated sessions.
+5. Destroyed on any error, as above.
+6. Explicit sign-off from the security agent's design, because it reintroduces
+   exactly the cross-tenant state that slice 1 removes by construction.
+
+Rejected: a global `CURLSH` share handle for DNS, TLS sessions or connections.
+It is the convenient way to get connection reuse and it shares state across
+tenants with no per-project key at all.
+
+---
+
+## 4. The budget model
+
+### The principle, carried over unchanged
+
+`src/functions/embed_budget.hpp` states it: a blocking host call cannot be
+interrupted by the QuickJS interrupt handler, because the engine never regains
+control while a C++ request is in flight, so **the timeouts handed to the client
+are the enforcement, not an optimisation**. It exists because a 10 s-budget run
+took 14314 ms, when the read timeout was clamped to the budget and the connect
+timeout was not, and the two are additive.
+
+curl is better placed than httplib here, and the design should bank that:
+**`CURLOPT_TIMEOUT_MS` is a bound on the whole operation, connect included.**
+The additive-overrun bug that `embed_budget.hpp` was written to fix is
+structurally impossible when `CURLOPT_TIMEOUT_MS` is set to the available
+budget, whatever `CURLOPT_CONNECTTIMEOUT_MS` says. Say so in the header comment,
+because the next person will otherwise assume curl has the same hazard.
+
+Also prefer the `_MS` variants over `CURLOPT_TIMEOUT` and
+`CURLOPT_CONNECTTIMEOUT`, which are whole seconds. The existing `ctx.fetch` path
+rounds a budget up to whole seconds because httplib takes `time_t`; curl does
+not force that, so a 1500 ms budget can be 1500 ms rather than 2 s.
+
+### The pure arithmetic: `src/functions/transfer_budget.hpp`
+
+Header-only, pure, **no curl header**, so the test target needs no libcurl and
+the file can be compiled into a dev-host test directly. Same discipline as
+`embed_budget.hpp`: milliseconds in, the numbers the client takes out.
+
+```
+struct TransferBudgetRequest {
+    int64_t remainingBudgetMs   = 0;  // <= 0 means refuse the call, do not floor it
+    int64_t configuredConnectSec = 0; // operator setting, 0 = unstated
+    int64_t configuredOpSec      = 0; // operator per-operation ceiling, 0 = unstated
+    int64_t callTimeoutMs        = 0; // per-call, from the script. NARROWING ONLY.
+    int64_t stallSec             = 0; // operator low-speed window, 0 = unstated
+};
+
+struct TransferBudget {
+    int64_t connectTimeoutMs = 1000;  // CURLOPT_CONNECTTIMEOUT_MS
+    int64_t totalTimeoutMs   = 1000;  // CURLOPT_TIMEOUT_MS, the whole operation
+    int64_t lowSpeedLimit    = 1;     // CURLOPT_LOW_SPEED_LIMIT, bytes/sec
+    int64_t lowSpeedTimeSec  = 1;     // CURLOPT_LOW_SPEED_TIME
+    bool    boundByCall      = false; // the script's own bound was binding
+};
+```
+
+Rules, all inherited from `resolveEmbedBudget` rather than reinvented:
+
+- **Connect gets at most half** the available time. A reachable mail server
+  connects in well under a second; a large connect allowance only starves the
+  transfer phase.
+- **Narrowing only.** A per-call timeout can ask for less than the remaining
+  budget and never for more. Same reasoning as the per-project embedding
+  timeouts being `min(project, global)`: these govern a shared connection and a
+  pooled runtime waiting on it.
+- **A floor of 1 s per phase**, and the same honest caveat as
+  `embed_budget.hpp`: below a 2 s budget the floor dominates and the worst case
+  overruns by up to a second. State it, do not gloss it.
+- **A non-positive remaining budget means refuse before connecting**, so an
+  exhausted budget costs no socket. That is already how `ctx.fetch` behaves.
+- `lowSpeedTimeSec` is `min(configured stall, available/2)` with a 1 s floor.
+
+Whether to share code with `resolveEmbedBudget` or delegate to it: **delegate.**
+Call it for the connect/total split and derive the low-speed pair, rather than
+copying the arithmetic. A second copy of the half-and-floor rule is a second
+place for it to be fixed. Do not change `resolveEmbedBudget`'s signature; the
+embedding path and its tests are correct as they stand.
+
+### Re-resolve per perform, not per session
+
+This is the part a session-based design gets wrong by default. A mail read is
+several performs on one handle, and the budget shrinks between them. So:
+
+**`resolveTransferBudget` is called immediately before every
+`curl_easy_perform`, from the run's current remaining budget**, and its output
+is applied to the handle each time. A budget resolved once at LOGIN and reused
+for the FETCH is the 14314 ms bug with extra steps.
+
+### The xferinfo abort: what makes the call genuinely interruptible
+
+Timeouts alone are not enough, and this is where curl buys something httplib
+cannot give. A server that trickles one byte every few hundred milliseconds
+defeats a read timeout indefinitely; `CURLOPT_LOW_SPEED_*` catches some of that,
+but only in whole seconds and only below a rate threshold. The real control is:
+
+```
+CURLOPT_NOPROGRESS      0
+CURLOPT_XFERINFOFUNCTION  shim
+CURLOPT_XFERINFODATA      &perCallState
+```
+
+Returning 1 aborts with `CURLE_ABORTED_BY_CALLBACK`. curl calls it frequently
+and **at least about once per second even when the transfer is idle**, which
+bounds the overshoot past the deadline at roughly one second plus the duration
+of whatever single blocking syscall is in flight. That is the honest figure and
+it should be written in the header, not implied to be instant.
+
+The callback does two jobs:
+
+1. **Deadline.** Compare now against the run's deadline.
+2. **Byte cap.** Abort when `dlnow` exceeds the per-call cap. This is the actual
+   defence against a 200 MB message landing in a 64 MiB JS heap, in the same
+   spirit as `kCtxFileMaxBytes` bounding what one run may load as against
+   `max_file_bytes` bounding what may be stored. Two caps, two questions. Pair
+   it with IMAP's partial fetch (`BODY.PEEK[TEXT]<0.160>`), which **bounds the
+   transfer on the wire rather than just the result** and is therefore the
+   cheaper of the two; the cap is the backstop for the cases where a partial
+   range cannot be used, such as BODYSTRUCTURE on a pathological message.
+
+**How the deadline reaches the callback.** The existing convention is that
+`HostContext::config.deadlineMs` is relative to run start and `elapsedMs()`
+measures against a steady clock (`outboundTimeoutMs(config.deadlineMs,
+elapsedMs(), requested)`). Keep that convention rather than inventing an
+absolute one: the per-call state struct, allocated on the stack of the calling
+host function and valid for exactly the duration of the perform, carries
+
+```
+struct TransferGuard {
+    int64_t  deadlineElapsedMs;  // run-relative, as config.deadlineMs is
+    int64_t (*elapsedMs)(void*); // or a std::function bound to the context
+    void*    owner;
+    int64_t  byteCap;
+    enum class Abort { None, Deadline, ByteCap } abort = Abort::None;
+};
+```
+
+and the decision itself is a **pure function** `shouldAbort(elapsedMs,
+deadlineElapsedMs, bytesSoFar, byteCap) -> Abort`, so the interesting logic is
+unit-tested and the callback is a four-line shim. The recorded `abort` field is
+load bearing for error mapping: both abort reasons produce the same
+`CURLE_ABORTED_BY_CALLBACK`, and section 6 must branch on our own reason rather
+than on the CURLcode, which is the `FailedPrecondition` lesson exactly.
+
+Also set `CURLOPT_ERRORBUFFER` (operator log only, see section 7) and keep
+`CURLOPT_FAILONERROR` out of it; the protocol response codes are read explicitly
+via `CURLINFO_RESPONSE_CODE`.
+
+### Rejected: `curl_multi` in slice 1
+
+`curl_multi` plus a poll loop is the only way to get abort granularity better
+than curl's roughly 1 s progress callback, and it is the only way the host could
+hand control back to the engine mid-transfer. Neither is needed yet: the run
+holds a pool thread for its whole duration anyway (that is why job runs get
+their own pool lane), and a 1 s overshoot on a budget measured in seconds is
+within the tolerance `embed_budget.hpp` already documents. `curl_multi` is the
+documented upgrade path if measurements show the overshoot matters; it is not
+worth its complexity on day one.
+
+---
+
+## 5. The IMAP response parser
+
+### Why we own it
+
+Fact 1. Every read goes through `CURLOPT_CUSTOMREQUEST`, so curl hands us the
+server's response bytes and offers no interpretation of them. There is no way to
+have PEEK semantics and also let curl parse.
+
+### One open measurement, before any code
+
+**Exactly what curl delivers to which callback for an IMAP custom request.**
+curl routes some protocol response material to `CURLOPT_HEADERFUNCTION` and the
+payload to `CURLOPT_WRITEFUNCTION`, and for IMAP the split is not obvious: the
+untagged `* 1 FETCH (...)` line and its literal, the greeting, and the tagged
+completion line may not all arrive in the same place, and the tagged line may be
+consumed by curl and surface only as a `CURLcode` plus `CURLINFO_RESPONSE_CODE`.
+Determine this on the wire against the fake server, write it down in the parser
+header, and make the parser's input contract match. Getting this wrong means a
+parser that works on one command shape and silently mis-frames another.
+
+### Structure: one tokenizer, one reader, several interpreters
+
+The wrong shape is a parser per command. The right shape is three layers, which
+is both less code and less risk:
+
+1. **A byte-counted tokenizer.** Atoms, quoted strings with escapes, `NIL`,
+   numbers, parentheses, and **literals** of the form `{n}\r\n` followed by
+   exactly `n` bytes. **The literal is the whole reason this cannot be
+   line-based**: those `n` bytes may contain CRLF, unbalanced parentheses, and
+   bytes that look like a tagged response line. A line-oriented parser will
+   appear to work on small test data and corrupt on the first real message. This
+   is the single most important correctness property in the parser.
+2. **A generic s-expression reader** producing a small value type
+   (`atom | string | number | nil | list`), with a **depth cap** and an
+   **element-count cap**. A hostile or broken server must not be able to drive
+   unbounded recursion or allocation; cap and refuse.
+3. **Interpreters over that tree**, one per response we actually ask for:
+   - `* <n> FETCH (...)` item lists: `UID`, `FLAGS`, `INTERNALDATE`,
+     `RFC822.SIZE`, `BODY[...]` including partials `<o.n>`, `BODYSTRUCTURE`.
+   - `* SEARCH <uid> <uid> ...`, and `* ESEARCH` if any target server returns it.
+   - `* LIST (<flags>) "<delim>" <name>`, where the name may be a quoted string
+     or a literal, and the flags matter (`\Noselect`, `\HasChildren`).
+   - `* <n> EXISTS`, `* <n> RECENT`, `* FLAGS`, `* OK [UIDVALIDITY n]`.
+   - Tagged completion: `TAG OK|NO|BAD [RESP-TEXT-CODE] text`, with the bracketed
+     code extracted as a **field**, not left in the text. `[AUTHENTICATIONFAILED]`,
+     `[UNAVAILABLE]`, `[OVERQUOTA]`, `[TRYCREATE]`, `[COPYUID]`,
+     `[CLIENTBUG]`, `[SERVERBUG]` are what section 6 branches on.
+
+Two pieces of encoding work that are easy to forget and are not optional:
+
+- **Modified UTF-7** for mailbox names (RFC 3501 5.1.3), unless the server
+  advertises `UTF8=ACCEPT` and we enable it. A customer with a mailbox named
+  `Levelek` is fine; one named `Bejövő` is not, and it will be reported as "the
+  folder does not exist".
+- **RFC 2047 encoded-words** in header fields, because a Subject or From that
+  comes back as `=?UTF-8?B?...?=` is not a usable surface. This arguably belongs
+  to the JS agent's lane, but the bytes arrive here and the decoder is pure, so
+  it should live next to the parser. **[hand-off: JS surface agent]** for whether
+  the decoded or the raw form is exposed, or both.
+
+### Behaviour on garbage
+
+Adopt the descriptor discipline, with one deliberate difference.
+`functions/descriptor.hpp` never throws because a script author's typo is data.
+Here, a malformed server response is **not** data in the same sense: it is a
+genuine protocol failure the tenant must be told about. So: **never throw, never
+undefined behaviour, always return an explicit error value**, which the caller
+turns into a protocol `ApiError` and which poisons the session (section 3).
+Unknown FETCH items and unknown response codes are ignored rather than refused,
+so a server with an extension we have not seen still works.
+
+### Where it lives
+
+`runner/include/runner/imap_parser.hpp` plus `runner/src/imap_parser.cpp`,
+compiled into `runner_net`. Pure: `std::string_view` in, structs out. No curl,
+no sockets, no settings, no clock. A test corpus of captured real responses in
+`runner/tests/data/imap/`, one file per case, which is the asset that makes the
+suite worth anything. Capture from Dovecot, Cyrus, Gmail, Outlook 365, Yahoo and
+Zoho early; they disagree about literals, about `ESEARCH`, about whether a
+mailbox name comes back quoted, and about BODYSTRUCTURE extension data.
+
+Adversarial tests, as first-class cases and not an afterthought: a literal whose
+declared length exceeds the bytes delivered; a literal whose length is larger
+than the cap; a declared length of zero; 8-bit bytes inside a quoted string;
+`NIL` where a list is expected; 10000 nested parentheses; a tagged line appearing
+inside a literal; a response that ends mid-token; CRLF versus bare LF.
+
+### BODYSTRUCTURE and the has-attachments flag
+
+**Is BODYSTRUCTURE parsing required for a has-attachments flag? Yes, and the
+cheaper routes should be rejected explicitly.**
+
+- `BODY.PEEK[HEADER.FIELDS (CONTENT-TYPE)]` and a `multipart/mixed` test is the
+  obvious shortcut, and it is wrong in both directions. False positives: plenty
+  of plain mail is `multipart/mixed` with only text parts, and
+  `multipart/alternative` nested in `multipart/mixed` is routine. False
+  negatives: a single-part `application/pdf` message has no multipart at all,
+  and `multipart/related` with inline images is a judgement call the header
+  cannot express. A silently wrong attachment flag is worse than no flag,
+  because tenants will branch business logic on it.
+- The honest cost of doing it properly is **lower than it looks**, because
+  BODYSTRUCTURE is an s-expression and the reader from layer 2 already parses
+  it. The additional work is interpreting the shape: `body-type-1part` versus
+  `body-type-mpart`, the recursive nesting, and the extension data where
+  `Content-Disposition` lives (attachment versus inline, and the `filename`
+  parameter). That is an interpreter, not a second parser.
+- It is also not optional work for long: BODYSTRUCTURE is what yields part
+  numbers, MIME types and part sizes, which is exactly what any later
+  "fetch attachment N" or "fetch the text part only" call needs. Building it
+  once serves both.
+
+Recommendation: **ship `hasAttachments` only once BODYSTRUCTURE is interpreted,
+and define it as "a part with `Content-Disposition: attachment`, or a non-text
+leaf part that is not an inline image referenced by the HTML"**, with the
+definition written in the docs so a tenant can see why a given message counts.
+Do not ship a header-sniffing approximation in the meantime.
+
+### Effort, honestly
+
+For one experienced person, with tests:
+
+| Piece | Code | Tests | Calendar |
+|---|---|---|---|
+| Tokenizer with literals, s-expression reader, caps | 350 - 450 lines | 400 lines | 3 - 4 days |
+| FETCH / SEARCH / LIST / tagged-completion interpreters | 300 - 400 | 400 | 3 - 4 days |
+| BODYSTRUCTURE interpreter | ~200 | 250 | 2 days |
+| Modified UTF-7 both directions | ~120 | 100 | 1 day |
+| RFC 2047 decoding | ~150 | 150 | 1 day |
+| Command construction, quoting, literal framing, injection tests | ~200 | 250 | 2 days |
+| Fake-server fixture plus a real-provider corpus | ~250 | n/a | 2 - 3 days |
+
+Call it **2.5 to 3 weeks to "works against the five big providers plus Dovecot
+and Cyrus"**, and then a long tail of per-server surprises that never fully
+ends. This should be **its own slice, with its own tests green, before any JS
+surface ships**, because a parser bug surfaces as wrong mail content rather than
+as an error, and wrong mail content is the worst possible failure for this
+product.
+
+### Would a dedicated IMAP library be better?
+
+For the parser specifically, a mature library would be better **if an acceptable
+one existed**. The realistic candidates and why none is chosen:
+
+- **libetpan.** C, the only serious general-purpose option, covers IMAP, SMTP
+  and POP3. Against it: it bundles its own networking and TLS handling, which
+  means a second network stack with a second set of outbound defaults and a
+  second place for address pinning to not happen; its maintenance has been thin;
+  and its historical defect profile in parsing code is not obviously better than
+  careful code of our own with a corpus. Adopting it also does not remove the
+  curl dependency, because FTP, FTPS and SFTP still need it.
+- **vmime.** GPLv3. That is disqualifying for a closed-source `.deb`, before any
+  technical discussion.
+- **Mailcore2.** Objective-C and Apple-platform oriented.
+- **mailio.** C++ and nicely written, but its strength is SMTP and POP3 with
+  MIME; its IMAP coverage does not reach the command set here.
+
+So the verdict is: **curl as the pipe plus our own parser**, with the parser
+scoped deliberately to the commands we expose and not written as a general IMAP
+client. That scoping is what makes it tractable, and it should be stated as a
+constraint in the header so nobody generalises it later "for free".
+
+The risk is real and should be recorded as such: this is the highest
+defect-density component in the project and the one most likely to produce a
+subtle, silent, customer-visible wrong answer. The mitigations are the corpus,
+the adversarial tests, the no-throw explicit-error contract, the session
+poisoning on any parse failure, and the decision not to ship `hasAttachments`
+before it is correct.
+
+The alternative that avoids the parser entirely, for completeness: use curl's
+convenient URL form with `;SECTION`, accept that reads mark mail `\Seen`, and
+ship. Rejected on the measurement in the brief; for a mail-triage product,
+silently marking a customer's mail read is not a tradeoff, it is a defect.
+
+---
+
+## 6. Error mapping
+
+### Shape
+
+Follow `src/db_errors.cpp` exactly, including its commenting style, because it
+is the project's worked example of this problem and its lessons apply verbatim:
+branch on a stable **reason**, never on message text; **never guess a 4xx for an
+unclassified failure**; and give distinct remedies distinct slugs even when they
+share a status.
+
+One file, `runner/src/curl_errors.{hpp,cpp}` in `runner_net`, one function:
+
+```
+ApiError apiErrorForTransfer(const TransferFailure& f);
+
+struct TransferFailure {
+    CURLcode     code = CURLE_OK;
+    long         responseCode = 0;       // CURLINFO_RESPONSE_CODE
+    TransferGuard::Abort abort = None;   // OUR reason, when ABORTED_BY_CALLBACK
+    ImapCompletion completion{};         // OK/NO/BAD + bracketed resp-text-code
+    int64_t      budgetMs = 0;           // what the call was allowed
+    int64_t      tookMs   = 0;           // what it used
+    std::string  host;                   // for the message
+    std::string  errorBuffer;            // OPERATOR LOG ONLY, never the message
+};
+```
+
+Everything in it is plain data, so the whole mapping is unit-tested with
+synthetic values and no network.
+
+### The table
+
+| Condition | Status | Slug | Reasoning |
+|---|---|---|---|
+| `CURLE_COULDNT_CONNECT` | 503 | `mail_unreachable` | Not the tenant's fault, possibly transient. Waiting helps. |
+| `CURLE_COULDNT_RESOLVE_HOST` / `_PROXY` | 503 | `mail_unreachable` | **And log at error.** With `CURLOPT_RESOLVE` set this should be impossible, so it means our pin did not take. That is our bug and the journal must say so. |
+| `CURLE_OPERATION_TIMEDOUT`, when `tookMs >= budgetMs - 1000` | 504 | `deadline_exceeded` | Our own budget ran out, not the server being slow. Same split, same reasoning and the same wording hint as the existing `fetch_timeout` path, which exists because a consumer misdiagnosed exactly this as a stale connection pool. The message must say "this is the run's time budget, not the network" and point at the job trigger. |
+| `CURLE_OPERATION_TIMEDOUT`, otherwise | 504 | `mail_timeout` | The server exceeded an allowance the operator set. Different remedy: raise the setting or fix the server. |
+| `CURLE_ABORTED_BY_CALLBACK` with `abort == Deadline` | 504 | `deadline_exceeded` | |
+| `CURLE_ABORTED_BY_CALLBACK` with `abort == ByteCap` | 422 | `response_too_large` | **One CURLcode, two meanings, branch on our own reason.** This is the `FailedPrecondition` lesson. Waiting never helps, so not 503; the fix is a partial fetch or a smaller range, and the message says so. |
+| `CURLE_WRITE_ERROR` | 422 | `response_too_large` | Our write callback refusing bytes is the same condition by another route. |
+| `CURLE_LOGIN_DENIED`, `CURLE_AUTH_ERROR`, or tagged `NO [AUTHENTICATIONFAILED]` | 422 | `mail_auth_failed` | Argued below. |
+| `CURLE_PEER_FAILED_VERIFICATION`, `CURLE_SSL_CACERT*`, `CURLE_USE_SSL_FAILED` | 422 | `mail_tls_failed` | A trust failure, or STARTTLS not offered on the port given. None of these fix themselves, so retrying is wrong advice. The remedy is the account's host, port or TLS mode. |
+| `CURLE_SSL_CONNECT_ERROR` | 503 | `mail_unreachable` | Often a transient handshake failure or a middlebox, unlike the above. The boundary here is genuinely fuzzy; the rule applied is "does waiting plausibly help", and it is written in the comment so the next person can disagree with the reasoning rather than the code. |
+| Tagged `NO` (any other bracketed code or none) | 422 | `mail_rejected` | A well-formed command the server refused. `[OVERQUOTA]`, `[TRYCREATE]`, "no such mailbox". The server's own text is passed through, truncated, under the rule below. |
+| Tagged `NO [UNAVAILABLE]` or `[SERVERBUG]` | 503 | `mail_unavailable` | The server says it is temporarily unable. Waiting helps. |
+| Tagged `BAD` | 500 | `internal` | **Never the tenant's fault.** The tenant never writes raw IMAP, so a syntactically bad command is our command builder's bug. Log at error with the command **verb** and the response code; return a generic message. Reporting this as a 4xx would send a tenant hunting for a mistake they could not have made. |
+| `CURLE_UNSUPPORTED_PROTOCOL`, `CURLE_URL_MALFORMAT` | 403 | `egress_blocked` | `CURLOPT_PROTOCOLS_STR` refused the handle, which means a URL got past validation. **Log at error**: either our validation has a hole or somebody is probing it. |
+| `CURLE_QUOTE_ERROR`, `CURLE_REMOTE_ACCESS_DENIED` | 422 | `mail_rejected` | The FTP/SFTP equivalents of a protocol refusal. |
+| SMTP `CURLINFO_RESPONSE_CODE` 5xx | 422 | `mail_rejected` | Permanent. Includes a rejected recipient, which is the common case and must not look like a server fault. |
+| SMTP 552, 523, or an IMAP APPEND refused for size | 422 | `message_too_large` | Deliberately the same slug `db_errors.cpp` uses, for the same reason: waiting cannot help, and it is a definite explainable refusal rather than our fault. |
+| SMTP 4xx | 503 | `mail_deferred` | Greylisting and transient refusals. Retrying is exactly right, and `mail_deferred` rather than `mail_unavailable` because the diagnosis differs even though the status does not. Same reasoning as `read_only` and `memory_pressure` each getting their own slug. |
+| `CURLE_OUT_OF_MEMORY`, `CURLE_FAILED_INIT` | 500 | `internal` | Ours. |
+| A parse failure from section 5 | 503 | `mail_protocol_error` | We could not understand a well-delivered response. Not the tenant's fault, and the session is poisoned. Log the first 200 bytes **only at debug**, since they may be message content. |
+| Anything else | 503 | `mail_error` | `curl_easy_strerror(code)` as the message. **The fallback must be the broader answer and never a guess at the narrower one** - the exact arm `db_errors.cpp` argues for in its `FailedPrecondition` default. |
+
+### Why `mail_auth_failed` is 422 and not 401 or 403
+
+401 and 403 in this service mean something specific: the **caller's** credential
+or grant against our API. A function run is already authenticated and authorized
+before any of this code runs, and `requireCapabilityCore` has already answered.
+Reusing 401 here would tell a tenant their API key is wrong when their mailbox
+password is wrong, which sends them to the wrong place entirely.
+
+The mailbox credential is tenant-supplied configuration, so a bad one is the
+tenant's own fixable mistake, which is what 422 means everywhere else here.
+Rejected alternative: 503, on the grounds that it is an upstream failure. It is,
+but retrying never helps and 503 tells a caller to wait, so it would produce a
+cron function that retries a wrong password forever. Same reasoning that put
+`message_too_large` at 422 rather than 429.
+
+### The text pass-through rule
+
+A server's own wording is genuinely useful (`[OVERQUOTA]`, "mailbox does not
+exist"), and the database mapping already sets the precedent of passing a
+server's message through verbatim when it carries the two sizes. But an IMAP
+response stream contains message content, so:
+
+- **Pass through text only from a tagged `OK`/`NO`/`BAD` completion line**, which
+  is a status line and not data, truncated to 200 bytes and stripped of control
+  characters.
+- **Never pass through anything from the untagged data stream.** That is where
+  bodies, subjects and attachments live.
+- **Never pass through `CURLOPT_ERRORBUFFER`** to the tenant. It can contain the
+  effective URL, and a URL is where credentials end up if anyone ever puts them
+  there. Operator log only.
+
+### Slug documentation
+
+These slugs reach the script as `e.code` through `throwApiError`, which is
+already how a function branches without matching message text. They are not HTTP
+routes, so `api/openapi.json` is not where they belong, but the function
+documentation must list them, and the list must be stable: a tenant branching on
+`mail_deferred` to schedule a retry is the intended use.
+
+---
+
+## 7. Observability
+
+### What the operator gets
+
+The existing precedent is the `ctx.fetch` warning, and the note next to it says
+why it was added: "a failing provider was visible ONLY to the tenant, inside
+their function, while the journal said nothing." Do not repeat that hole.
+
+One `spdlog` line per completed protocol call, at **info** for a success that was
+slow and **warn** for a failure, carrying:
+
+- `project`, `function_id`, `run_id`, trigger kind;
+- protocol and scheme, host, port;
+- **the command verb only** (`UID FETCH`, `UID SEARCH`, `APPEND`), plus the
+  number of arguments and, for a FETCH, the item **names**. Never the argument
+  values: `UID SEARCH FROM "boss"` has the tenant's business in it;
+- the account identity as a **reference**, not a value: the secret name the
+  credential came from (`secret:IMAP_PASS`) and the username **masked** at info
+  (`b***@example.com`), unmasked only at debug. A username is both the thing an
+  operator needs to diagnose an auth failure and personal data;
+- `tookMs`, `budgetMs`, bytes transferred, and whether the handle was newly
+  created or reused within the run;
+- the `CURLcode` **name**, `CURLINFO_RESPONSE_CODE`, the tagged completion code,
+  and our own abort reason when there was one. The abort reason is the field that
+  makes a 504 diagnosable without guessing;
+- `CURLINFO_CONNECT_TIME` and `CURLINFO_APPCONNECT_TIME` on a slow call, since
+  that is what separates "the network is slow" from "TLS is slow" from "LOGIN is
+  slow";
+- `CURLOPT_ERRORBUFFER` on a failure, which is often the only readable
+  explanation.
+
+### What must never be logged, at any level
+
+- **Passwords, OAuth bearer tokens, app passwords, SSH private keys or
+  passphrases**, in any form. The concrete mechanism that makes this structural
+  rather than a discipline: pass credentials through `CURLOPT_USERNAME` and
+  `CURLOPT_PASSWORD`, **never embedded in the URL string**. Then no log line, no
+  `CURLINFO_EFFECTIVE_URL`, no error buffer and no exception message can carry
+  them, because they were never part of a string that gets printed. `net_guard`
+  already strips userinfo from an http URL for a related reason; this is the same
+  idea applied upstream.
+- **Message bodies, and message headers including Subject and From.** A Subject
+  is content. If a tenant needs to see it, it goes to the run console, which is
+  theirs, not to the journal, which is ours.
+- **Attachment bytes or filenames.**
+- **SEARCH criteria values**, per the verb-only rule above.
+- Mailbox names at info. They are tenant configuration and mostly harmless, but a
+  mailbox can be named after a customer, so debug.
+
+### `CURLOPT_VERBOSE` is a trap
+
+Turning it on prints the entire protocol dialogue, **including the LOGIN line
+with the password**, to stderr and therefore to the journal. It must not be
+reachable from a settings path.
+
+If a diagnostic mode is wanted, and it will be, implement it as a
+`CURLOPT_DEBUGFUNCTION` with a redactor: keep `CURLINFO_TEXT`,
+`CURLINFO_HEADER_IN` and `CURLINFO_HEADER_OUT`; **drop `CURLINFO_DATA_IN` and
+`CURLINFO_DATA_OUT` entirely**; and filter any line beginning `LOGIN`,
+`AUTHENTICATE`, `AUTH` or `PASS` down to its verb. Gate it behind an
+operator-only runner setting, default off, and log loudly at startup when it is
+on. Note that the runner's `runtime` ceilings are boot-time only for a
+documented reason; this one can hot-reload, since it is read per call, like the
+egress CIDR lists.
+
+### Metrics
+
+Counters per `(protocol, outcome class)` using the slug set from section 6, plus
+a histogram of **login time** and one of total call duration.
+
+The login histogram is not decoration. It is the measurement the slice-2
+cross-run handle cache decision rests on, and section 3 defers that decision
+explicitly on the grounds that we do not have the number yet. Shipping the
+counter in slice 1 is what makes the deferral honest rather than an excuse.
+
+### Tenant-facing run console
+
+Mirror the two existing precedents. `ctx.fetch` records refusals in a `blocked`
+list the tenant can see, and a filtered vector search warns in the run console
+when the scan cap bit rather than silently returning short. So:
+
+- a warning when a FETCH was **truncated** by the byte cap or by a partial range,
+  because a tenant silently receiving the first 160 bytes of a message and
+  believing it is the whole message is the mail-shaped version of the
+  `scan_capped` bug;
+- a warning when a session was poisoned and later commands were refused;
+- byte counts and durations, so a tenant can see their own budget being spent.
+
+---
+
+## Risk and effort summary
+
+| Item | Effort | Risk |
+|---|---|---|
+| Build integration, distro path | 1 day | Low. Depends on the trixie protocol-set measurement. |
+| Build integration, vendored path | 2 - 3 days | **Standing**, not one-off: we own curl and libssh2 CVE tracking forever. |
+| `runner_net` layer and its test wiring | 1 - 2 days | Low. Pure mechanical, and it is what makes everything else testable on the dev host. |
+| Handle and session lifecycle | 2 - 3 days | Medium. The failure mode of getting it wrong is cross-tenant, so the slice-1 design removes the risk by construction rather than by careful keying. |
+| Budget model, `transfer_budget.hpp`, xferinfo abort | 2 - 3 days | Low to medium. The arithmetic is pure and tested; the residual is the roughly 1 s abort granularity, which is documented rather than hidden. |
+| **IMAP parser** | **2.5 - 3 weeks plus a long tail** | **High, and the project's main risk.** Silent wrong answers, not errors. Needs its own slice and its own corpus. |
+| Error mapping | 2 days | Low. Pure, tested, and it has a worked example to copy. |
+| Observability and the redacting debug function | 2 days | Low, but the credential-logging failure mode is severe enough that the `CURLOPT_USERNAME` mechanism should be in the first commit, not retrofitted. |
+
+### Open questions for the other two lanes
+
+1. **[JS surface]** Mail work should be documented as belonging on `job` and
+   `cron` triggers, because a 2 s HTTP ceiling barely covers TLS plus LOGIN on a
+   remote server. Does the proposed surface make that obvious?
+2. **[JS surface]** Raw or RFC 2047-decoded header values, or both?
+3. **[JS surface]** `hasAttachments` does not ship until BODYSTRUCTURE is
+   interpreted. Is the surface shaped so adding it later is additive?
+4. **[security]** Mail credentials come from project secrets and nowhere else;
+   `netrc` and proxy environment variables are compiled out. Confirm the storage
+   and retrieval path.
+5. **[security]** The loopback allowance needed by the fake-server test fixture
+   must be test-only and unreachable from any settings path. Confirm the shape.
+6. **[security]** `CURLOPT_RESOLVE` is set from the guard's single approved
+   address, which is the curl equivalent of httplib's
+   `set_hostname_addr_map`. Confirm that is the intended pinning mechanism and
+   that the one-resolution-one-classification rule is preserved.
+7. **Product owner:** WebDAV is out of slice 1, as a consequence of
+   `CURL_DISABLE_HTTP`. Confirm.
+
+
+# Part 3
+
+# Spec part 3: security and tenancy for the multi-protocol host surface
+
+Scope: authorisation, egress, private destinations, credentials, TLS, process
+attack surface, abuse limits, audit. The JS surface shape and the libcurl option
+plumbing are other agents' parts; where a libcurl option is the *mechanism of a
+security control* it is named here, because the control is not implementable
+without it.
+
+Status: design. Nothing in this document is implemented.
+
+---
+
+## 0. The one decision everything else follows from
+
+**The tenant's JavaScript never names a host.**
+
+`ctx.fetch` takes a URL from the script, so its guard must police attacker-chosen
+input on every call: parse, resolve, classify every address, pin, fail closed.
+That machinery exists and works, but it is expensive and it is permanently one
+parser bug away from a bypass.
+
+The protocol surface does not have to work that way. Mail and file transfer
+destinations are *configuration*, not *arguments*: a tenant's support mailbox is
+the same host every run, and no legitimate function computes its IMAP server at
+runtime. So:
+
+> A project admin defines named **connections**. A function is granted a
+> connection by name in its policy. The script says
+> `ctx.mail('inbox_support').list(...)`, and the host resolves `inbox_support`
+> to a protocol, host, port, credential and TLS posture that the script cannot
+> see, influence or override.
+
+This is capability addressing rather than URL addressing, and it removes, by
+construction, the entire class of problems the `ctx.fetch` guard spends its
+effort on: no tenant-chosen hostname, no user-controlled scheme, no redirect
+chasing, no "the script built the URL from a document field". The SSRF guard is
+still needed (a project admin is a tenant, not us, and a connection's host is
+still a destination we must classify), but it is applied to a small, slow-moving,
+admin-authored set of destinations instead of to arbitrary per-call strings.
+
+Everything below assumes this model. If the JS-surface design instead exposes a
+host string to scripts, most of the controls in this document weaken to
+`ctx.fetch`'s level, and sections 2, 3 and 7 should be read as objections.
+
+**Rejected:** a `ctx.imap({host, user, pass})` free-form connector. It is what
+every "add IMAP to our serverless platform" ships, and it makes the host string
+tenant input, the credential tenant-visible, and the destination unauditable
+before the fact. It would also force the per-call guard to re-resolve per call,
+which is the rebinding window `net_guard` exists to close.
+
+---
+
+## 1. Authorisation
+
+### 1.1 Shape: reserved pseudo-collection, following `_files`
+
+Protocol access is granted through the **existing scope-rule machinery**, under a
+reserved pseudo-collection namespace:
+
+```json
+{"collection": "_conn:inbox_support", "ops": ["read", "list", "search"]}
+{"collection": "_conn:smtp_out",      "ops": ["insert"]}
+```
+
+This is the `_files` precedent (`kFilesPseudoCollection`) extended one step: the
+leading underscore is unshadowable because collection-create rejects
+`_`-prefixed names, and `:` is already reserved as the `qualify()` separator so
+it cannot occur in a real collection name either. `KeyScope::findRule` and its
+prefix glob work unchanged, which means:
+
+- one implementation of "may this principal do this", so connection access
+  cannot drift from collection access or file access;
+- the existing `components/ScopeRules.tsx` editor can already express it (it
+  edits `{collection, ops}` pairs), so the web UI needs a nicer presentation but
+  not a second grant model;
+- `rateLimitPerMin` and `expiresAt` on the scope apply to connection use for
+  free (see §7.5);
+- the floor is preserved with **no change at all**:
+  `builtinDefaultFunctionPolicy()` returns `KeyScope{}`, which has no rules, so
+  it grants no connection. Unreviewed code reaches no mailbox.
+
+**Rejected: a new rule kind** (`{protocol, host, accounts, ops}` as a parallel
+array). It is more expressive and it is the wrong trade: a second rule evaluator
+is a second place for a precedence bug, and the two would drift the first time
+someone adds a feature to one. It also duplicates the destination, which is
+already pinned down by the connection row, so the rule would be able to disagree
+with the thing it authorises.
+
+**Rejected: a single `_net` grant** ("may use protocols at all"). Too coarse to
+be useful: the consumer that needs two mailboxes needs one function to reach one
+of them, which a single flag cannot say.
+
+### 1.2 The `*` hole, which must be closed before this ships
+
+`collMatches("*", x)` is true for every `x`, including `_files`. So an existing
+policy carrying `{"collection": "*", "ops": [...]}` would, the moment this
+feature lands, **silently gain every connection in the project**. That is exactly
+the retroactive widening `mergeForCodePush()` exists to prevent, arriving through
+a different door.
+
+Requirement: a rule matches a connection only if its `collection` pattern
+*literally begins with* `_conn:`. Concretely, a new sibling of
+`requireCapabilityCore`:
+
+```
+requireConnectionCapability(p, project, connName, op):
+    requireProjectAccess(p, project)
+    if (!p.scope) -> permit            // unscoped principal, as today
+    rule = p.scope->findRule("_conn:" + connName, op)
+    if (!rule) -> 403
+    if (!rule->collection.starts_with("_conn:")) -> 403   // `*` must not reach here
+    rate limit on p.id, as requireCapabilityCore does
+```
+
+It shares the rule-lookup and rate-limit body with `requireCapabilityCore` so
+there is still one implementation; the extra line is the explicitness gate. A
+test must assert that a `*` policy and a `_c*` policy both fail to reach a
+connection, and that `_conn:*` succeeds.
+
+**Pre-existing finding, outside this feature and worth reporting separately:**
+the same `*` behaviour already grants `_files`. An API key or function policy
+written as `{"collection": "*", "ops": ["read"]}` can read every project file
+today, which is probably not what whoever wrote it understood. Not mine to fix
+here, but the same gate would close it.
+
+### 1.3 Op vocabulary: reuse `KeyOp`, do not invent one
+
+Because a connection has exactly **one** protocol and **one** host, the existing
+six ops are unambiguous per connection:
+
+| KeyOp | IMAP / POP3 | SMTP | FTP / FTPS / SFTP | WebDAV |
+|---|---|---|---|---|
+| `list` | LIST mailboxes, UID enumeration | - | directory listing | PROPFIND |
+| `read` | FETCH a message | - | download | GET |
+| `search` | IMAP SEARCH | - | - | REPORT |
+| `insert` | APPEND | **send** | **upload** | PUT / MKCOL |
+| `update` | flags, move, rename | - | rename | PROPPATCH / MOVE |
+| `delete` | STORE \Deleted + EXPUNGE | - | delete | DELETE |
+
+`insert` is the dangerous one everywhere: it is "send mail" and "upload bytes",
+i.e. the egress channel. An admin granting read-only grants
+`read`+`list`+`search` and the UI should offer that as a preset, with `insert`
+visually separated and labelled as data egress.
+
+Two protocol operations have no honest KeyOp mapping and are therefore **not
+exposed at all** in v1: IMAP IDLE (a long-held connection, incompatible with a
+pooled runtime and a wall budget) and arbitrary command passthrough
+(`ctx.imap(...).raw("...")`). Passthrough would make the op table a lie, since
+one grant would buy every command.
+
+### 1.4 Who grants what
+
+Three separate authorities, deliberately not collapsed:
+
+1. **Operator** (host, not API): which protocols exist at all. Build-time
+   (§6.2) plus a runtime global setting `function_protocols_allowed`, default
+   `[]`. An operator who never wants SMTP out of their box sets nothing and no
+   project admin can overrule it. Also `function_private_destinations` (§3).
+2. **Admin key** (`requireAdmin`): create, update and delete connection
+   definitions, including the credential reference, the TLS posture and the
+   `private_ok` flag. Admin-only and not project-manage, matching project
+   secrets (`handlers/project_secrets.cpp`) and function policy: a connection
+   row carries a destination and a credential, which is egress authority, not
+   project housekeeping.
+3. **Admin key** again: granting `_conn:<name>` in a function's policy. Function
+   policy is already admin-only, so this needs no new rule.
+
+A project-manage caller may **list** connection names and protocols (it needs to
+write functions against them) and may not see hosts, credentials or TLS
+exceptions. Rationale: the name is what the script uses; the destination is not
+the script author's business, and hiding it keeps a leaked project-manage key
+from mapping the operator's internal network.
+
+### 1.5 Storage
+
+`<project>:vectorapi_connections`, one document per connection, **encrypted**,
+reusing the `ProjectSecretStore::ensure` pattern (service-prefixed, no leading
+underscore because `_`-prefixed collections misroute when project-qualified).
+Not in the collection registry, so the documents API and `ctx.collections` both
+404 it even under a policy granting every collection, exactly as
+`vectorapi_secrets` is handled. Dropped by `dropAll` on project delete, or a
+recycled project name inherits the previous tenant's mail server.
+
+No GET ever returns a credential reference's *value*; the reference *name* is
+returned to admin only.
+
+### 1.6 Validation on write
+
+Follow the existing function-push discipline: **validate on a runner before
+storing**. The shape checks (protocol in the operator allow-list, port in range,
+hostname charset, TLS posture coherent, credential reference exists, host literal
+not in never-relax space per §3.3) are pure and run in the server. Reachability
+is *not* required at write time: a mail server being down must not stop an admin
+from fixing its password. Instead there is an explicit admin-only
+`POST /api/v1/projects/{p}/connections/{name}/test`, proxied to a runner, which
+performs one real connect+auth+NOOP and returns a classified result. That keeps
+libcurl in exactly one binary (§6.4) and makes the egress probe an audited,
+admin-gated act rather than a side effect of a settings write.
+
+With no healthy runner, `/test` is 503. A connection *definition* write is still
+accepted, because its validation is pure.
+
+### 1.7 Routes
+
+```
+GET    /api/v1/projects/{p}/connections            project-manage: names+protocols
+                                                   admin: full rows, credentials masked
+POST   /api/v1/projects/{p}/connections            admin
+GET    /api/v1/projects/{p}/connections/{name}     admin (project-manage: masked)
+PUT    /api/v1/projects/{p}/connections/{name}     admin
+DELETE /api/v1/projects/{p}/connections/{name}     admin
+POST   /api/v1/projects/{p}/connections/{name}/test admin, proxied to a runner
+```
+
+`api/openapi.json` and `api/llms.txt` must be updated in the same change.
+
+---
+
+## 2. Egress
+
+### 2.1 The discipline, restated for non-HTTP
+
+The four rules from `net_guard.hpp` carry over unchanged and must be visibly the
+same code:
+
+1. **Fail closed.** Unparseable host, unparseable port, resolution failure, a
+   name resolving to nothing: refused.
+2. **Classify every address**, not the first. Reuse
+   `blockReasonForAddresses()` as-is.
+3. **Resolve exactly once**, at connect time, in the component that owns the
+   policy.
+4. **Pin the approved address** and connect to it, rather than letting the
+   transport re-resolve. Re-resolving is the rebinding window.
+
+Resolution happens at connect time, not at definition time: a DNS answer cached
+from a write hours earlier is a stale authorisation, and the point of rule 3 is
+that the address that was *classified* is the address that is *connected to*,
+which only holds if they are the same lookup.
+
+### 2.2 Pinning with libcurl, exactly
+
+Per connection attempt, on a fresh easy handle:
+
+```
+CURLOPT_RESOLVE        = ["<host>:<port>:<approved_addr>"]
+CURLOPT_DNS_CACHE_TIMEOUT = 0          // no cross-attempt DNS cache
+CURLOPT_URL            = "<scheme>://<host>:<port>/..."   // the NAME
+CURLOPT_PROTOCOLS_STR  = "<the one protocol of this connection>"
+CURLOPT_REDIR_PROTOCOLS_STR = ""       // nothing
+CURLOPT_FOLLOWLOCATION = 0
+CURLOPT_PROXY          = ""            // see below, this one is load bearing
+CURLOPT_NETRC          = CURL_NETRC_IGNORED
+CURLOPT_FRESH_CONNECT  = 1
+CURLOPT_FORBID_REUSE   = 1
+CURLOPT_NOSIGNAL       = 1
+```
+
+`CURLOPT_RESOLVE` installs a pre-populated DNS cache entry, so libcurl does not
+resolve the name at all. The URL stays the **name**, so SNI, certificate
+verification and the SMTP/IMAP greeting all use the name the policy approved,
+and the address map is what is dialled. This is the same pairing as the existing
+`set_hostname_addr_map` + name-based origin in `ctx.fetch`.
+
+The `CURLOPT_RESOLVE` entry is host **and port** specific, so it must be
+installed for every port the attempt can reach. That matters for FTP (§2.4).
+
+Three differences from httplib that are easy to get wrong:
+
+- **libcurl reads proxy environment variables** (`http_proxy`, `all_proxy`,
+  `ALL_PROXY`, `no_proxy`); httplib does not, and the existing `ctx.fetch`
+  comment relies on that. A proxy would reroute an approved destination to an
+  unapproved one and defeat the pin entirely. `CURLOPT_PROXY = ""` must be set
+  explicitly on every handle, and a test must assert that setting `all_proxy` in
+  the runner's environment does not change where a connection goes.
+- **No shared handle, no connection reuse across attempts.** A `CURLSH` or a
+  reused easy handle would let one tenant's authenticated IMAP connection be
+  picked up for another tenant's request to the same host, which is a
+  cross-tenant credential and data leak. `FRESH_CONNECT` + `FORBID_REUSE` + a
+  handle per attempt. The cost is a TLS handshake per operation; that is the
+  correct price.
+- **`CURLOPT_NOSIGNAL = 1` is mandatory** in a threaded process, or the
+  resolver's alarm-based timeout fires a signal in an unrelated thread.
+
+### 2.3 Budget, because a blocking call cannot be interrupted
+
+Same lesson as `resolveEmbedBudget()`: while libcurl is inside a connect or a
+read, the QuickJS interrupt handler never runs, so the wall deadline is noticed
+only on return. Host timeouts *are* the enforcement.
+
+```
+CURLOPT_CONNECTTIMEOUT_MS = connect share of the remaining budget (<= half)
+CURLOPT_TIMEOUT_MS        = remaining budget
+CURLOPT_LOW_SPEED_LIMIT / CURLOPT_LOW_SPEED_TIME
+```
+
+The connect/read split and the 1 s-per-phase floor should come from
+`functions/embed_budget.hpp` or a sibling built on the same reasoning, not a
+fresh hand-rolled calculation: the 14314 ms bug was precisely an additive
+connect timeout outside the budget, and this surface has the same shape.
+
+`LOW_SPEED_LIMIT`/`TIME` is the extra one protocols need and HTTP mostly does
+not: a mail server that trickles one byte per second stays under `TIMEOUT_MS`
+per byte forever. Without it a hostile destination holds a pooled runtime for
+the entire wall budget on purpose, every run.
+
+### 2.4 The second-connection problem: FTP data channels
+
+This is the genuine hole in any pin-the-address scheme, and it has three
+distinct shapes.
+
+**Active mode (PORT / EPRT).** The client opens a listening socket and the server
+connects back. This means an inbound connection to the process running untrusted
+JS, on a port advertised in cleartext. **Refused outright, always.**
+`CURLOPT_FTPPORT` is never set and `CURLOPT_FTP_USE_EPRT = 0`. There is no
+configuration that enables it. A customer whose FTP server requires active mode
+gets SFTP or nothing; I am not opening a listener in this process for anybody.
+
+**Passive mode (PASV / EPSV).** The server replies with an address and a port,
+and libcurl dials it. The address is server-chosen, which is the classic
+FTP-bounce SSRF: a hostile or compromised FTP server answers
+`227 ... (127,0,0,1,x,y)` and the data connection lands on the runner's loopback,
+where our API and the database listen. The pin on the control connection does
+nothing for it.
+
+The mitigation is **`CURLOPT_FTP_SKIP_PASV_IP = 1`**: libcurl discards the IP in
+the PASV/EPSV reply and reuses the *control connection's* address, taking only
+the port. This has been the libcurl default since 7.74.0, but it must be set
+explicitly, because a control whose correctness depends on an upstream default
+is a control that disappears in a refactor or a vendored build. With it:
+
+- the data connection goes to the same address the guard approved and pinned;
+- no second DNS resolution happens anywhere;
+- the server-chosen component is reduced to **the port, on an
+  already-approved host**.
+
+**Residual, stated plainly: an FTP or FTPS connection grants the function reach
+to an arbitrary TCP port on the approved host.** A hostile FTP server can make
+us connect to port 22, 6379, 5432, 9200 or 9004 *on itself*. Against a public
+FTP server that is near-worthless (the attacker already owns that host). Against
+a host inside the customer's network it is a port-scan and a blind data-write
+primitive on exactly one machine. Partial mitigations, all of which I would ship:
+
+- refuse a PASV port below 1024 (where SSH, SMTP and the LDAP/SMB family live);
+  honest about the limit, since Redis, Postgres and our own database are above
+  it;
+- refuse a PASV port equal to the control port's host's *known* service ports we
+  care about, specifically the configured `database.address` port and the
+  runner's and server's own ports, as a cheap backstop;
+- the kernel-level `IPAddressDeny` in §6.4, which does not care which connection
+  of which protocol is dialling;
+- **prefer SFTP**: SFTP multiplexes everything over one TCP connection and has
+  no data-channel hole at all. The UI should say so where an admin picks a
+  protocol.
+- **FTP and FTPS to a private destination require an extra operator opt-in**
+  beyond §3's allow-list, because that is the combination where the residual has
+  teeth. Setting `private_ok` on an FTP connection is refused unless the global
+  `function_ftp_private_destinations_allowed` is true, and the setting's
+  description says what it grants: reach to any high port on that host.
+
+**FTPS control vs data.** `CURLOPT_USE_SSL = CURLUSESSL_ALL`, never
+`CURLUSESSL_CONTROL`: encrypting the login and then shipping the file in
+cleartext is a posture nobody intends and the option names make easy to pick by
+accident.
+
+**Everything else is single-connection.** IMAP, POP3, SMTP and SFTP open no
+second connection. WebDAV/CalDAV is HTTP and its "second connection" is a
+redirect, which §2.2 bans outright (`FOLLOWLOCATION = 0`,
+`REDIR_PROTOCOLS_STR = ""`). A WebDAV server that 301s is a configuration error
+the admin fixes in the connection's URL, not something we chase.
+
+### 2.5 Where the guard runs
+
+In the runner (or, per §6.4's recommendation, in the runner before it hands the
+request to the helper), using `svapi::functions` directly: `runner_host` already
+links `vectorapi_core`, so `SsrfPolicy`, `blockReasonForAddresses` and
+`currentSsrfPolicy()` are available without a new dependency. The policy
+snapshot already hot-reloads from settings; connection checks read the same
+snapshot a `ctx.fetch` in the same run would.
+
+The resolver is `getaddrinfo` with `AI_ADDRCONFIG`, the same call `ctx.fetch`
+uses, so a destination that is blocked for fetch is blocked for IMAP without two
+code paths agreeing by coincidence.
+
+---
+
+## 3. Private addresses
+
+### 3.1 Why `function_egress_allow_private` cannot be reused
+
+It is global, it is shared with `ctx.fetch`, and it relaxes
+`privateBlockedCidrs()` **including loopback**, where our own API and the
+database listen. Honouring it here would mean: an operator who turned it on last
+year so one webhook could reach an internal HTTP service has, on upgrade,
+silently permitted every project's IMAP and FTP connections to reach 127.0.0.1
+and the whole RFC1918 space. That is the "an operator adding one CIDR must not
+silently reopen loopback" failure mode, in reverse.
+
+**The protocol surface does not read `function_egress_allow_private` at all.**
+This divergence is deliberate and must be stated in the settings UI next to the
+flag, or someone will "unify" them.
+
+### 3.2 Two gates, ANDed
+
+**Operator gate.** A new global setting:
+
+```json
+"function_private_destinations": ["10.20.0.0/16", "192.168.40.0/24"]
+```
+
+Default `[]`. These are the private ranges this *host* may reach over the
+protocol surface at all. Parsed with `parseCidr()`; an entry that does not parse
+is skipped and logged, following `SsrfPolicy::fromStrings`'s `invalid` list, so a
+typo is a visible hole rather than a silent one.
+
+**Project gate.** Per connection: `"private_ok": true`. Admin-only, per
+destination, and meaningless on its own.
+
+A connection attempt to address `A` is permitted iff:
+
+```
+   not neverRelaxable(A)                       // §3.3, unconditional
+&& ( !builtinPrivate(A)                        // public: ordinary case
+     || ( connection.private_ok
+          && A inside union(function_private_destinations) ) )
+```
+
+Both gates, ANDed. An operator who opens `10.20.0.0/16` has not thereby exposed
+it to every project: each connection still needs its flag and each function still
+needs its `_conn:` grant. A project admin who sets `private_ok` on a connection
+pointing at `10.99.0.1` gets a refusal, not reach, because the operator never
+opened that range.
+
+Every resolved address is checked, not one of them, per §2.1 rule 2. A
+split-horizon name that answers with one permitted and one forbidden address is
+refused.
+
+### 3.3 The never-relaxable set
+
+No setting, flag, project override or connection field relaxes these, for the
+protocol surface:
+
+- `127.0.0.0/8`, `::1/128` - **loopback, unconditionally.** There is no
+  legitimate "my mail server runs on the runner's loopback" case; if it did, it
+  would have a real address. The runner's loopback holds our API, the database
+  and the runner's own authenticated `/run` endpoint. This is the one place the
+  protocol surface is *stricter* than `ctx.fetch`, and intentionally so.
+- `169.254.0.0/16`, `fe80::/10` - link-local and the cloud metadata endpoint.
+- multicast, broadcast, `0.0.0.0/8`, reserved space.
+- the IPv6 spellings of an IPv4 destination: `::ffff:0:0/96`, `64:ff9b::/96`
+  (NAT64), `2002::/16` (6to4). `SsrfPolicy::isBlocked` already decomposes
+  v4-mapped addresses; the transition prefixes are in
+  `defaultBlockedCidrs()`.
+
+Enforcement is layered on purpose:
+
+1. **Write time:** a connection whose host is an address literal inside the
+   never-relax set is refused with 422, and a `function_private_destinations`
+   entry that *contains or overlaps* any never-relax range is refused at write
+   time too (so nobody configures `0.0.0.0/0` and calls it a private range).
+2. **Connect time:** re-checked against the live policy, fail closed. A
+   hand-edited settings document or a database row written outside the API must
+   not be able to widen anything. This is the control; (1) is user experience.
+3. **Kernel:** `IPAddressDeny` on the unit (§6.4). Our C++ can have a bug; eBPF
+   does not care what our C++ thinks.
+
+### 3.4 Rejected alternatives
+
+- **A per-project `allow_private` boolean** without the operator list. The
+  project admin is a tenant; letting a tenant open RFC1918 on the operator's
+  host is the wrong direction of trust, and on a shared host it means any
+  customer can scan the operator's LAN.
+- **Allow-listing by hostname instead of CIDR.** DNS is attacker-influenced for
+  any name the admin does not control, and the check has to be on the resolved
+  address anyway. A name allow-list reads safer than it is.
+- **Reusing the `ctx.fetch` flag with loopback carved out.** Tempting, one less
+  setting. Rejected because the resulting flag means two different things in two
+  places, which is how a security setting ends up misunderstood by the person
+  setting it.
+
+---
+
+## 4. Credentials
+
+### 4.1 The reference, not the value
+
+A connection stores a *reference*:
+
+```json
+{
+  "name": "inbox_support",
+  "protocol": "imaps",
+  "host": "mail.acme.example",
+  "port": 993,
+  "auth": { "username": "support@acme.example", "password_secret": "IMAP_SUPPORT_PW" },
+  "tls": { ... },
+  "private_ok": false
+}
+```
+
+`password_secret` names a project secret. Resolution happens entirely host-side
+at connect time, through `ProjectSecretStore` plus the existing
+`SVAPI_FN_<project>__<NAME>` host-environment precedence from
+`functionEnvFor()`: **the host variable wins**, so an operator keeps the
+break-glass override that a stolen API credential cannot shadow, and the rule is
+the same one that already governs `ctx.env` rather than a second precedence
+nobody remembers.
+
+The value is never returned by any route, never placed in a JS value, and never
+reachable from the script. The script holds the string `"inbox_support"`.
+
+Several named accounts per project fall out for free: the consumer needing two
+mailboxes defines `inbox_support` and `inbox_billing`, each with its own
+`password_secret`, and a function can be granted one and not the other
+(`{"collection": "_conn:inbox_support", "ops": ["read","list"]}`). That is the
+case that a `ctx.imap(host, user, pass)` design cannot express as a *grant* at
+all.
+
+### 4.2 A problem in what exists today: `ctx.env` exports every stored secret
+
+`functionEnvFor()` merges **all** of a project's stored secrets into `ctx.env`.
+So a password stored as a project secret is, today, readable by the tenant's
+JavaScript. If credentials are stored that way, "the tenant's JS never sees the
+secret value" is false.
+
+In many deployments the function author and the project admin are the same
+person, so this is tolerable - but it must not be *assumed*, and the distinction
+between "an admin's credential" and "a script's configuration" is exactly what a
+multi-tenant platform sells.
+
+**Required change:** a per-secret `exportable` flag on the secret row, default
+`true` (every existing secret keeps working, and the host-variable path is
+untouched). A secret created through the connection editor defaults to
+`exportable: false`. `functionEnvFor()` filters on it; the credential resolver
+ignores it (a non-exportable secret is still usable as a connection credential,
+which is the whole point). Also: a host variable is currently always exported,
+so an operator wanting a non-exportable host credential needs a second prefix
+(`SVAPI_FNC_<project>__<NAME>`, credential-only) or the credential must live as a
+stored secret. I would ship the second prefix; the alternative is telling
+operators their break-glass override is tenant-readable.
+
+If the `exportable` flag is judged out of scope, then this document's claim must
+be downgraded to "the tenant's JS does not *need* to see the value", and the
+connection editor must warn that a stored credential is script-readable. I would
+rather ship the flag.
+
+### 4.3 SSH keys for SFTP
+
+A private key is bytes, not a short string, and libcurl's
+`CURLOPT_SSH_PRIVATE_KEYFILE` takes a **path**. It must never be written to
+persistent storage.
+
+Mechanism: store the key as a non-exportable project secret (or as a project
+file with a restricted name, if size argues for it), then at connect time
+`memfd_create()` it, write the bytes, and pass `/proc/self/fd/<n>` as the path.
+The fd is closed when the attempt ends and the memory never touches a
+filesystem. Fallback, only if `memfd_create` is unavailable: a 0600 file in the
+unit's `RuntimeDirectory=` (a tmpfs), unlinked immediately after `open`.
+`CURLOPT_KEYPASSWD` comes from a second secret reference.
+
+**Host key verification is mandatory and libcurl will not do it for you.**
+libcurl verifies an SSH host key only if told to: `CURLOPT_SSH_KNOWNHOSTS` or
+`CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256`. With neither, it connects to whatever
+answers, which makes SFTP's confidentiality worthless against anyone on the
+path. A connection of protocol `sftp` is therefore **refused at definition time
+unless it carries `host_key_sha256`**, and `CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256`
+is always set. The `/test` route (§1.6) should report the server's actual
+fingerprint on a mismatch so an admin can pin it deliberately on first setup,
+and that report is admin-only.
+
+There is no "accept any host key" option. Not a setting, not a flag.
+
+### 4.4 Never logged, never surfaced
+
+Never in any log, run console, audit record, error message, metric label or
+exception text:
+
+- passwords, SSH private keys, key passphrases, OAuth tokens;
+- the SASL/AUTH exchange in either direction, base64 or otherwise;
+- message bodies, headers, subjects, attachment bytes, file contents;
+- full recipient or sender addresses (domains only - see §8);
+- a URL containing userinfo.
+
+Mechanical consequences, each of which is a way this leaks by accident:
+
+- **Credentials go in `CURLOPT_USERNAME` / `CURLOPT_PASSWORD`, never in the
+  URL.** `user:pass@host` in `CURLOPT_URL` ends up in libcurl's error strings,
+  in `CURLINFO_EFFECTIVE_URL`, and in anything that logs the URL. The existing
+  `parseHttpUrl` already strips userinfo for the same class of reason.
+- **`CURLOPT_VERBOSE = 0` in production, and no `CURLOPT_DEBUGFUNCTION` wired to
+  the run console or to spdlog.** A verbose trace of an IMAP session is the
+  mailbox contents and the login line. If a debug callback is wired for
+  diagnostics, it must whitelist `CURLINFO_TEXT` and drop
+  `HEADER_IN`/`HEADER_OUT`/`DATA_*`/`SSL_DATA_*`, be behind a build flag, and be
+  off by default.
+- **`CURLOPT_ERRORBUFFER` text is not returned to the tenant.** The script gets
+  a stable classified code: `conn_unreachable`, `conn_auth_failed`,
+  `conn_tls_failed`, `conn_denied`, `conn_timeout`, `conn_too_large`,
+  `conn_quota`, `conn_protocol_error`. The detail goes to the run log with the
+  `run_id`, which is the existing rule that function error text never reaches
+  the caller. Also: do not echo the server's greeting banner or its rejection
+  text verbatim to the script - mail servers quote submitted addresses back, and
+  SMTP rejection text is a user-enumeration oracle.
+- A secret must not reach `spdlog` through a `FunctionRunLog::console` entry
+  either; the console is tenant-visible in the web UI.
+
+---
+
+## 5. TLS
+
+### 5.1 The floor, non-negotiable
+
+```
+CURLOPT_SSL_VERIFYPEER = 1        // no global off switch exists
+CURLOPT_SSL_VERIFYHOST = 2
+CURLOPT_SSLVERSION     = CURL_SSLVERSION_TLSv1_2   // minimum
+CURLOPT_USE_SSL        = CURLUSESSL_ALL            // for STARTTLS protocols
+CURLOPT_CAINFO / CAPATH = explicit distro path
+```
+
+TLS 1.2 rather than 1.3 as the floor: real mail servers lag, and a floor nobody
+can meet gets turned off. 1.0/1.1 are refused.
+
+**`CURLUSESSL_ALL`, never `CURLUSESSL_TRY`.** `TRY` attempts STARTTLS and
+*silently continues in cleartext* if the server does not offer it, which is a
+password on the wire and looks identical to success. For a STARTTLS port (143,
+110, 587, 21) `ALL` makes TLS mandatory and fails the connection otherwise.
+Implicit-TLS ports (993, 995, 465, 990) are preferred and the UI should default
+to them.
+
+**Cleartext protocols.** `imap://`, `pop3://`, `smtp://` and `ftp://` with a
+password are refused: the credential is the project's, the wire is not ours, and
+"it is on our LAN" is not an argument I will accept in a config file. If a
+customer's ancient FTP box genuinely cannot do FTPS, that is a case to decline
+rather than a flag to add. If the flag is added anyway over my objection, it must
+be operator-level (not project-level), named for what it does
+(`function_allow_cleartext_credentials`), default off, and restricted to
+`private_ok` destinations.
+
+### 5.2 The CA bundle
+
+The system bundle (`ca-certificates` on Debian 13), set **explicitly** via
+`CURLOPT_CAINFO`/`CURLOPT_CAPATH` from the packaged path rather than left to
+libcurl's compiled-in default. A vendored or rebuilt libcurl with a different
+default would otherwise change trust silently, and a missing bundle would turn
+into "verification passes because there is nothing to verify against" in some
+builds.
+
+### 5.3 Self-signed and private-CA mail servers, which are the real world
+
+Three levels, in the order an admin should try them. None of them is
+`VERIFYPEER = 0`, which is **not offered at all**: it is one checkbox that
+converts every TLS guarantee into theatre, and it is the thing every similar
+product regrets shipping.
+
+**(a) Private CA or self-signed certificate as a trust anchor.** The admin
+uploads the PEM as a **project file** (`file_store.hpp`, which already exists for
+exactly this class of tenant-specific blob) and the connection references it:
+
+```json
+"tls": { "ca_file": "acme-mail-ca.pem" }
+```
+
+At connect time the runner loads the file through `FileStore` and sets
+**`CURLOPT_CAINFO_BLOB`** - a memory blob, so no temp file exists at any point.
+Verification stays fully on; the trust set is just this one anchor instead of the
+system bundle, which is *narrower* than the default, not weaker. A self-signed
+leaf works here as its own anchor. This covers the large majority of real cases
+and is the answer the UI should push.
+
+Note: the CA PEM is a project file and so is reachable by `ctx.files` under a
+`_files` read grant. That is a public certificate, so it is not a secret, but the
+file name should be conventional (`*-ca.pem`) and the UI should not let an admin
+accidentally upload a *private key* here.
+
+**(b) Public-key pinning.** `"tls": {"pin_sha256": "..."}` ->
+`CURLOPT_PINNEDPUBLICKEY = "sha256//..."`. Checked *in addition* to chain
+verification, so it tightens rather than replaces. Useful with (a); useless on
+its own against a self-signed cert, because the chain still fails. The UI must
+not present it as an alternative to (a).
+
+**(c) Hostname-check exception**, for the genuinely common case of a self-signed
+certificate whose CN/SAN does not match the hostname (`mail.local`, an IP
+literal, a cert minted in 2014):
+
+```json
+"tls": { "ca_file": "acme-mail.pem", "skip_hostname_check": true }
+```
+
+-> `CURLOPT_SSL_VERIFYHOST = 0`, with `VERIFYPEER` still 1 against the pinned
+anchor. The connection is then authenticated by "presents exactly this
+certificate chain" and not by "its name matches", which, combined with the
+address pin from §2.2, is a defensible posture: we dial a specific address and
+require a specific anchor.
+
+**How it cannot be set accidentally:**
+
+1. **Structurally impossible alone.** `skip_hostname_check: true` is refused with
+   422 unless the same connection carries `ca_file` or `pin_sha256`. There is no
+   way to express "trust the system bundle and ignore the name", which would be
+   the genuinely dangerous combination (any valid certificate for any domain
+   would then pass).
+2. **Per destination only.** It is a field on one connection row. There is no
+   global, no per-project and no per-run equivalent, and the script cannot set
+   it.
+3. **Admin only**, like every other connection field.
+4. **Visible after the fact.** The connection list returns
+   `tls_posture: "weak_hostname_check"` for it, the web UI renders a warning
+   badge, and every audit record for that connection carries the flag (§8), so
+   "find every connection running with a relaxed check" is one query rather than
+   an archaeology exercise.
+5. Audited at the moment it is set, with the acting key id.
+
+I deliberately did **not** add a confirmation word or a `i_understand: true`
+sibling field. Those get copy-pasted within a week and buy nothing; the
+structural requirement in (1) is the control that actually holds.
+
+---
+
+## 6. Attack surface
+
+### 6.1 What linking libcurl actually adds
+
+A correction to the premise first: `runner_host` already links `vectorapi_core`,
+and therefore the database client, gRPC, protobuf, httplib and OpenSSL. The
+process executing untrusted JS is not "QuickJS plus an HTTP client" today; it is
+QuickJS plus a gRPC stack, which is a larger C++ surface than libcurl. So
+libcurl is an increment, not a category change. That does not make it free.
+
+New code paths that parse **hostile server input**, in roughly descending risk:
+
+- **libssh2** (SFTP). The outlier. A smaller, less-fuzzed codebase than OpenSSL
+  with a steady history of memory-safety CVEs in key exchange and packet
+  parsing, processing attacker-controlled bytes *before* authentication
+  completes. If one thing here argues for process separation, it is this.
+- **libcurl's protocol state machines**: IMAP response/literal parsing, SMTP
+  multiline replies, POP3, FTP reply parsing and the PASV/EPSV address parser.
+  Server-driven.
+- **SASL / authentication mechanisms**: NTLM (has had buffer bugs), GSSAPI/krb5
+  (very large), DIGEST-MD5. None of it is needed for the target use cases.
+- **libidn2** - IDNA processing of hostnames, and with it homograph/confusable
+  destinations. Admin-supplied here, so lower risk than in `ctx.fetch`, but a
+  destination that *looks* like one host and resolves as another defeats human
+  review of a connection row.
+- **zlib / brotli / zstd** - decompression, i.e. memory amplification from a
+  server-controlled stream.
+- **nghttp2, libpsl, c-ares** - not needed.
+- **`file://`** - if enabled, a URL scheme that reads the runner's filesystem.
+
+Resource-level exposure, independent of memory safety: a blocking curl call pins
+a pooled QuickJS runtime for its duration and cannot be interrupted (§2.3), and
+N slow connections starve the pool exactly as N slow jobs did before the job
+lane existed.
+
+### 6.2 Build-time reduction
+
+Package a purpose-built libcurl for this (a static, private build in
+`packaging/`, not the distro's general-purpose shared one, which enables
+everything):
+
+```
+--disable-file --disable-ldap --disable-ldaps --disable-dict --disable-telnet
+--disable-tftp --disable-gopher --disable-rtsp --disable-mqtt --disable-smb
+--disable-smbs --disable-ntlm --disable-ntlm-wb --disable-ares
+--disable-alt-svc --disable-hsts --disable-netrc --disable-doh
+--without-gssapi --without-libgsasl --without-brotli --without-zstd
+--without-libpsl --without-nghttp2 --without-nghttp3
+--with-openssl  --enable-imap --enable-smtp --enable-pop3 --enable-ftp
+```
+
+`--disable-file` and `--disable-smb` and the LDAP pair are the important ones:
+each is a URL scheme that turns a protocol mix-up into local file read or an
+internal-service request. `CURLOPT_PROTOCOLS_STR` per handle (§2.2) is the
+runtime backstop, but a scheme that is not compiled in cannot be reached by any
+bug in our option setting.
+
+`--enable-sftp` (libssh2) **only if** §6.4's recommendation is followed; if
+protocol work stays in the runner process, I would ship without SFTP in v1 and
+say so, rather than put libssh2 in the process that holds every project's
+secrets.
+
+`curl_global_init()` exactly once, before any thread starts.
+
+### 6.3 Runtime hardening of the handle
+
+Already listed in §2.2 and §5.1. Additionally: `CURLOPT_MAXFILESIZE_LARGE` plus
+a hard stop in the write callback (§7.2), `CURLOPT_MAXREDIRS = 0`,
+`CURLOPT_HTTPAUTH`/`CURLOPT_LOGIN_OPTIONS` restricted to the mechanisms needed
+(`AUTH=PLAIN`/`LOGIN` over TLS, `XOAUTH2` where used), never
+`CURLAUTH_ANY` - which would let a server negotiate the process into the NTLM or
+GSSAPI code paths.
+
+### 6.4 Recommendation: a separate helper process. Yes.
+
+**Ship protocol work in a third binary, `smartbotic-vectorapi-netd`, from v1.**
+One per runner host, reached over a unix socket, speaking a small JSON protocol.
+Not because defence in depth is nice, but for three specific reasons, the second
+of which is functional rather than security:
+
+1. **It is the only place a kernel-enforced destination ban can live.** A
+   dedicated systemd unit can carry
+
+   ```
+   IPAddressDeny=127.0.0.0/8 ::1/128 169.254.0.0/16 fe80::/10
+   RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
+   PrivateDevices=yes  ProtectSystem=strict  ProtectHome=yes
+   NoNewPrivileges=yes MemoryDenyWriteExecute=yes
+   User=svapi-netd
+   ```
+
+   `IPAddressDeny` is eBPF, in the kernel, and it does not care whether our
+   guard has a bug, whether a PASV reply slipped past `SKIP_PASV_IP`, or whether
+   someone hand-edited a settings row. It is the strongest statement available
+   about §3.3's never-relaxable set, and it is simply not expressible for the
+   runner process, which *must* reach the database and may legitimately reach
+   loopback.
+
+2. **A hung protocol call becomes killable.** This is the argument I find
+   decisive on engineering grounds alone. In-process, a blocking libcurl call
+   holds a pooled QuickJS runtime until a timeout we hope we set correctly; the
+   interrupt handler cannot touch it. Out of process, the runner has a socket
+   with its own deadline and can `SIGKILL` the helper, release the lease and
+   answer the run honestly. The `resolveEmbedBudget()` bug (10 s budget, 14314 ms
+   run) is the same failure mode and it cost a release to find; protocols are
+   worse, because mail servers hang for a living.
+
+3. **The blast radius of a libssh2 or libcurl memory bug stops before the
+   secrets.** The helper is handed the credential for the connection it is
+   servicing right now, in the request. It holds no secret store, no database
+   client, no other project's anything, and - because the runner resolves and
+   passes the **pinned address** - it needs no resolver at all. Compromising it
+   buys one tenant's one credential and a socket that cannot reach loopback.
+   Compromising the runner today buys every project's secrets.
+
+Division of responsibility, which also keeps the one-resolution rule intact:
+
+- **Runner**: authorisation (`requireConnectionCapability`), connection lookup,
+  credential resolution, DNS resolution + classification + the §3 gates, budget
+  computation, quota checks, audit writes. Everything policy.
+- **netd**: given `{protocol, host, port, pinned_addr, username, password,
+  tls_blob, limits, operation}`, perform exactly that one operation and return
+  bytes and a classified result. No DNS, no database, no settings, no policy.
+  It cannot widen anything, because it is told the answer rather than asked the
+  question.
+
+Costs, honestly: a third binary, a third `.deb`, a socket protocol and its
+versioning, one more thing an operator can fail to install (and the existing
+"installing the runner does not enable functions" trap repeats itself - netd
+absent must mean the protocol surface answers a clean 503, never a silent
+fallback to in-process). Credentials cross a unix socket, so the socket is 0600
+and owned by the runner user. A per-operation process spawn would be cleaner
+still but costs a fork and a TLS handshake per mail fetch; a long-lived helper
+with per-request state is the right balance.
+
+**If this recommendation is overruled and protocol work goes in the runner**,
+then at minimum: no SFTP (no libssh2 in-process), the §6.2 build reduction in
+full, `LOW_SPEED_LIMIT`/`TIME` on every handle, and the job-lane reasoning
+re-examined because protocol calls will hold leases far longer than
+`ctx.fetch` does. And the `IPAddressDeny` protection is simply unavailable,
+which should be written down as accepted risk rather than forgotten.
+
+---
+
+## 7. Abuse
+
+### 7.1 What is and is not preventable
+
+Stated first, because the rest is easier to calibrate against it:
+
+**A connection granted to a function is a data egress channel to a fixed
+destination, and no control in this document prevents a function with
+`read` on a collection and `insert` on a connection from exfiltrating that
+collection.** That is what the feature *is*. The design makes it narrow
+(destination is admin-fixed, not script-chosen), consented-to (two separate
+admin grants), bounded (§7.2) and detectable (§8). It does not make it
+impossible, and anyone told otherwise is being misled.
+
+Worth keeping in proportion: `ctx.fetch` is already an unbounded exfiltration
+channel to any public host, with no per-project destination allow-list available
+to an operator at all. The protocol surface is *narrower* than what already
+ships. If exfiltration is the operator's concern, the higher-value work is a
+per-project egress allow-list for `ctx.fetch`, which does not exist. Worth
+flagging as a separate gap.
+
+### 7.2 Byte caps: three of them, answering three questions
+
+Following the `max_file_bytes` / `kCtxFileMaxBytes` precedent, where two caps
+exist because they answer different questions:
+
+| Cap | Bounds | Default | Where |
+|---|---|---|---|
+| per item | one message, one uploaded or downloaded file | 10 MiB | global setting, per-connection narrowing |
+| per run | total bytes a single run may move over connections | 32 MiB | global setting |
+| per project per hour | total bytes out + messages sent | operator-set | global setting, per-connection override |
+
+Enforcement detail that is easy to get wrong: `CURLOPT_MAXFILESIZE_LARGE` only
+acts when the server *declares* a size. A chunked or unknown-length IMAP fetch
+sails past it, so the write callback must also count and abort. Both, not either.
+Uploads are checked before the transfer starts, since the size is known.
+
+A 10 MiB message in a 64 MiB (or 128 MiB, per the shipped `runner.json`) JS heap
+is already uncomfortable; the JS surface should stream or chunk rather than hand
+scripts whole message bodies, which is the other agent's call but is a real
+constraint on these numbers.
+
+### 7.3 SMTP specifically
+
+Sending is the one operation with third-party consequences (someone else's inbox,
+our IP reputation, a blocklist entry that affects every tenant). It gets its own
+controls:
+
+- **`function_protocols_allowed` need not include `smtp`/`smtps`.** An operator
+  who does not want to be in the mail business sets nothing and the whole
+  question disappears. This is the cheapest and most effective control available.
+- **Per-connection recipient allow-list**: `allowed_recipient_domains:
+  ["acme.example"]`. Empty means any, which the UI should warn about. This is the
+  concrete anti-spam control and it is per destination, as asked.
+- **Envelope sender is not the script's to choose.** The connection carries
+  `from`, and optionally `allowed_from` (a list). A script may select from the
+  list or get the default; it cannot set an arbitrary sender. This prevents the
+  obvious spoofing-as-a-service case and keeps SPF/DKIM alignment an admin
+  decision.
+- **Header and command injection.** Every envelope address and every header value
+  the script supplies is rejected if it contains CR, LF or NUL. CRLF in a
+  recipient address is SMTP command injection; CRLF in a header is header
+  injection and extra recipients. Validate, do not sanitise: a stripped newline
+  hides the attempt, a 422 records it.
+- **Caps**: messages per project per hour, recipients per message, recipients per
+  project per hour. Defaults deliberately low (say 100 messages/hour, 50
+  recipients/message), because a legitimate transactional use fits easily and a
+  spam run does not.
+
+### 7.4 Durable counters, and the honest caveat
+
+Rate limits for *connection establishment* can use the existing in-memory
+`rateLimiter()` (§7.5). Abuse caps on messages and bytes cannot: the limiter is
+per process and resets on restart, so with N runners a cap of 100 is a cap of
+100N, and a crash-loop is an unlimited send.
+
+So: counters live in the database, `<project>:vectorapi_conn_usage`, one document
+per `(connection, UTC hour)`, read before an attempt and incremented after.
+`patch` for the increment, with the `Aborted`/`version_conflict` retry path
+(client 2.12.0) on contention.
+
+**Caveat, stated rather than glossed:** read-then-increment under concurrency
+permits modest overshoot. For an abuse cap that is acceptable - the point is to
+stop a thousand-message run, not to be exact at 100. It must not be presented to
+operators as a precise quota. If precision is ever required, it needs a
+server-side atomic counter the database does not currently offer.
+
+These two collections must be excluded from `db` triggers, or an audit/usage
+write fires a watcher that performs an audit/usage write.
+
+### 7.5 What is already there and should be reused
+
+- `KeyScope::rateLimitPerMin` applies through
+  `requireConnectionCapability`, so a function policy already bounds connection
+  attempts per minute with no new mechanism.
+- `KeyScope::expiresAt` gives a time-boxed grant for free.
+- The wall budget per run kind already bounds how long one run can hold a
+  connection; `max_job_wall_time_ms` (120 s in the shipped config) is the real
+  bound on a single transfer and should be read as such.
+
+---
+
+## 8. Audit
+
+### 8.1 Two separate records, for two separate readers
+
+**The run log is not the audit trail.** `FunctionRunLogStore` is trimmed to N per
+function, is tenant-visible in the web UI, and is explicitly documented as
+"anything stored here is stored thousands of times". An audit trail needs its own
+retention, its own route and operator-only fields.
+
+So: `<project>:vectorapi_conn_audit`, append-only, trimmed on a separate and
+longer retention (count and/or age, operator-set), read through an **admin-only**
+route `GET /api/v1/projects/{p}/connections/audit?...`. A one-line summary is
+*also* mirrored into the run console so the tenant can debug ("imap
+inbox_support: list, 24 items, 312 KiB, 410 ms"), without the operator-only
+fields.
+
+### 8.2 Written before the act, completed after
+
+Write an `attempt` record before connecting; update it with the outcome. A
+connection that hangs until the process is killed, or that triggers a crash in
+libcurl, must still leave a trace: an audit trail that records only completions
+cannot answer "what was it doing when it died", which is exactly the question
+asked after an incident.
+
+### 8.3 Fields
+
+Per connection use:
+
+- `run_id` (ties to the run log), `project`, `function_id`, `trigger`
+  (http/cron/db/job), `depth` (the `fn:<project>/<id>:<depth>` chain)
+- `connection` (name), `protocol`, `host`, `port`, **`pinned_addr`** - the
+  address actually dialled, which is the one field that lets an operator answer
+  "did the guard send this where I think it did"
+- `op` (the KeyOp), `started_at`, `duration_ms`
+- `outcome`: `ok` or one of the classified codes from §4.4
+- `bytes_in`, `bytes_out`, `item_count`
+- `tls`: negotiated version, cipher suite, and
+  `tls_posture: system_ca | custom_ca | pinned | weak_hostname_check` - so
+  "find every connection running with a relaxed hostname check, and whether it
+  was used" is one query
+- protocol specifics, metadata only:
+  - IMAP/POP3: mailbox name, UID count, flags changed. **No subjects, no
+    headers, no bodies.**
+  - SMTP: recipient **count** and recipient **domains**, message size, generated
+    Message-ID, sender identity selected from `allowed_from`. **No local-parts**
+    (personal data, and domains are enough to spot a spam pattern), **no
+    subject, no body.**
+  - FTP/FTPS/SFTP: remote path, direction, size. Paths are metadata and the
+    operator genuinely needs them; file contents are not recorded.
+  - WebDAV: method and path.
+- `quota`: the counter values at the time of the check, so a refusal is
+  explicable after the fact.
+
+### 8.4 Never in the audit record
+
+Credentials of any kind, message bodies, headers, subjects, attachment bytes,
+file contents, full addresses, SASL exchanges, curl verbose output. Section 4.4's
+list is the same list; it is repeated here because an audit record is written by
+different code than a log line and this is where "just include the error for
+debugging" creeps in.
+
+### 8.5 Administrative audit
+
+Separate from use, and arguably more important: creating, updating or deleting a
+connection, rotating its credential reference, setting `private_ok`, setting
+`skip_hostname_check`, changing `function_private_destinations` or
+`function_protocols_allowed`, and granting `_conn:<name>` in a function policy
+must each be recorded with the **acting key id** and a before/after of the
+changed fields (values redacted for anything secret-shaped). Those events are
+where authority changes; a use record only shows the consequence.
+
+---
+
+## 9. Things I believe cannot be made safe, listed plainly
+
+1. **FTP active mode.** An inbound connection to the process running untrusted
+   JS. Not offered at any setting.
+2. **The FTP/FTPS passive data port.** With `FTP_SKIP_PASV_IP` the address is
+   ours but the port is the server's, so an FTP connection grants reach to an
+   arbitrary high port on the approved host. Mitigated (§2.4), not eliminated.
+   Against a private destination this has real teeth, which is why that
+   combination needs its own operator opt-in and why SFTP should be the
+   recommended answer.
+3. **Exfiltration by a function holding both a collection read and a connection
+   `insert`.** Structurally unpreventable; made narrow and auditable.
+4. **Precise quotas on sends and bytes.** Read-then-increment overshoots under
+   concurrency (§7.4). Honest bound, not an exact one.
+5. **`skip_hostname_check`** weakens authentication to "presents this exact
+   anchor" rather than "is the host it claims". Defensible given the address pin,
+   but it is a real reduction and the audit must make it findable.
+6. **libssh2 in the sandbox process.** If §6.4 is overruled, I do not consider
+   SFTP safe to ship in-process, and would drop SFTP rather than accept it.
+7. **Credentials are tenant-readable today** via `ctx.env` (§4.2). Until the
+   `exportable` flag lands, the claim "the script never sees the secret" is
+   false for stored secrets, and the UI must not imply otherwise.
+
+---
+
+## 10. Checklist of changes this design implies outside its own files
+
+- `requireConnectionCapability` in `server.cpp`, sharing the rule/rate-limit body
+  with `requireCapabilityCore`, plus the `_conn:`-explicitness gate (§1.2).
+- A per-secret `exportable` flag, honoured by `functionEnvFor()`, and a
+  credential-only host-variable prefix (§4.2).
+- `function_protocols_allowed`, `function_private_destinations`,
+  `function_ftp_private_destinations_allowed`, and the byte/message caps in
+  global `Settings` (hot-reloading, like `function_egress_*`).
+- An explicit note in the settings UI that
+  `function_egress_allow_private` does **not** affect the protocol surface
+  (§3.1).
+- `<project>:vectorapi_connections`, `vectorapi_conn_usage`,
+  `vectorapi_conn_audit`: created encrypted where credentials are involved, kept
+  out of the collection registry, excluded from `db` triggers, dropped on project
+  delete.
+- `api/openapi.json` and `api/llms.txt` for the new routes.
+- If §6.4 is accepted: a `smartbotic-vectorapi-netd` package, unit file with the
+  `IPAddressDeny` set, socket permissions, and a clean 503 when it is absent.
+- Pre-existing finding to raise separately: a `{"collection": "*"}` rule already
+  grants `_files` (§1.2).
+
+
+# Part 4
+
+# Spec part 4 - mail semantics (IMAP / SMTP / POP3)
+
+Scope: the protocol-level semantics only. The JS surface shape, the libcurl
+integration mechanics and the security/authorization model are designed
+elsewhere; where this document touches them it states a *requirement* on them
+and defers.
+
+Two words used throughout:
+
+- **FLOOR** - what the first consumer needs. Ship this.
+- **FULL** - what "fully featured IMAP" needs. Designed now so the wire formats
+  (ids, markers, error slugs) do not have to change later.
+
+Error slugs follow the house convention: a thrown `TypeError`/`Error` carrying
+`e.code`, a stable slug a script branches on, never message text
+(`host_context.cpp:throwApiError`). All slugs proposed here are prefixed
+`mail_` so they cannot collide with the existing `validation`,
+`embedding_timeout`, `file_too_large` family.
+
+---
+
+## 0. Two absolute rules that constrain everything below
+
+**0.1 Never use message sequence numbers. Ever.** Every command is the `UID`
+variant: `UID FETCH`, `UID SEARCH`, `UID STORE`, `UID COPY`, `UID MOVE`,
+`UID EXPUNGE`. A sequence number is invalidated by an untagged `* n EXPUNGE`
+that can arrive at any point in a session, including interleaved with the
+responses to our own command, and the renumbering is silent. A sequence-number
+implementation works perfectly in testing and corrupts a mailbox in production.
+There is no case in this feature where a sequence number is the right handle.
+
+**0.2 UIDVALIDITY is read from the `SELECT`/`EXAMINE` that precedes each
+command, and compared then.** Not cached across calls. This is normally
+awkward, but curl's behaviour makes it free: curl issues its own `SELECT` from
+the URL path on *every* `curl_easy_perform`, so every command we send is
+preceded by a fresh `* OK [UIDVALIDITY n]` in the same response stream the
+parser is already reading. The generation check therefore costs zero round
+trips and is exact rather than approximate - it is the generation under which
+*this* FETCH actually ran, not one we remembered. The one thing the
+implementation must not do is discard the untagged `SELECT` responses before
+the FETCH data; the response parser must see the whole stream.
+
+---
+
+## 1. The message id
+
+### 1.1 Composition
+
+An exposed id must be self-sufficient: the function may hold it across runs,
+store it in a document, and hand it back on a different connection. It must
+therefore carry everything needed to resolve it *and* everything needed to
+refuse it.
+
+Payload fields, in order, US-ASCII, `\x1F` separated:
+
+| field | source | why it is in the id |
+|---|---|---|
+| `account` | the connection's account id (operator-configured name, e.g. `assistant`, `owner`) | an id from the owner's mailbox must not resolve against the assistant's connection |
+| `mailbox` | the mailbox name **in wire form** (modified UTF-7, or UTF-8 when `UTF8=ACCEPT` was negotiated, with a 1-byte tag saying which) | a UID is scoped to a mailbox; `INBOX` uid 42 and `Archive` uid 42 are different messages |
+| `uidvalidity` | the `* OK [UIDVALIDITY n]` of the SELECT the message was listed under | the hazard this whole section exists for |
+| `uid` | the `UID` FETCH item | the message |
+
+Wire form, not a decoded display name, for `mailbox`: the round trip must be
+byte-exact. Re-encoding `Elküldött elemek` to modified UTF-7 a second time can
+differ from what the server emitted (modified UTF-7 permits more than one
+encoding of the same string), and a mailbox name that does not match
+byte-for-byte is a different mailbox to the server.
+
+### 1.2 Encoding
+
+`m1.` + base64url-without-padding of the payload.
+
+- `m1.` is a version tag. A later id that needs a fifth field is `m2.` and the
+  parser refuses an `m2.` id by name on an older host rather than
+  misinterpreting it.
+- base64url, no padding: safe in a URL path segment, in a JSON string, in a
+  filter value, and - the one that matters here - it contains no `:`, which is
+  the `qualify()` separator this project already treats as hostile in a project
+  segment.
+- Not JSON inside: a JSON payload would make the id a few hundred bytes and
+  tempt a consumer into parsing it. Opaque means opaque.
+
+Typical length: ~40-70 characters. Acceptable as a document field and in a URL.
+
+### 1.3 Not signed, and why
+
+A tenant function can forge an id. Considered and rejected a truncated HMAC
+over the payload. Reasons:
+
+- It buys nothing. An id is only ever resolved against the connection the call
+  is made on, and the host re-checks that the decoded `account` equals the
+  connection's account (`mail_id_wrong_account`) and that the decoded `mailbox`
+  equals the mailbox being addressed. A forged id can therefore only name a
+  message in a mailbox the caller already has open. Forging `uid: 7` is exactly
+  as powerful as listing the mailbox.
+- It costs real operational pain: a key to hold, to rotate, and a rotation that
+  invalidates every stored id in every tenant's documents.
+
+What replaces it is strictness: the parser accepts only the exact field count,
+only the known tag, only a canonical base64url body, and a `uid` that is a
+positive 32-bit integer. Anything else is `mail_id_malformed` - a validation
+error, raised before any network call, never a lookup.
+
+### 1.4 The stale-generation refusal
+
+When the decoded `uidvalidity` differs from the one reported by the SELECT that
+the command just ran under:
+
+```
+code:    mail_id_stale_generation
+status:  409
+message: "this id was issued under UIDVALIDITY 1337 and INBOX is now at
+          UIDVALIDITY 1402; the mailbox was recreated or migrated and the id
+          cannot be resolved"
+details: { mailbox: "INBOX", id_uidvalidity: 1337, current_uidvalidity: 1402 }
+```
+
+Three things this is deliberately **not**:
+
+- **Not a 404 / not `null`.** The project's own convention is that absence is an
+  ordinary answer a script branches on (`ctx.files.get`,
+  `ctx.collections(...).get`). A stale id is not absence - it is "I refuse to
+  answer, because the honest answer is unknowable". A function that treats 404
+  as "the mail was deleted, drop my record" would silently discard a mailbox
+  worth of state after a server migration. The distinction has to be visible.
+- **Not resolved.** Never fetched, never re-looked-up by Message-ID, never
+  "probably the same". The whole hazard is that uid 42 under a new generation is
+  a *different message*, and a plausible-looking wrong answer is the worst
+  outcome available.
+- **Not retryable.** The status is 409, not 503. Nothing improves on a retry;
+  the caller has to re-list.
+
+A separate slug for the ordinary case: generation matches, uid is gone
+(expunged, moved out). That is `mail_not_found` and the FETCH-one path returns
+`null` for it, matching the house style. A listing simply omits it.
+
+The parse-and-check is a pure function - `mail/message_id.hpp`,
+`encodeMessageId()` / `decodeMessageId()` / `checkGeneration()` - testable on
+the dev host with no server, same shape as `resolveEmbedding()` and
+`resolveWallBudget()`. The refusal floor belongs in a test: a decoded id whose
+generation differs must never reach a FETCH.
+
+### 1.5 POP3
+
+**The scheme does not stretch. POP3 needs its own id, and probably should not
+ship at all.**
+
+POP3 has two candidate handles:
+
+- **The message number** (`1..n` in `LIST`/`RETR`). Scoped to a single session
+  and renumbered after any `DELE`+`QUIT`. Using it as a durable id is the same
+  class of bug as an IMAP sequence number, with no UIDVALIDITY to even detect
+  it. Unusable.
+- **`UIDL`** (RFC 1939, optional but universal in practice): a 1-70 character
+  printable-ASCII string the server promises is *persistent* and unique within
+  the maildrop. That is the only usable handle.
+
+So: `p1.` + base64url of `account \x1F uidl`. No mailbox (POP3 has exactly one
+maildrop), no generation (UIDL's contract is persistence, so there is nothing
+to version). A distinct prefix rather than stuffing POP3 into `m1.` with empty
+fields, because the two have different *guarantees* and a reader of the id
+should not have to inspect fields to learn which.
+
+If the server does not advertise `UIDL`: refuse the account at connect time,
+`mail_pop3_no_uidl`. Do not fall back to message numbers. An id that silently
+means a different message is exactly the hazard the consumer has already agreed
+to design against; shipping it for POP3 would be reintroducing it.
+
+What POP3 cannot do at all, and must refuse by name rather than emulate
+(`mail_unsupported_for_protocol`, with `details.protocol` and
+`details.operation`):
+
+- flags - there is no `\Seen`, so **read/unread does not exist** and the whole
+  PEEK design is meaningless. `RETR` is destructive of nothing but there is no
+  "mark read" to avoid; `TOP` vs `RETR` is not a read-state distinction.
+- `SEARCH` - no server-side search of any kind. Free-text search over a POP3
+  account means downloading everything, which the memory and budget design
+  below forbids.
+- mailboxes, `MOVE`, `COPY`, `APPEND` - so no save-to-Sent, and no folders.
+- partial fetch - `TOP n` gives headers plus the first *n* lines of the body,
+  which is the only preview mechanism, and it hands you the raw multipart
+  source. See §4: this is the one path where a real local MIME parser is
+  unavoidable.
+
+Recommendation: **do not implement POP3 in the FLOOR.** The id scheme above is
+specified so that if an account later demands it, the shape is already decided
+and the reduced capability set is already named. Surface a per-account
+`capabilities` object (`{ flags, search, folders, append, partialFetch, idle }`)
+so a script can branch before it calls, rather than discovering a refusal four
+steps into a workflow.
+
+---
+
+## 2. PEEK and mark-read
+
+### 2.1 What actually sets `\Seen`
+
+Only these FETCH items implicitly set `\Seen`:
+
+- `BODY[...]` - any section, including `BODY[]`, `BODY[TEXT]`, `BODY[1]`,
+  `BODY[2.1]`, and including a partial `BODY[1]<0.160>`.
+- `RFC822` (equivalent to `BODY[]`)
+- `RFC822.TEXT` (equivalent to `BODY[TEXT]`)
+
+These never do:
+
+- `UID`, `FLAGS`, `INTERNALDATE`, `RFC822.SIZE`, `ENVELOPE`, `BODYSTRUCTURE`,
+  `BODY` (the non-extensible structure item - note the collision with
+  `BODY[...]`, which is a different thing and a classic reading error)
+- `RFC822.HEADER` and every `BODY.PEEK[...]`
+
+That is the whole mechanism. The consumer's listing (§4) needs `ENVELOPE`,
+`FLAGS`, `INTERNALDATE`, `BODYSTRUCTURE` and a *partial body* - so it is only
+the preview and the full-body fetch that are exposed to this at all.
+
+### 2.2 The curl trap, and why `EXAMINE` is not the lever
+
+curl derives the mailbox from the IMAP URL path and issues its own read-write
+`SELECT` for it on every transfer. A `CURLOPT_CUSTOMREQUEST` of
+`"EXAMINE INBOX"` does not replace that `SELECT`; at best it adds a second
+mailbox-opening command whose ordering relative to curl's own is not something
+to build a read-only guarantee on. Even if `EXAMINE` won, it would be the wrong
+lever: `EXAMINE` makes the *session* read-only, which also blocks the explicit
+flag writes that "fully featured IMAP" requires, and a server is permitted to
+answer `NO` to an `EXAMINE` on a mailbox it will happily `SELECT`.
+
+**Therefore read-only-ness is enforced at the FETCH item level, which is the
+only place it is reliable.** The rule is mechanical and absolute:
+
+> The host never emits a bare `BODY[...]`, `RFC822` or `RFC822.TEXT`. Every
+> body, header, part and preview fetch is `BODY.PEEK[...]`. There is no code
+> path that constructs a non-PEEK body item.
+
+That is a one-line invariant and it should be enforced by construction: the
+only function that renders a body section into a FETCH item string emits the
+`.PEEK` form, and a test asserts no command the host can generate contains
+`BODY[` without `.PEEK`.
+
+### 2.3 Marking read is an explicit, separate command
+
+When the caller *does* want the message marked read, the host does **not**
+switch to a non-PEEK fetch. It fetches with `BODY.PEEK` as always, and then
+issues:
+
+```
+UID STORE <uid> +FLAGS.SILENT (\Seen)
+```
+
+Four reasons this is better than letting the fetch do it:
+
+1. **One fetch code path.** The peek/non-peek branch would otherwise multiply
+   through every fetch site (preview, body, part, attachment).
+2. **It fails loudly.** On a mailbox the server opened read-only, a non-PEEK
+   fetch quietly does not set the flag and the caller is told nothing. An
+   explicit `STORE` answers `NO` and the host can report
+   `mail_flag_store_failed` with the server's text.
+3. **All-or-nothing.** A body fetch that dies halfway through a 4 MB transfer
+   has already set `\Seen` server-side. The explicit order - fetch, then flag -
+   means a failed fetch leaves the message unread, which is the state the caller
+   would want on a retry.
+4. **It is auditable.** "What marked this read" is a command in the run log, not
+   an implicit consequence of an item spelling.
+
+Cost: one extra command. `+FLAGS.SILENT` suppresses the untagged FETCH echo, so
+it is the cheap form. Before relying on it, the host checks the
+`* OK [PERMANENTFLAGS (...)]` from the SELECT: if `\Seen` is not permanent, the
+flag write will not persist and the host reports
+`mail_flags_not_permanent` rather than claiming success. (`\*` in
+PERMANENTFLAGS means custom keywords are allowed - relevant to FULL, not the
+FLOOR.)
+
+### 2.4 How the connection default and the per-call override compose
+
+Three states, and `undefined` must mean *inherit*, not *false*. This is the
+same reasoning the house style already applies to `ttl_seconds`: absent is not
+zero, and collapsing the two makes a plain call silently change behaviour.
+
+```
+effectiveMarkRead(call, connection) =
+    call.markRead  !== undefined ? call.markRead
+  : connection.markRead !== undefined ? connection.markRead
+  : false                                  // the safe default
+```
+
+- **Safe default: `markRead: false`** - i.e. PEEK, nothing is marked. A function
+  that reads a mailbox to summarise it must not change what the human sees in
+  their own inbox. Surprising mutation of someone's inbox is the worst failure
+  mode available here, so it is the one that requires an explicit opt-in.
+- **Settable at connect time**, in either direction - including
+  `markRead: true`, which satisfies the product owner's requirement verbatim: a
+  consumer whose whole function is "process and mark read" sets it once on the
+  connection and every call inherits it.
+- **Overridable per call in either direction.** A connection default of `true`
+  can be overridden to `false` for one call (a peek at a message the function
+  decided not to process), and a default of `false` to `true` for one call. The
+  override is *not* narrowing-only. The product owner asked for "safely
+  overwrite it", which means both directions.
+
+This resolution is a pure function - `mail/read_policy.hpp`,
+`resolveMarkRead()` - unit-tested for all nine combinations, including the two
+that matter most: `undefined`/`undefined` is `false`, and
+`false`-over-`true` works.
+
+One narrowing-only layer sits *above* this and is not mine to design: an
+operator-level per-account `readOnly` flag, which if set makes every
+`markRead: true` a refusal (`mail_account_read_only`) rather than silently
+ignoring it. Precedent: embedding timeouts are per-project and narrowing-only
+for exactly this reason - a tenant option must not be able to widen what the
+operator allowed. **Deferred to the security-model agent**, with the
+recommendation that it exist.
+
+### 2.5 Side effects that cannot be avoided - named
+
+- **`\Recent` is consumed by `SELECT` itself.** The first session to SELECT a
+  mailbox clears `\Recent` for everyone else. There is no PEEK for this and no
+  way to avoid it short of never opening the mailbox. Consequence: `\Recent`
+  must never be exposed in the API and must never be used for "new mail" - the
+  uid marker in §8 exists partly because of this. Worth stating in the consumer
+  docs, because a human user may notice their client stops bolding new mail.
+- **Attachment download is a body fetch**, so it must also be `BODY.PEEK[part]`
+  - easy to forget, because the attachment path is written later and separately.
+  Covered by the §2.2 invariant.
+- **`UID MOVE` / `UID COPY` do not set `\Seen`**, but a MOVE expunges the source:
+  the id dies, and a *new* uid exists in the destination. The host returns the
+  new id when `UIDPLUS` gave it a `COPYUID`, and `null` plus
+  `details.new_id_unknown: true` when it did not. A caller holding the old id
+  after a move must get `mail_not_found`, not a resolution.
+- **`EXPUNGE` is destructive beyond its argument.** A bare `EXPUNGE` removes
+  *every* message flagged `\Deleted` in the mailbox, including ones another
+  client flagged and has not expunged yet. The host must never send a bare
+  `EXPUNGE`. Delete is, in order of preference: `UID MOVE` to the `\Trash`
+  special-use mailbox; else `UID STORE +FLAGS (\Deleted)` followed by
+  **`UID EXPUNGE`** (UIDPLUS, RFC 4315), which is scoped to the uids given;
+  else refuse with `mail_expunge_unsafe`. Refusing a delete is vastly better
+  than silently destroying a colleague's pending deletions.
+- **A server with broken PEEK.** Rare but real. Cheap mitigation: the first
+  time an account fetches a body with `markRead: false`, re-read `FLAGS` for
+  that uid afterwards; if `\Seen` appeared, log a warning naming the server
+  greeting once per account. Do not retry or compensate - unsetting `\Seen`
+  would be a second wrong mutation.
+- **`APPEND` of a sent copy lands unseen** unless flags are given. A Sent folder
+  full of unread mail is a bug; see §6.4.
+
+---
+
+## 3. SEARCH
+
+### 3.1 What it is, and what it costs
+
+`UID SEARCH` is evaluated entirely server-side and the cost ranges over three
+orders of magnitude depending on the keys:
+
+| key | typical cost |
+|---|---|
+| `UNSEEN`, `SEEN`, `UID <range>`, `ALL` | index lookup, milliseconds |
+| `SINCE`, `BEFORE`, `LARGER`, `SMALLER` | metadata scan, fast |
+| `FROM`, `SUBJECT`, `HEADER <f> <s>` | header scan - fast with a full-text index, seconds without |
+| `TEXT`, `BODY` | **full body scan.** Dovecot without an `fts` plugin reads every message. Tens of seconds on a large mailbox is normal, not pathological. |
+
+This is not something a wrapper can fix. The surface must make the cost visible
+and bound it.
+
+### 3.2 The exposed surface
+
+```
+.search({
+  unread:  true | false,        // -> UNSEEN / SEEN
+  since:   Date | epoch ms,     // -> SINCE  (1-day granularity, see below)
+  before:  Date | epoch ms,
+  query:   "free text",
+  scope:   ['from','subject','body'],   // default ['from','subject']
+  limit:   15,                  // <= a host maximum
+  timeoutMs: 8000               // per-command, bounded by the run budget
+})
+```
+
+The decisive design choice is **`scope`**, with `body` *off by default*. The
+difference between `['from','subject']` and `['from','subject','body']` is the
+difference between a 50 ms search and a 30 s search, and a caller who does not
+know that will write the slow one. Making `body` an explicit opt-in means the
+expensive query is a decision rather than a default.
+
+`since` has 1-day granularity in IMAP and compares against INTERNALDATE in the
+server's notion of a date. It is therefore a *coarse bound*, never a precise
+filter - the host documents it as such and does not post-filter to make it look
+precise, because post-filtering would make the returned count disagree with the
+mailbox.
+
+### 3.3 Mapping the consumer's "free-text over sender, subject and body"
+
+**Server-side SEARCH.** It is the only option: client-side filtering can only
+see messages already fetched, and the point of a search is to find the ones you
+have not fetched.
+
+IMAP SEARCH is prefix boolean, multiple keys are implicit AND, and `OR` takes
+exactly two arguments, so three terms nest:
+
+```
+UID SEARCH CHARSET UTF-8 UNSEEN OR OR FROM "acme" SUBJECT "acme" BODY "acme"
+```
+
+Two protocol problems with that line.
+
+**Charset.** `CHARSET UTF-8` is permitted but a server may answer
+`BAD [CANNOT] unsupported charset`, leaving only US-ASCII - which cannot
+express a Hungarian search term. The host probes once per account: if `UTF-8` is
+rejected and the query is pure ASCII, re-issue without the `CHARSET` clause
+(identical semantics). If the query is **not** ASCII and UTF-8 is unsupported,
+**refuse** with `mail_search_charset_unsupported`. Do not transliterate, do not
+strip accents: `Elkuldott` finding nothing when `Elküldött` exists is a wrong
+answer, and a wrong answer silently is worse than a named refusal.
+
+**Non-ASCII search strings must be sent as literals.** A search term containing
+non-ASCII octets is not a valid IMAP quoted-string; it has to be
+`{nn}\r\n<octets>`. A *synchronizing* literal requires the client to wait for a
+`+ go ahead` continuation mid-command, which does not fit a model where the
+whole command is handed to curl as one `CUSTOMREQUEST` string. So: the host
+requires the `LITERAL+` or `LITERAL-` capability (non-synchronizing literals,
+RFC 7888) for a non-ASCII search term and refuses with
+`mail_search_literal_unsupported` otherwise. **This needs verifying against
+curl's actual continuation handling before the design is final** - it may be
+that curl's IMAP state machine handles the continuation, in which case the
+restriction lifts. Flagging it as the single most likely "we were wrong about
+the plumbing" item in this document. *(Mechanics: curl agent.)*
+
+### 3.4 Bounding a slow search
+
+The run constraint from CLAUDE.md is hard: a blocking host call cannot be
+interrupted, the QuickJS interrupt handler only fires between bytecode ops, and
+so while a SEARCH is in flight the wall budget is *not being enforced*. The
+budget is enforced by handing curl timeouts that already fit the remaining
+budget - exactly the problem `resolveEmbedBudget()` solves, and the solution
+should be the same function generalised rather than a second one.
+
+`resolveMailBudget(remainingBudgetMs, callTimeoutMs, phase)` - pure,
+`mail/budget.hpp`:
+
+- connect gets **at most half** the available time (same reasoning: a reachable
+  server connects in well under a second, and a generous connect allowance
+  starves the read phase). Note mail connects are costlier than HTTP ones - TLS
+  plus `AUTHENTICATE`/`LOGIN` is routinely 200-500 ms - so the half-rule is
+  load-bearing here, not theoretical.
+- the read timeout is `min(callTimeoutMs, remaining - reserve)`, where `reserve`
+  is enough to run the §7 bookkeeping and return a response. A command is not
+  started at all if the remaining budget is below a floor:
+  `mail_budget_exhausted`, with `details.command` naming which command was
+  being attempted. Naming the command matters: "your run timed out" is useless,
+  "your run timed out before the SEARCH" tells the consumer to narrow the scope.
+- a search that times out is **`mail_search_timeout`, 504**, deliberately
+  distinct from the run merely running out of budget - the precedent is
+  `embedTimeoutMs` on `.search()` producing a 504 `embedding_timeout` rather
+  than folding into a generic timeout, because the remedies differ (narrow the
+  scope vs raise the budget).
+
+**The honest finding this produces: mail does not fit the HTTP wall budget.** An
+interactive `/fn/...` route has ~2 s by default. Login + SELECT + SEARCH + FETCH
+against a remote IMAP server, with a 15-message page, is routinely 1-3 s before
+any search is slow. Recommendations:
+
+- Mail work belongs in a **`job`** trigger, which draws on the job wall ceiling
+  and its own pool lane, and whose runs hold no socket.
+- An interactive route that must list mail should read a cached listing a job
+  produced, not go to IMAP.
+- The per-project per-kind http cap exists and can be raised, but raising it to
+  accommodate mail makes every other route on that project able to hold a
+  runtime for that long. Say so rather than recommending it.
+- Connection reuse within a run is not an optimisation, it is a requirement: a
+  listing that re-authenticates per command cannot fit any budget.
+  *(Mechanics: curl agent. Tenancy requirement: a reused authenticated
+  connection must be keyed by at least `(project, account)`. A pool keyed by
+  credentials alone would be a cross-tenant leak of precisely the class the
+  `file_store` note in CLAUDE.md warns about. Deferred to the security agent,
+  flagged here because it is a protocol-shaped temptation.)*
+
+### 3.5 A huge result set
+
+`UID SEARCH` answers with a single untagged `* SEARCH 1 2 3 ...` line listing
+**every** matching uid. `SINCE 1-Jan-2020` on a 200 000-message mailbox is a
+multi-megabyte line. Three defences, in order:
+
+1. **Never issue an unbounded SEARCH.** Every search the host emits is ANDed
+   with a bounding key. If the caller gave none, the host adds
+   `SINCE <today - mail.search_default_window_days>` (default 90). The window is
+   reported back in the response so it is not a hidden behaviour.
+2. **Use `ESEARCH` when advertised** (RFC 4731):
+   `UID SEARCH RETURN (COUNT MIN MAX) ...` returns a count instead of the list,
+   which is both the cheap way to answer "how many matched" and the way to
+   decide whether to ask for the list at all. `SORT`/`THREAD` (RFC 5256) and
+   `SEARCHRES` (`$`, RFC 5182) are the other capability-gated upgrades - FULL,
+   not FLOOR.
+3. **Cap the bytes read from the search response** and report truncation. The
+   cap is a host setting (`mail.max_search_response_bytes`, default 1 MiB ~
+   130k uids).
+
+Result shaping, which follows the project's existing `scanCapped` precedent
+exactly: the host takes the **highest `limit` uids** (newest first - uids are
+monotonic within a generation, so the tail of the SEARCH result is the newest
+mail without a second sort), and the response carries:
+
+```
+{ messages: [...],
+  matched: 1847,          // the true count, from ESEARCH COUNT or the parsed list
+  truncated: true,        // ONLY when matched > limit
+  responseCapped: false,  // ONLY when the byte cap cut the uid list itself
+  window: { since: "2026-07-10" },   // if the host added one
+  degraded: []            // e.g. ['charset_ascii_only'] - see below
+}
+```
+
+`truncated` is set **only when truncation actually happened**, never when the
+mailbox simply contained fewer matches than `limit`. Same rule, same reason as
+`VectorSearchResult::scanCapped`: a flag that cries wolf stops being read.
+`responseCapped` is separate from `truncated` because they mean different
+things - `truncated` means "there are more and we know how many",
+`responseCapped` means "**we no longer know how many**", which is strictly
+worse and a caller may want to narrow and retry rather than paginate.
+
+### 3.6 Client-side filtering - where it is legitimate
+
+Only two cases:
+
+- A predicate IMAP SEARCH cannot express, applied to an **already bounded and
+  already fetched** set (e.g. "of these 15, which have a PDF attachment" from
+  the BODYSTRUCTURE we already have - zero extra bytes).
+- A refinement of a page the caller already holds.
+
+Whenever the host filters client-side, the response carries
+`filteredClientSide: true` and `matched` is **omitted**, because the host no
+longer knows the mailbox-wide count and a number that only describes the fetched
+window would be read as the truth. The rule: a count is either the server's
+answer about the mailbox or it is absent. Never a count about a window dressed
+up as a count about a mailbox.
+
+---
+
+## 4. The listing
+
+### 4.1 The FETCH
+
+```
+UID FETCH <set> (UID
+                 FLAGS
+                 INTERNALDATE
+                 RFC822.SIZE
+                 ENVELOPE
+                 BODYSTRUCTURE
+                 BODY.PEEK[HEADER.FIELDS (MESSAGE-ID REFERENCES IN-REPLY-TO
+                                          LIST-UNSUBSCRIBE AUTO-SUBMITTED)])
+```
+
+Field by field:
+
+| consumer field | item | note |
+|---|---|---|
+| `id` | `UID` + the SELECT's `UIDVALIDITY` + mailbox + account | §1 |
+| `subject` | `ENVELOPE[1]` | raw; RFC 2047 decode needed (§5) |
+| `from` name + address | `ENVELOPE[2]` - already a structured `(name adl mailbox host)` list | the big win of ENVELOPE: the server has already parsed the address list, so we do not need an RFC 5322 address parser on the read path. The *name* still needs 2047 decoding. |
+| `receivedAt` | `INTERNALDATE` | **not** the `Date:` header. INTERNALDATE is when *this server* received it; `Date:` is sender-asserted, frequently wrong and trivially forged. Order by INTERNALDATE. Expose `ENVELOPE`'s date as `sentAt` separately for display, clearly labelled as claimed. |
+| `unread` | `FLAGS` lacks `\Seen` | |
+| `hasAttachments` | `BODYSTRUCTURE` walk | §4.4 - costs nothing extra |
+| `size` | `RFC822.SIZE` | lets a caller avoid a body fetch it cannot afford |
+| threading ids | the `HEADER.FIELDS` peek | **added now though threading is "later"** - see §6.6. Retrofitting it means re-fetching every message a consumer already stored. |
+
+`BODY.PEEK[HEADER.FIELDS (...)]` is a peek, so no `\Seen`. The field list is
+short on purpose; `HEADER.FIELDS.NOT` with a block list would drag in whole
+header blocks (DKIM signatures are kilobytes).
+
+### 4.2 The preview cannot be in the same round trip - honestly
+
+The preview must be a **partial fetch of the text part**, not a truncation of
+the whole message: `BODY.PEEK[1.1]<0.4096>` moves 4 KB,
+`BODY.PEEK[]<0.4096>` of a message with a 6 MB attachment also moves 4 KB but
+of the *wrong bytes* (MIME preamble and part headers), and fetching the whole
+message to truncate locally moves the 6 MB.
+
+But **you cannot know which part is the text part until you have the
+BODYSTRUCTURE**, and the BODYSTRUCTURE arrives in the same response as the
+partial you were trying to aim. One correctly-aimed round trip is impossible in
+general. Two options:
+
+**(a) Two commands, recommended.** Command 1 is §4.1 for the whole page.
+Command 2 is a single `UID FETCH` for the whole page, each message naming the
+part the structure chose:
+
+```
+UID FETCH 412,415,419 (BODY.PEEK[1.1]<0.4096>)
+```
+
+- one command for N messages, not N commands
+- the slice size is chosen *per message* from the part's encoding and charset,
+  which option (b) cannot do
+- with a kept-alive connection the marginal cost is one round trip, ~50-300 ms
+
+**(b) One command with speculative parts.** Fetch
+`BODY.PEEK[1]<0.4096>`, `BODY.PEEK[1.1]<0.4096>` and `BODY.PEEK[TEXT]<0.4096>`
+together, then use the BODYSTRUCTURE in the same response to pick whichever
+guess was right and discard the rest. Covers the common shapes
+(`text/plain` alone → part `1`; `alternative(plain, html)` → `1.1`;
+`mixed(alternative(plain,html), pdf)` → `1.1.1`, **which this set misses**).
+`BODY.PEEK[TEXT]` is a universal fallback only in the sense that it always
+returns bytes; on a multipart those bytes are the preamble and the first part's
+headers, which need a MIME parser to make sense of - so it is not actually a
+fallback for the hard cases.
+
+**Recommendation: (a).** (b) trades correctness on nested structures for one
+round trip and costs 2-3x the bytes in the common case. Revisit only if
+measurement shows the round trip matters, and if so adopt (b) *with* (a) as the
+fallback for a structure the guesses missed - which means implementing both.
+
+### 4.3 A clean text preview out of a multipart/alternative HTML mail
+
+This is the genuinely hard part. The honest answer is a ladder, and the rungs
+get progressively less reliable.
+
+**Rung 1 - a `text/plain` alternative exists.** Walk the BODYSTRUCTURE, take
+the `text/plain` leaf, partial-fetch it, transfer-decode, charset-convert,
+trim, take 160 characters. **Fully correct**, needs no HTML handling, and covers
+most machine-generated mail and most mail from real MUAs (nearly all still send
+a plain alternative). *This is the FLOOR and it should be shipped on its own.*
+
+Decoding a *partial* slice has four traps, all solvable:
+
+- **base64**: trim the slice to a multiple of 4 after removing CRLF, then decode.
+  Safe from offset 0.
+- **quoted-printable**: a slice may end in `=` or `=4` (a truncated escape or a
+  soft line break). Drop a trailing incomplete escape.
+- **multi-byte charsets**: a byte cut mid-sequence. Trim the trailing incomplete
+  sequence - iconv reports `EINVAL` for exactly this and the remainder is
+  discarded, which is correct because we always slice from offset 0 and only the
+  *tail* can be partial.
+- **stateful charsets** (ISO-2022-JP): safe only because the slice starts at 0.
+  A non-zero offset would be undecodable. Never partial-fetch from a non-zero
+  offset for text.
+
+**Rung 2 - `text/html` only.** Now a stripper is unavoidable, and the partial
+fetch gets harder: the first 4 KB of an HTML mail is frequently
+`<!DOCTYPE>…<head><style>` with *zero visible characters*. So HTML-only mail
+needs a much larger slice - recommend `mail.preview_html_slice_bytes`, default
+64 KiB - and a stripper that:
+
+- discards the contents of `<script>`, `<style>`, `<head>`, and HTML comments
+- discards tags, inserting a space or newline for block-level elements
+  (`p`, `div`, `br`, `li`, `tr`, `h1-6`) so words do not run together - the
+  single most visible stripper bug is `HelloWorldClickhere`
+- decodes entities: the numeric forms, and a named table. The full HTML5 named
+  table is ~2200 entries; a 60-entry table covering the ones that occur in mail
+  (`nbsp amp lt gt quot apos hellip mdash ndash rsquo lsquo ldquo rdquo` and
+  the Latin-1 block) gets ~99.9% and anything unknown is passed through
+  literally
+- collapses whitespace runs, including `&nbsp;` and the zero-width characters
+  marketing mail uses as preheader padding (`&#8203;`, `&zwnj;`) - which
+  otherwise produce a preview of 160 invisible characters, a real and common
+  failure
+- **discards a trailing partial tag or entity** from the cut
+
+Honest assessment: this gets a usable preview most of the time and an ugly one
+sometimes. A preview is cosmetic, so an imperfect one is an acceptable outcome
+in a way an imperfect address or id is not. Say so in the consumer
+documentation rather than implying fidelity.
+
+**Rung 3 - the preheader and quoted-reply problem.** Two things ruin a preview
+even when the extraction is perfect:
+
+- A reply's first visible text is often `On Tue, 7 Oct 2026, X wrote:` or a
+  block of `>`-quoted lines. Crude mitigation: drop leading lines beginning with
+  `>`, and drop a leading line matching a small set of attribution patterns.
+  Locale-dependent, imperfect, best-effort, and must be documented as
+  cosmetic-only.
+- Marketing mail leads with a hidden preheader div. Partly handled by the
+  zero-width stripping above; `display:none` detection would need real CSS and
+  is out of scope.
+
+**Rung 4 - `multipart/signed`, `multipart/encrypted`, `message/rfc822`.** The
+readable text is nested one level deeper (inside the signed part's first
+subpart; inside a forwarded message's own structure). The BODYSTRUCTURE walk
+handles `signed` and nested `rfc822` naturally - IMAP reports their inner
+structure and the parts are addressable (`2.1.1`, `2.TEXT`). `encrypted` has no
+readable text and the preview is correctly empty with
+`previewUnavailable: 'encrypted'`.
+
+### 4.4 Where a local MIME parser becomes unavoidable
+
+The key insight, and it is worth stating plainly because it is what keeps this
+feature tractable:
+
+> **On the IMAP read path, the server is the MIME parser.** `BODYSTRUCTURE`
+> gives the full tree - types, subtypes, parameters, encodings, sizes,
+> dispositions, filenames, Content-IDs - and `BODY.PEEK[<part>]` fetches any
+> leaf of it directly. We need a parser for the *BODYSTRUCTURE response*
+> (parenthesised lists, atoms, quoted strings, NIL, literals), not for MIME.
+
+A local MIME parser becomes unavoidable in exactly these cases:
+
+1. **POP3.** `TOP`/`RETR` hand you the raw RFC 822 message. There is no
+   structure to ask for. This is the strongest argument for not shipping POP3.
+2. **A raw message we hold as bytes**: an `.eml` attachment a function wants to
+   look inside, an imported mailbox, a "give me the source" feature.
+3. **A server whose BODYSTRUCTURE is wrong.** It happens - Exchange has shipped
+   releases with mis-reported nesting and mis-reported encodings. Mitigation
+   without a parser: the part's *own* `MIME` section is fetchable
+   (`BODY.PEEK[1.1.MIME]`) and gives the part headers directly, so a disagreement
+   can be detected and the part headers trusted over the structure. Cheap, and
+   avoids a parser.
+4. **FULL only**: `multipart/report` (DSNs - bounce handling), and
+   `multipart/related` reassembly if we ever render HTML with inline images,
+   which we should not.
+
+So the FLOOR needs **no MIME parser**, only a BODYSTRUCTURE walker. That is the
+line to hold.
+
+`hasAttachments` from the walk: true if any leaf has
+`Content-Disposition: attachment`, **or** is a non-`text/*`, non-`multipart/*`
+leaf that is not an inline part referenced by a `cid:` in the HTML. The second
+clause matters because plenty of real mail attaches a PDF with no disposition
+header at all. The cid exclusion matters because a signature image must not
+make every mail from that sender report an attachment - the consumer's own
+outbound mail would do this to itself.
+
+---
+
+## 5. MIME - parse and generate
+
+### 5.1 Parse direction
+
+| what | recommendation | risk |
+|---|---|---|
+| **IMAP response grammar** (atoms, quoted strings, `NIL`, parenthesised lists, `{n}` literals, untagged vs tagged, response codes) | **hand-roll**, as a standalone pure unit with no transport and no database - the same shape as `runner_protocol`, so it unit-tests and fuzzes on the dev host | **The single largest risk in the feature.** ~500-700 lines. The #1 bug is scanning a literal for a delimiter instead of counting its octets: a literal can contain `)`, `"` and CRLF, and a subject line containing `)` will break a scanner-based parser on day three. Literals are **length-counted, always.** Must be fuzzed. |
+| **RFC 2047 encoded-words** (`=?utf-8?B?...?=`) in Subject and address display names | hand-roll, ~150 lines | Known pitfalls, all of which must be in the test corpus: `?B?` and `?Q?`; `_` means space in Q only; whitespace *between two adjacent encoded-words is removed* while whitespace between a word and plain text is kept; encoded-words appear inside `phrase` but must not be decoded inside an `addr-spec`; and the classic - **a multi-byte character split across two adjacent encoded-words**, which requires concatenating the decoded *bytes* of adjacent same-charset words before charset conversion, not converting each word separately. Converting per word produces U+FFFD in real mail from real senders. |
+| **RFC 2231** parameter continuation and charset (`filename*0*=`, `filename*=utf-8''...`) | hand-roll alongside 2047 | Needed for non-ASCII attachment filenames, which Hungarian mail will have immediately. Some senders use 2047 inside a parameter instead (non-conformant but widespread) - accept both. |
+| **Charset → UTF-8** | **do not hand-roll. libiconv** (in glibc; GNU libiconv elsewhere). ICU only if normalisation is ever wanted, which it is not. | The real work is the **alias table**, which iconv does not provide: `iso-8859-1` should be decoded as `windows-1252` for mail (senders label cp1252 as latin-1 and iconv will reject the 0x80-0x9F range), `utf8`→`utf-8`, `gb2312`→`gbk`, `ks_c_5601-1987`→`cp949`, `cp936`→`gbk`, `unicode`→`utf-16`, plus the empty and bogus labels. Unknown label or undecodable byte → **U+FFFD, never a failure**: one broken sender must not break a page of 15. |
+| **base64 / quoted-printable transfer decoding** | hand-roll; base64 already exists in `hostdetail` | Trivial. QP needs the soft-break rule and tolerant handling of a bare `=`. Both need the partial-slice trimming of §4.3. |
+| **HTML → text** | hand-roll a small stripper for both the 160-char preview and the ~4000-char body | Divergence from a browser on malformed markup, and the entity table. Acceptable because the output is *displayed text we never render or execute*. **Explicitly: the stripper is not a sanitiser and must never be described as one.** If fidelity complaints arrive, `lexbor` (BSD, no deps, fast) is the upgrade; `gumbo` is unmaintained. |
+| **Modified UTF-7 mailbox names** (RFC 3501 §5.1.3) | hand-roll, ~80 lines each way | Needed to *display* `Elküldött elemek`. The wire form is what goes in ids and commands (§1.1); the decoded form is display only. Skipped entirely when `UTF8=ACCEPT` (RFC 6855) is negotiated, which should be preferred when available. |
+| **RFC 5322 address parsing** | **not needed on the read path** - `ENVELOPE` is pre-parsed by the server. Needed only for validating caller-supplied addresses on send, where a strict subset is correct. | Avoided, and worth noticing that it is avoided: a general 5322 address parser (groups, comments, obsolete syntax) is a multi-week trap. |
+
+**Rejected: libetpan / vmime / mailcore2.** libetpan is the only serious C
+option and it brings its own socket and TLS layer, which would duplicate and
+fight curl - and, more seriously, would bypass the SSRF guard that every
+outbound call in this service goes through. Its CVE history is in the response
+parser, which is exactly the component we would be adopting it for. A narrow,
+auditable, fuzzed hand-rolled parser over bytes curl already delivered is the
+better risk.
+
+### 5.2 Generate direction
+
+**Hand-roll, and the risk is genuinely low** - a generator's input is ours, so
+there is no adversary and no "real world mail is non-conformant" problem. The
+asymmetry is worth stating: parsing MIME is dangerous, generating it is not.
+
+Target structure for the consumer's send (HTML body + inline cid signature):
+
+```
+multipart/mixed;   boundary=B0        <- only when there are file attachments
+  multipart/related; type="multipart/alternative"; boundary=B1
+    multipart/alternative; boundary=B2
+      text/plain;  charset=utf-8; Content-Transfer-Encoding: base64
+      text/html;   charset=utf-8; Content-Transfer-Encoding: base64
+    image/png;     Content-ID: <sig-7f3a@example.com>
+                   Content-Disposition: inline; filename="signature.png"
+                   Content-Transfer-Encoding: base64
+```
+
+The correctness points that are easy to get wrong:
+
+- **The cid image goes inside `multipart/related`, together with the
+  `alternative`, not as a sibling of it.** Get this wrong and Outlook shows the
+  signature as a downloadable attachment instead of rendering it - the single
+  most common inline-image bug.
+- `Content-ID` is angle-bracketed `<sig@domain>`; the HTML references
+  `src="cid:sig@domain"` **without** the brackets. Mismatch = broken image.
+- `type="multipart/alternative"` on the `related` part is the RFC 2387 `type`
+  parameter naming the root; some clients need it.
+- **Always emit a `text/plain` alternative**, generated by the same stripper as
+  §4.3 when the caller supplied only HTML. An HTML-only mail scores badly with
+  spam filters and is unreadable in a text client. Not optional.
+- Boundaries from 16 random bytes. Since every part is base64-encoded, a
+  boundary cannot occur in a body - but assert it anyway, cheaply.
+- **CRLF only, everywhere.** A bare LF in a header or body is a protocol
+  violation that some servers silently accept and others reject, and it breaks
+  DKIM.
+- RFC 5322 line limit is 998 octets. base64 at 76 columns, encoded-words folded
+  at 76 **on encoded-word boundaries, never mid-word** - folding inside an
+  encoded-word corrupts it.
+- Address display names RFC 2047-encoded when non-ASCII; the `addr-spec` stays
+  raw. A **non-ASCII local part or domain requires `SMTPUTF8`** (RFC 6531) -
+  refuse by name (`mail_address_requires_smtputf8`) unless the server advertises
+  it. Do not punycode the domain silently and do not mangle the local part.
+- `MIME-Version: 1.0`, `Date` in RFC 5322 form with a real numeric offset,
+  `Message-ID` (§6.5), `From`, `To`, `Cc`, `Reply-To`, `Subject`.
+  **No `Bcc` header, ever** (§6.1).
+- **SMTP dot-stuffing**: a body line beginning with `.` must be doubled in the
+  DATA phase. Because every part is base64 or QP encoded, no generated line can
+  begin with a bare `.` - the problem is eliminated **by construction**, which
+  is the reason to encode even a pure-ASCII plain part rather than send it 7bit.
+  Note it explicitly so a later "optimisation" to send short bodies 7bit does
+  not reintroduce it.
+
+---
+
+## 6. Send semantics
+
+### 6.1 Envelope vs headers - the trap
+
+**The SMTP envelope determines delivery. `To`/`Cc`/`Bcc` headers are display
+text and determine nothing.** This is the mechanism by which Bcc works
+(recipient in the envelope, absent from the headers) and it is the mechanism by
+which a careless implementation leaks or drops recipients:
+
+- build `RCPT TO` from the `To` header only → **Cc recipients silently never
+  receive the mail**, and nothing anywhere reports an error. The sender sees a
+  Cc line in their Sent copy and believes it was delivered.
+- render a `Bcc` header → **every recipient sees the blind list.** A privacy
+  incident, not a bug.
+
+The invariant, which belongs in a test rather than a comment:
+
+> The set of `RCPT TO` commands equals `dedupe(to ∪ cc ∪ bcc)`. The rendered
+> header block contains `To` and `Cc` and **never** `Bcc`. A send with only
+> `bcc` populated still issues at least one `RCPT TO` and renders a header
+> block with no recipient headers (legal; `To: undisclosed-recipients:;` is the
+> conventional filler and should be emitted).
+
+Dedupe: an address in both `To` and `Cc` gets **one** `RCPT TO` and appears in
+**both** headers - the envelope is a set, the headers are a display.
+
+**Partial recipient failure.** SMTP can accept some `RCPT TO` and reject others
+(`550` on one address) and curl has `CURLOPT_MAIL_RCPT_ALLOWFAILS` to tolerate
+it. **Do not enable it in the FLOOR.** Rationale: partial acceptance combined
+with at-least-once job delivery means the retry re-sends to the recipients who
+already received. Send is therefore all-or-nothing: any rejected recipient fails
+the whole send with `mail_recipient_rejected` and `details.recipients` naming
+which, before DATA where possible. For FULL, a best-effort mode is an explicit
+option returning a per-recipient result array - and then §7's idempotency record
+must store *which recipients succeeded* so the retry can send only to the rest.
+The data model supports that; the FLOOR does not use it.
+
+### 6.2 `MAIL FROM` vs the `From` header, and on-behalf-of
+
+`MAIL FROM` is the envelope sender (bounce address, and what SPF checks). The
+`From` header is what DMARC aligns against. They are different and both matter.
+
+- **Default: `MAIL FROM` is the authenticated account's own address.** Most
+  submission servers enforce this anyway and will answer `550` otherwise.
+- **`From` must be an address the account is authorized to send as.** A `from`
+  option is honoured only against a per-account operator-configured allow-list;
+  otherwise `mail_from_not_authorized`. Never silently rewrite `From` to the
+  account address - the caller asked for something specific and a silent
+  substitution means the mail goes out over the wrong identity.
+- **On-behalf-of is `Reply-To`, not `From`.** Setting `From: owner@` from the
+  assistant's account is a DMARC failure for any owner domain with a policy,
+  and the mail is quarantined or rejected. The consumer's stated need - "a
+  Reply-To so on-behalf-of replies reach the owner" - is exactly the correct
+  shape and should be endorsed rather than extended. Display name carries the
+  relationship: `From: "Assistant (for Jane Owner)" <assistant@...>`,
+  `Reply-To: jane@...`.
+- When `From` legitimately differs from the authenticated mailbox, RFC 5322
+  requires a `Sender:` header naming the actual sender. Emit it.
+- `Reply-To` may hold multiple addresses. It does not affect DMARC or SPF.
+
+### 6.3 Message-ID
+
+**Generated by us, always.** Never left to the server, because it is the only
+durable handle on a message we sent and §7 depends on knowing it *before* the
+send.
+
+```
+<base32(16 random bytes).<epoch-ms>@<domain>>
+```
+
+- 16 random bytes: collision-free without coordination.
+- epoch-ms: makes it sortable and debuggable in a log.
+- `<domain>`: **the domain of the `From` address.** Not the project name, not
+  the host's hostname, not `localhost` - filters penalise a Message-ID domain
+  that does not match `From`.
+- base32 rather than base64: no `+`/`/` to worry about in a header whose
+  grammar is `msg-id` and which gets quoted and re-quoted by every hop.
+
+It is generated, written into the §7 idempotency claim, *then* sent. That
+ordering is what makes the ambiguous-retry case recoverable.
+
+### 6.4 Saving to Sent via `APPEND`
+
+**Detection, in strict priority order:**
+
+1. **Per-account operator override** (`mail.accounts.<id>.sent_mailbox`). Always
+   wins. This is the escape hatch for every server that gets the rest wrong, and
+   it is the reason the fallback chain below does not need to be exhaustive.
+2. **`LIST (SPECIAL-USE) "" "*"`** (RFC 6154) and look for the `\Sent`
+   attribute. Covers Gmail, Dovecot, modern Exchange, Fastmail.
+3. **Name candidates against the actual `LIST` output**, case-insensitively,
+   honouring the hierarchy delimiter from the LIST response and any prefix from
+   `NAMESPACE` (RFC 2342): `Sent`, `Sent Items`, `Sent Messages`,
+   `[Gmail]/Sent Mail`, `INBOX.Sent`. **Do not build a localisation table**
+   (`Gesendet`, `Elküldött elemek`, `Envoyés`, …) - it is endless and it is what
+   step 1 exists for.
+4. **Undetermined → send anyway**, and report
+   `savedToSent: false, savedToSentReason: 'mailbox_not_found'`. The mail going
+   out matters more than the copy, and refusing the send over a cosmetic failure
+   would block business for a filing problem. **Never auto-create a folder** - a
+   stray `Sent` beside the real `Sent Items` is worse than no copy.
+
+Resolution is cached with the connection and re-detected when a `LIST` no
+longer shows it.
+
+**The Gmail duplicate.** Gmail files SMTP-submitted mail into Sent Mail by
+itself, so an `APPEND` produces **two copies**. Real, well known, and a
+consumer-visible bug if ignored. So `saveToSent: 'auto' | 'always' | 'never'`,
+default `auto`, where `auto` means "never for a server that files its own sent
+mail", detected by the `X-GM-EXT-1` capability. Overridable per account, because
+other providers do this too and the detection is necessarily incomplete.
+
+**Doing the APPEND.** curl supports IMAP `APPEND` first-class: an IMAP URL whose
+path is the mailbox plus `CURLOPT_UPLOAD` and `CURLOPT_INFILESIZE_LARGE`. That
+is a good fit and avoids hand-rolling a multi-megabyte synchronizing literal.
+The cost: curl's APPEND does not let us set the flag list or INTERNALDATE, so
+the copy lands **unseen** - a Sent folder of unread mail. The repair chain:
+
+1. If the server supports `UIDPLUS`, the tagged `OK [APPENDUID <uidvalidity>
+   <uid>]` gives the new uid directly → `UID STORE <uid> +FLAGS.SILENT (\Seen)`,
+   and the host can also return the Sent copy's **id** (§1) to the caller, which
+   is useful for threading later.
+2. Without `UIDPLUS`: `UID SEARCH HEADER MESSAGE-ID "<our generated id>"` in the
+   Sent mailbox, then STORE. **This is the second reason §6.3 generates its own
+   Message-ID** - without it, the appended copy is unfindable.
+3. If both fail: report `savedToSent: true, sentCopyUnread: true`. Cosmetic, and
+   named rather than hidden.
+
+A better path where available: hand-roll the `APPEND` with its literal so the
+flags and INTERNALDATE go in the command, which needs `LITERAL+`. Worth doing
+for FULL; the curl path plus the repair chain is enough for the FLOOR.
+
+### 6.5 Threading headers (later, but the ids are captured now)
+
+- `In-Reply-To: <parent-message-id>` - exactly one id.
+- `References:` = the parent's `References` value, then the parent's
+  `Message-ID` appended. When it would exceed the line budget, truncate **from
+  the middle**, keeping the **first** reference (which is the thread root, and
+  what every threading algorithm anchors on) and the last ~20.
+
+This requires the parent's `Message-ID` and `References` headers, which is why
+they are already in §4.1's `HEADER.FIELDS` list. Adding them later means
+re-fetching every message a consumer has already listed and stored - a cheap
+decision now, an expensive migration later.
+
+---
+
+## 7. Idempotent send
+
+### 7.1 The problem
+
+Job delivery is at-least-once. A claim that goes stale is reclaimed and the run
+executes again. For a database write that is handled by making the function
+idempotent; for an outbound email there is no undo and a duplicate is visible to
+a customer.
+
+### 7.2 The key
+
+`idempotencyKey`, caller-supplied, **required** for a send from a `job`, `cron`
+or `db` run - those are the kinds that get reclaimed. Optional for an `http`
+run, where the response simply reports `idempotent: false` so a caller is never
+under the illusion of a guarantee it did not ask for.
+`mail_idempotency_key_required` when missing on a retryable kind. Caller-supplied
+rather than host-derived because only the caller knows what "the same send"
+means - a body hash would make a re-serialised payload a different send, and
+`(function, run)` would make every retry a new send, which is the bug.
+
+### 7.3 The claim - the database's `duplicate_id` as the atomic check-and-set
+
+This is the right mechanism and it should be adopted. Read-then-write races
+between two concurrent runs of the same job; an insert on a unique document id
+does not.
+
+- Collection: `<project>:vectorapi_mail_sends`. **In the reserved `vectorapi_`
+  namespace**, so it is not addressable from `ctx.collections` or the documents
+  API - following the `vectorapi_secrets` precedent. A function that could
+  delete its own idempotency rows could re-send, which defeats the whole
+  mechanism.
+- Document id: `sha256(project \x1F account \x1F function_id \x1F key)` as hex.
+  - **Hashed** because the key is caller-supplied: it may be 512 characters,
+    contain anything, and must become a fixed-width id the DB accepts.
+  - **Namespaced by account and function** because two functions legitimately
+    both use the key `daily-digest-2026-10-08`, and a collision would make one
+    of them silently not send.
+  - **The body is not in the id.** If it were, a retry whose JSON re-serialised
+    with a different key order would hash differently and send twice.
+
+Sequence:
+
+```
+1. generate Message-ID
+2. insert { _id: H, state:'sending', message_id, body_sha256, recipients,
+            account, function_id, run_id, claimed_at }    <- BEFORE the send
+     -> AlreadyExists / duplicate_id  => §7.4
+3. SMTP transaction
+4. APPEND to Sent (best effort)
+5. patch { state:'sent', sent_at, smtp_response, saved_to_sent }
+```
+
+The insert branches on `FailureDetail.reason` to distinguish `duplicate_id` from
+`duplicate_values` - CLAUDE.md records that database 2.12.1 made these the same
+code with different reasons, and only `duplicate_id` means "already claimed".
+
+**Claim-before-send, deliberately.** It biases toward "never sends twice, may
+occasionally fail to send", and for business email that is the correct bias: a
+missing mail is noticed and retried deliberately, a duplicate to a customer
+cannot be recalled.
+
+A `body_sha256` field, compared on a repeat: same key, **different** body →
+`mail_idempotency_key_reused`, 409. The caller has a bug, and sending a
+different message under the old key, or refusing to send the new one silently,
+are both worse than saying so.
+
+### 7.4 What a repeat sees
+
+| stored state | age | action |
+|---|---|---|
+| `sent` | any | **do not send.** Return the stored result with `duplicate: true`, including the original `message_id` and `sent_at`. The correct, common case. |
+| `sending` | younger than the lease (`2 x` the SMTP command timeout ceiling, default 120 s) | **refuse, `mail_send_in_progress`, 409, retryable.** Another run is in flight or just died inside the SMTP transaction. We cannot know whether it reached DATA, so we do not guess. |
+| `sending` | older than the lease | the genuinely ambiguous case - §7.5 |
+
+### 7.5 The ambiguous case, and the probe that mostly eliminates it
+
+SMTP offers no way to ask "did you accept this". But we generated the
+Message-ID *before* the send and stored it, so there is a probe:
+
+> `UID SEARCH HEADER MESSAGE-ID "<stored id>"` in the Sent mailbox, and if that
+> is inconclusive, in the account's own mailbox (self-addressed sends) - found
+> means it was sent.
+
+That resolves most stale claims to a definite answer. It is not complete: it
+fails when save-to-Sent is off or Gmail-suppressed, when the APPEND is what
+failed, and when the server accepted the mail but we never got the `250`. For
+the residue, the policy is the **caller's** choice at send time:
+
+```
+onAmbiguous: 'refuse' | 'resend'      // default: 'refuse'
+```
+
+Default `refuse` → `mail_send_indeterminate`, 409, with
+`details.message_id` and `details.claimed_at`, and the row is patched to
+`state:'indeterminate'` so it is visible and never silently retried again.
+Default chosen because a duplicate business email is worse than a mail the
+operator can send deliberately once they have looked. `'resend'` exists for
+genuinely idempotent content (a digest, an alert) where a duplicate is harmless.
+
+### 7.6 Send succeeded but recording failed
+
+Step 5's `patch` fails. The row stays `sending`.
+
+- The next retry hits §7.4's `sending` path, ages out, runs the §7.5 probe, finds
+  the Message-ID in Sent and resolves correctly to "already sent" → no duplicate.
+- If the probe cannot run or finds nothing, the default `refuse` means the worst
+  outcome is a **refused retry**, never a duplicate. The asymmetry is deliberate
+  and is the whole point of claiming first.
+- Log at **error** with `run_id`, `message_id`, `idempotency_key` and the
+  account. This is the one state a human may have to resolve, so it must be
+  findable by Message-ID in the run log.
+
+The mirror case - crash between the claim and the send, so a row exists for mail
+never sent - resolves the same way: the probe finds nothing, the caller is told
+`mail_send_indeterminate`, and a deliberate `onAmbiguous:'resend'` sends it.
+
+### 7.7 TTL
+
+`ttl_seconds` on the claim row. The constraint is a floor, not a preference:
+
+> **The TTL must exceed the longest window in which a retry can occur**, which
+> is the job queue's maximum reclaim-plus-backoff horizon plus any human or
+> external retry. A TTL shorter than that reintroduces the duplicate it exists
+> to prevent, and does so rarely and unreproducibly.
+
+Default **30 days**, operator-settable, with a configured value below the job
+retention ceiling **refused at startup** rather than accepted - this is a
+setting whose misconfiguration is invisible until it causes a duplicate.
+
+Note that the *lease* (§7.4) is a timestamp comparison on `claimed_at`, not a
+shorter TTL. An expired row is indistinguishable from no row at all, so
+expiring a `sending` row early would turn "in progress" into "never sent".
+
+---
+
+## 8. The new-mail poll
+
+### 8.1 The marker
+
+Opaque, versioned, the same encoding family as the id so neither can be
+mistaken for the other:
+
+`k1.` + base64url of `account \x1F mailbox(wire) \x1F uidvalidity \x1F lastUid`
+
+Same reasoning as §1: self-sufficient, URL/JSON-safe, no `:`, and the version
+tag is what lets the marker grow a `modseq` field later (§8.5) without
+invalidating markers already stored in tenant documents. The function stores the
+marker itself, in its own collection - the host keeps no poll state, so a
+function can keep several markers for several purposes, and nothing in the host
+has to be migrated when a consumer changes its mind about what it polls.
+
+### 8.2 The query, and the `n:*` trap
+
+```
+UID FETCH <lastUid+1>:* (UID FLAGS INTERNALDATE ENVELOPE BODYSTRUCTURE ...)
+```
+
+**`n:*` always returns at least one message** - the one with the highest uid -
+even when `n` is greater than it. IMAP ranges are inclusive and `*` is the
+maximum existing uid, so `UID FETCH 5000:*` on a mailbox whose highest uid is
+4000 returns uid 4000. The same applies to `UID SEARCH UID n:*`. **The host must
+discard every returned uid `<= lastUid`.** Without this, every poll of a quiet
+mailbox re-delivers the newest message forever - and it looks like it works in
+testing, because during testing new mail keeps arriving.
+
+Why a uid and not `SINCE`/`INTERNALDATE`: `SINCE` has 1-day granularity and
+depends on the server's clock and timezone; a uid is monotonic and exact within
+a generation. A date-based marker either re-delivers a day or skips one.
+
+The poll is bounded by `limit` like any listing, and the response carries
+`more: true` plus a marker advanced only as far as the delivered messages, so a
+backlog is drained across several polls instead of blowing the budget. Marker
+advance is **never ahead of what was delivered** - that is what makes a crash
+after the poll but before processing safe.
+
+### 8.3 When UIDVALIDITY changes
+
+The two failure modes to design against are a silent skip and a full
+re-delivery. A mailbox recreated or migrated gets a new generation, and the old
+`lastUid` is meaningless: uid 4000 in the new generation may be message #3.
+
+Unlike a stale **id**, a stale **marker** is not an error. Reasons: an id is a
+request to address one specific message, and answering it wrongly is a
+correctness bug with no recovery; a marker going stale is an expected
+administrative event (mailbox recreated, server migrated, account rebuilt) and
+what to do about it is a **business decision the function owns**. So the poll
+returns facts, and the function chooses in advance:
+
+```
+onGenerationChange: 'report' | 'rebaseline' | 'rescan'    // default: 'report'
+```
+
+```
+{ generationChanged: true,
+  previous: { uidvalidity: 1337, lastUid: 4012 },
+  current:  { uidvalidity: 1402, uidnext: 57 },
+  messages: [],
+  marker: null,            // 'report': UNCHANGED - the caller keeps its old one
+  mailbox: "INBOX" }
+```
+
+- **`report` (default) - fail closed.** Deliver nothing, advance nothing, change
+  nothing. Nothing is lost, nothing is duplicated, and the operator sees it. Also
+  logged at **warn** by the host with the account and both generations, because a
+  poll that silently stops delivering is otherwise invisible for weeks. A
+  function that ignores `generationChanged` stops receiving mail, which is loud;
+  the alternative failure modes are quiet.
+- **`rebaseline`** - set the marker to the current generation at `UIDNEXT - 1`
+  and deliver nothing. A deliberate, acknowledged gap: everything in the new
+  generation before now is treated as already-seen. For a poll that only cares
+  about mail arriving from now on.
+- **`rescan`** - deliver the newest `limit` messages of the new generation and
+  set the marker accordingly. **Bounded by `limit`, never the whole mailbox** -
+  this is the mode that must not be able to re-deliver 200 000 messages. The
+  function will see mail it has already processed, which is why whatever it does
+  with a message must be idempotent anyway (§8.4).
+
+`UIDNEXT` comes from the `* OK [UIDNEXT n]` of the SELECT. Some servers omit or
+misreport it; fall back to the uid of `UID FETCH *:* (UID)`, which is one
+message and cheap.
+
+### 8.4 Two things the marker cannot and should not hide
+
+- **Delivery is at-least-once here too.** A poll that returns messages and then
+  the run dies before storing the new marker re-delivers them. Correct and
+  unavoidable - the marker advance must come *after* the function's own
+  processing, which means the function must be idempotent about what it does with
+  a message. Same rule CLAUDE.md already states for cron and db functions. The
+  message id (§1) is the natural dedupe key and is stable within a generation.
+- **A uid-based poll sees "new to this mailbox", not "newly sent".** An old mail
+  copied or moved into the inbox gets a fresh high uid and *will* be delivered,
+  with an old `INTERNALDATE`. That is the correct answer to the question asked,
+  but it can surprise, so the poll always exposes `receivedAt` and the function
+  can judge. Conversely, a message moved out and back changes uid and is
+  re-delivered.
+- **A uid-based poll cannot see flag changes.** Mail marked read in Outlook does
+  not change its uid, so the poll will not report it. For the FLOOR that is fine
+  (we poll for arrivals). §8.5 is the upgrade.
+
+### 8.5 The upgrade path, and why the marker is versioned
+
+`CONDSTORE`/`QRESYNC` (RFC 7162) add `HIGHESTMODSEQ`, which makes
+`UID FETCH 1:* (FLAGS) (CHANGEDSINCE <modseq>)` report *changes* rather than
+arrivals - the only way to learn that something was read or flagged elsewhere.
+That becomes a `k2.` marker carrying `modseq` alongside `lastUid`, and a `k1.`
+marker upgrades by keeping its `lastUid` and starting the modseq at the current
+`HIGHESTMODSEQ`. This is the entire reason the marker is opaque and tagged
+rather than a bare integer the consumer could have been handed.
+
+**`IDLE` is out of scope and should stay out.** It is a long-lived stateful
+command and is fundamentally incompatible with a pooled runtime under a wall
+budget. The cron poll is the answer, and the marker design above is what makes
+it correct.
+
+---
+
+## 9. Attachments and memory
+
+### 9.1 The arithmetic
+
+The JS heap limit is 64 MiB. An 8 MB attachment is ~10.9 MB as base64, and it
+does not cross the boundary once: the host builds it into a `nlohmann::json`
+string, serialises that, the engine parses it, and the resulting JS string is
+another copy. Transient peak ~30-40 MB on top of whatever the run already holds,
+inside a 64 MiB runtime - and an OOM poisons the runtime, so the pool destroys
+it rather than leasing it out. One 8 MB attachment can therefore cost a pool
+slot. `ctx.files` already caps at 1 MiB (`kCtxFileMaxBytes`) for precisely this
+reason.
+
+**The bytes must never enter the heap.**
+
+### 9.2 The FLOOR needs none of this
+
+The consumer's stated need today is a **has-attachments flag**, and
+`BODYSTRUCTURE` provides it - plus filename, media type, size and disposition
+for every part - at **zero extra bytes**. An attachment *list*
+(`[{partId, filename, contentType, size, inline, contentId}]`) is also free from
+the same walk.
+
+**Ship that. Nothing crosses the boundary, so there is no memory design to get
+wrong.** §9.3 is the design for the later PDF/Office step, specified now so the
+return shapes do not have to change.
+
+### 9.3 Handles, not bytes
+
+The host streams the part out of `BODY.PEEK[<partId>]`, transfer-decodes it
+streaming (base64/QP), writes it to a host-side per-run buffer, and hands the
+script a **handle**:
+
+```
+{ attachmentId: "<128-bit random token>",
+  filename: "invoice.pdf", contentType: "application/pdf",
+  size: 8123456, sha256: "..." }
+```
+
+- `attachmentId` is a random token in a per-run map, **not a path and not
+  forgeable** - the same reasoning the egress guard applies to a pinned address.
+- Lifetime is the run. Freed at run end, and on the `poisoned()` destruction
+  path, so a timed-out run cannot leak a buffer into the next tenant's.
+
+What the script can do with a handle, none of which puts bytes in the heap:
+
+1. **Pass it to `ctx.fetch` by reference** - `bodyAttachment: handle` - so an
+   8 MB PDF can be posted to an extraction service without ever being a JS
+   string. This is probably the consumer's real need.
+2. **Ask the host to extract text**, capped: `handle.text({ maxChars: 4000 })`.
+   Given that the consumer's "read-only PDF/Office up to ~8 MB" almost certainly
+   means *read its text*, this is the right primitive and the bytes never need to
+   be handed over at all. (The extractor itself - poppler, or an external
+   service - is out of scope here.)
+3. **Store it as a project file.** This conflicts with a stated rule:
+   `ctx.files` is read-only by design, because writing a tenant's asset is a
+   management act. The bytes also originate *outside* the tenant, from arbitrary
+   senders, which is exactly why writing them is a policy question rather than a
+   convenience. **Deferred to the security-model agent**, flagged as a real
+   tension rather than assumed resolved.
+4. **Materialize it as base64** - only under `max_attachment_inline_bytes`, for
+   the small-attachment convenience case.
+
+### 9.4 Three caps, three different questions
+
+Following the project's own `max_file_bytes` / `kCtxFileMaxBytes` precedent,
+where separate caps answer separate questions:
+
+| setting | default | question it answers |
+|---|---|---|
+| `mail.max_attachment_fetch_bytes` | 8 MiB | what the host will pull over the wire at all |
+| `mail.max_attachment_inline_bytes` | 256 KiB | what may be materialized as base64 **into the heap** |
+| `mail.max_attachment_bytes_per_run` | 32 MiB | the total a single run may buffer host-side, so a loop over 50 attachments cannot fill the host's memory or disk |
+| existing `max_file_bytes` | 2 MiB | what may be **stored** as a project file |
+
+Each refuses by name with the limit in the message -
+`mail_attachment_too_large`, `mail_attachment_run_budget_exceeded` - rather than
+truncating. Half a PDF is worse than an error, which is the reasoning already
+written into `ctx.files.get`.
+
+**`BODYSTRUCTURE` is checked before any fetch**, so an oversized attachment is
+refused without moving a byte. And a partial fetch (`<0.N>`) means "is this
+really a PDF" costs 1 KB, not 8 MB.
+
+---
+
+## 10. Summary - FLOOR vs FULL
+
+**FLOOR (first consumer), in dependency order:**
+
+1. IMAP response parser (atoms / quoted / NIL / lists / **length-counted
+   literals**), pure, fuzzed, dev-host-testable. The critical path and the
+   biggest risk.
+2. `mail/message_id.hpp` - encode/decode/`checkGeneration`, pure, with the
+   stale-generation refusal floor in a test.
+3. `mail/read_policy.hpp` - `resolveMarkRead()`, pure, nine cases; the
+   `BODY.PEEK`-only invariant asserted by a test over generated commands.
+4. `mail/budget.hpp` - `resolveMailBudget()`, pure, connect ≤ half.
+5. BODYSTRUCTURE walker: text-part selection, `hasAttachments`, attachment list.
+6. RFC 2047 + 2231 decode, iconv + alias table, base64/QP decode (incl. partial
+   trimming), the HTML stripper.
+7. Listing: the §4.1 FETCH + the §4.2(a) second preview command.
+8. SEARCH with `scope` (body opt-out), the added window, `truncated` /
+   `responseCapped` / `matched`.
+9. Mark-read as an explicit `UID STORE +FLAGS.SILENT (\Seen)`.
+10. Fetch one: subject/from/to/cc/received + text body ≤4000 + attachment flag.
+11. Send: generator (multipart/related + alternative + cid), the envelope
+    invariant, Reply-To, generated Message-ID, APPEND to a SPECIAL-USE-detected
+    Sent with the Gmail `auto` rule.
+12. Idempotent send via `duplicate_id` on `<project>:vectorapi_mail_sends`,
+    with the Message-ID probe and `onAmbiguous: 'refuse'`.
+13. Poll: `k1.` marker, `lastUid+1:*` with the `<= lastUid` discard,
+    `onGenerationChange: 'report'`.
+
+**FULL (deferred, shapes already fixed above):**
+
+flags and custom keywords (with PERMANENTFLAGS checking) · MOVE/COPY with
+`COPYUID`, and safe delete via `\Trash` or `UID EXPUNGE` · mailbox CRUD,
+LIST/NAMESPACE with the server's real delimiter · modified-UTF-7 display names ·
+`ESEARCH`/`SORT`/`THREAD`/`SEARCHRES` · `CONDSTORE`/`QRESYNC` and the `k2.`
+marker · threading headers (ids already captured) · attachment handles and text
+extraction · best-effort multi-recipient send with per-recipient idempotency ·
+hand-rolled `APPEND` with flags via `LITERAL+`.
+
+**Recommended against:** POP3 (id scheme specified, capability gaps named, do
+not ship) · `IDLE` · libetpan/vmime · a local MIME parser on the IMAP read path ·
+`CURLOPT_MAIL_RCPT_ALLOWFAILS` in the FLOOR · auto-creating a Sent folder ·
+relying on `EXAMINE` or `\Recent` for anything.
+
+**The three things most likely to be wrong in this document**, in order: whether
+curl's IMAP state machine handles a synchronizing-literal continuation inside a
+`CUSTOMREQUEST` (§3.3), whether curl delivers untagged `SELECT` response codes
+to the write callback reliably enough for the per-command UIDVALIDITY check
+(§0.2), and whether mail work can fit an HTTP wall budget at all (§3.4 - the
+expectation is that it cannot, and that mail belongs in job runs).