diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 015bd50..5f146c1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -31,7 +31,7 @@ jobs:
- run: cargo test --locked --no-default-features --features standalone --test platform_native
- run: cargo check --locked --all-targets --no-default-features --features standalone
- run: cargo test --locked --no-default-features --features standalone process
- - run: cargo test --locked --no-default-features --features standalone --test cli agent_disabled_build_has_no_worker_or_agent_rpc
+ - run: cargo test --locked --no-default-features --test cli agent_disabled_build_has_no_worker_or_agent_rpc
standalone-app-macos:
name: Standalone app (macOS arm64)
diff --git a/AGENTS.md b/AGENTS.md
index c36b505..ad9a443 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -10,575 +10,63 @@ Test with synthetic messages and temporary application directories. Never commit
The upstream rules below apply unchanged. Some historical architecture prose describes earlier implementations; confirm the current source before extending a module.
-## Colors
+## Required reading by task
-- Use colors from the active Omarchy system theme. Do not hard-code UI colors.
-- Pass semantic colors down from `App.qml` as required component properties so
- a theme change propagates through every view.
-- Derive muted, hover, and selected variants from an inherited color with
- alpha, or from `Style.normalFillFor` / `hoverFillFor` / `selectedFillFor`.
- Do not introduce literal fallback grays.
-- Secondary text mixes the foreground toward the **background**, not
- `Qt.darker`. On a light theme, darkening an almost-black foreground makes
- "secondary" text heavier than body text — the opposite of what it means.
-- `tests/test_source.sh` enforces the no-literal-colors rule. Keep it updated
- rather than working around it.
+Read the relevant document before changing its area; these contain constraints that are easy to miss in the code.
-## Layout
+| Area | Required reading |
+| --- | --- |
+| Keyboard, focus and navigation | [docs/KEYS.md](docs/KEYS.md) |
+| Provider adapters, capabilities and account identity | [docs/providers/README.md](docs/providers/README.md) |
+| HEY | [docs/providers/hey.md](docs/providers/hey.md) |
+| IMAP, SMTP and Proton Bridge | [docs/providers/imap.md](docs/providers/imap.md) |
+| JMAP discovery and streaming | [docs/providers/jmap.md](docs/providers/jmap.md) |
+| Message HTML, images, direction and outgoing MIME | [docs/MESSAGE-RENDERING.md](docs/MESSAGE-RENDERING.md) |
+| Network requests, credentials, subprocesses and security reviews | [docs/SECURITY-BOUNDARIES.md](docs/SECURITY-BOUNDARIES.md) |
+| Backend APIs, binary pins and releases | [docs/BACKEND-RUNTIME.md](docs/BACKEND-RUNTIME.md) |
-Rust lives in `src/`; Qt/QML and its JavaScript live in `ui/`. Keep CLI
-argument handling in `src/cli/`, protocol and process dispatch in `src/backend/`,
-and shared business modules beside them, such as `src/account/` and `src/message/`.
-`tests/` holds integration tests; Rust unit tests live with their modules and
-UI unit tests live in `ui/tests/`.
+## Structure and boundaries
-**Within each layer, group by module, not by file type.** A UI module holds whatever doing its job
-takes — the rules in `.js`, the object in `.qml`, side by side. There is no
-directory of "all the JavaScript": that arrangement puts a provider's parsing
-three directories away from the client that calls it.
+- Group by module, not file type. Rust lives in `src/`, CLI handling in `src/cli/`, and dispatch in `src/backend/`. QML and its JavaScript live together under `ui/`. Rust unit tests live with their modules; UI tests live in `ui/tests/`; integration tests live in `tests/`.
+- Rust owns mail business logic and durable agent jobs. QML owns presentation and interaction state, communicating with the persistent backend over stdin/stdout rather than invoking CLI commands. See `docs/BACKEND.md` and `docs/ARCHITECTURE.md`.
+- QML JavaScript libraries start with `.pragma library` and use `var` and `function`, not `const`, `let`, arrows or template literals. Put testable presentation rules there. Tests load module paths, e.g. `load("cache/Cache.js")`; `ui/tests/load.js` resolves QML `.import` chains.
+- List new QML files in the Makefile's lint inputs and import other modules explicitly.
+- `Service.qml` is shell-constructed and must declare no required properties. The shell injects only `shell`, `manifest`, `pluginRegistry`, and `barWidgetRegistry`; settings arrive through the bar widget's `applySettings`.
-| Module | What it is |
-|-----------------|--------------------------------------------------------|
-| `ui/` | `Service.qml`, `BarWidget.qml`, and `App.qml` are the shell entry points. The root `manifest.json` names their `ui/` paths. |
-| `ui/providers/` | Everything that differs between mail services: a description per provider, the registry over them, the protocol each speaks, and the pair of objects — signs in, fetches — that each needs. |
-| `ui/account/` | One mailbox and the list of them. `MailAccount.qml`, `Accounts.js`, and the rules in `Model.js` about what a list does after an action. |
-| `ui/cache/` | What a query result and a message body are kept in, and the two objects that keep them. |
-| `ui/calendar/` | The calendars an account serves and their events: the sources in `Sources.js`, the rules in `Calendar.js`, the controller that reads and writes them, and the range cache. |
-| `ui/message/` | A message's own content: parsing it (`Message.js`) and making it safe to draw (`Html.js`). |
-| `ui/components/` | Views. They draw what they are given and decide nothing. |
-| `ui/agent/` | The message agent: presentation helpers in `Agent.js` and the thin `AgentRunner.qml` RPC adapter. Rust `src/agent/` owns context, durable task state and detached native worker processes; see `docs/AGENT.md`. |
+## UI
-- `tests/test_qml_names.py` checks the entry points under `ui/`, and any QML
- file the Makefile does not list — a file `qmllint` never sees is a file nobody
- checks.
-- QML resolves a type by name from its own directory, so a file that builds a
- type from another module imports that directory: `Service.qml` has
- `import "account"`, `ui/account/MailAccount.qml` has `import "../providers"` and
- `import "../cache"`.
+- Use the active Omarchy theme. Pass semantic colors from `App.qml` as required component properties; derive variants with alpha or `Style.normalFillFor` / `hoverFillFor` / `selectedFillFor`. Secondary text mixes foreground toward background, never `Qt.darker`. Provider artwork retains its original colors.
+- Render sender-controlled labels with `Text.PlainText`, never `AutoText`. Rich message bodies go through the sanitizer. Do not fetch remote message resources directly through Qt.
+- Never convey state by color alone. Use accurate labels; suffix actions that open another dialog/page/browser/terminal workflow with `...`.
+- An open popup keeps its trigger selected. Anchor to the control's edge, not the pointer. Place after opening and on height changes; on overflow, flip, clamp to the window, then clamp to zero.
+- Keep content direction separate from interface layout; no `LayoutMirroring`.
-## Backend API compatibility
+## Backend compatibility
-- `backend-version` is the installed plugin's exact binary pin, independent of
- the development Cargo version. Never resolve main/latest or a PATH binary for
- the plugin. Keep old release assets available and never overwrite them.
-- `backend-api.json` versions the public API contract. Internal Rust changes do
- not require a release, but new QML dependencies on methods, parameters,
- responses or error semantics require updated contract fixtures and a higher
- API revision — one step past `releasedApiVersion`, with the new methods and
- cases named under `unreleased`, and the feature checking the connected backend against its fixed minimum API revision (for example API 2 for event suggestions). Keep that requirement after release; `released` and `unreleased` describe publication state, not a feature's permanent capability. A second step
- waits for a release. See "Released and unreleased" in `docs/BACKEND-RUNTIME.md`.
-- The required Published backend merge gate tests the actual pinned release with
- current QML codecs. Extend the contract tests for changed behavior; an inventory
- check alone does not prove compatibility. Source fingerprints are release
- provenance, not a requirement that future Rust source remain unchanged.
-- Plugin-local exact version and API handshake checks must both remain in place.
- The missing-apiVersion exception applies only to the historical 0.9.0 binary
- with API 1. See `docs/BACKEND-RUNTIME.md` for the release process.
+- `backend-version` is the plugin's exact binary pin, independent of Cargo's development version. Never substitute main/latest or a PATH binary. Keep both exact-version and API handshake checks; missing `apiVersion` is allowed only for historical 0.9.0/API 1.
+- New QML dependencies on methods, parameters, responses or error semantics require contract fixtures and an API revision exactly one past `releasedApiVersion`, named under `unreleased`. Gate each feature on its fixed minimum revision even after release. Internal Rust-only changes do not require a release.
+- The Published backend gate exercises the actual pinned release with current QML codecs. Inventory checks and source fingerprints do not replace behavioral compatibility tests.
-## JavaScript libraries
+## Security
-- The `.js` files are read by the QML engine. They start with `.pragma library`
- and use `var` and `function` only — no `const`, `let`, arrow functions, or
- template literals. `tests/test_source.sh` finds them wherever they are, so a
- new module is covered without being added to a list.
-- UI decisions belong in these libraries so node tests can reach them without
- a compositor. Mail fetching, parsing, classification, organization and updates
- are migrating into shared Rust modules; see `docs/BACKEND.md`. QML retains
- presentation and interaction state and communicates with a persistent backend
- over stdin/stdout, not by invoking CLI commands.
-- One JS resource may build on others with QML's `.import "Other.js" as Other`,
- which is how `ui/providers/Registry.js` is assembled out of `Gmail.js`,
- `Outlook.js`, `Hey.js`, `Jmap.js` and `Imap.js` — and those out of `GmailApi.js`,
- `HeyCli.js` and `JmapProtocol.js` in turn, because where a message lives on
- the web, or what a query string means, is a fact about the service rather
- than about the registry. `ui/tests/load.js` resolves the chain the same
- way the engine does, so the tests exercise the real files.
-- Tests name the module path: `load("cache/Cache.js")`. A bare filename would no
- longer say where the thing lives.
+- Treat mail, server responses, URLs, filenames and persisted settings as untrusted. Validate at the consuming boundary; encoding is not sanitization.
+- Keep credentials out of argv, logs and world-readable settings. Use synthetic credentials and controlled targets for tests.
+- Preserve account/draft ownership, human approval of AI proposals, and normal outbox dispatch. Model text must not supply routing or permission to send mail.
+- Every review states **Security: PASS / BLOCK / NOT VERIFIED** for the affected boundaries. Missing evidence or a security failure blocks approval/release. Security regressions must verify the forbidden effect did not happen, not merely that an error was returned; follow `docs/SECURITY-BOUNDARIES.md`.
-## Entry points
+## Repository and pull requests
-- `Service.qml` is constructed by the shell itself, which injects only `shell`,
- `manifest`, `pluginRegistry`, and `barWidgetRegistry`. It must declare **no**
- required properties: one the shell does not know about makes the whole plugin
- fail to instantiate, with the reason buried in a console warning.
-- Plugin settings reach the service from the bar widget via `applySettings`,
- because the shell hands settings to the widget rather than to the service.
+- Keep runtime assets, source, tests and maintained documentation in the tree. Keep planning notes and screenshots outside it. Upload PR screenshots to GitHub attachments; tracked files must stay under 128 KiB.
+- UI PRs require labeled before/after screenshots of every changed view/state at matching dimensions, theme and scale, using synthetic or redacted data. Update them when the UI changes and explain the visible differences.
+- Commit/PR titles name the concrete machinery and action. Use `Fix ` for bugs, `Add ` for features, otherwise an accurate imperative. Prefix AI changes with `ai: `, repository documentation with `docs: `, website work with `website: `, and build/CI/release/tooling maintenance with `chore: `. Choose one prefix from the primary outcome.
+- Reconcile the title and description with the complete final diff whenever scope changes. Describe shipped behavior, architectural reasons and verification actually performed. User-visible PRs include concise bullets under `## Release Notes`.
+- Markdown prose uses one source line per paragraph.
-## UI labels
-
-- Suffix button and menu labels with `...` when activating them opens a dialog,
- a page, a browser, or a terminal workflow instead of completing the action
- immediately.
-- Never let colour alone carry state. Unread is a dot, a heavier weight, and a
- brighter subject, because some themes put the accent close to the foreground.
-- Prefer the shorter label when both are honest, but never buy brevity with
- accuracy: "Mark these read" acts on the messages that are loaded, so it does
- not claim to mark all of them.
-
-## Direction
-
-Which way a message runs is a fact about the mail, not about the window. The
-interface is not mirrored and there is no `LayoutMirroring` anywhere;
-`tests/test_source.sh` enforces that, because "RTL support" is the name of two
-different features and only one of them is here.
-
-- Qt already resolves each paragraph and each `Text` from its own first strong
- character, and it is good at it. Leave it alone wherever it is right. It
- elides the *logical* end of a right-to-left string under `Text.ElideRight`,
- resolves each `
`-separated line of a plain body separately, and needs no
- help with an Arabic subject or an Arabic paragraph.
-- `ui/message/Direction.js` exists for the three places it is wrong or absent, and
- for nothing else. Adding a fourth caller is a decision, not a formality.
-- **A subject is asked with `resolveSubject`, never `resolve`.** A reply prefix
- is Latin whatever the thread is written in, so `Re: مرحبا` reads left-to-right
- to anything taking the first strong character at face value — which is every
- message in a thread after the first, and most of a mailbox.
-- **Qt honours the `dir` attribute and ignores the CSS `direction` property.**
- `promoteDirection` translates one into the other next to
- `promoteImageDimensions`, which is there for the same reason on `width`. A
- template written for a browser states direction only in CSS.
-- **The body's `dir` and the stylesheet's physical sides are one statement.**
- Qt reads `margin-left` and has never heard of `margin-inline-start`, so a side
- is chosen when the sheet is built; and Qt places a list marker on the side the
- block runs from, so a sheet that indents a list from the right while the block
- is still left-to-right does not move the bullet, it **drops** it. Writing one
- without the other was tried and looked exactly like that.
- `baseDirectionAttribute` keeps them together and `tests/test_source.sh` keeps
- them that way.
-- A base direction is a **default, not an override**: a sender's own `dir` — or
- a `direction` in their CSS, which `promoteDirection` turns into the same thing
- — still wins element by element inside it. That is what makes supplying one
- safe on a message nobody has inspected.
-- A `Text` with no answer to give is left alone rather than assigned Qt's own
- default back. `undefined` on `horizontalAlignment` restores natural alignment;
- it does not warn.
-- **A message being sent states its direction or loses it.** This is the fourth
- caller, and it was a decision. Qt resolves a compose field from the text in
- it, so a writer sees their own paragraph against the right edge as they type
- — but none of that travels with the message. A `text/plain` part states no
- direction at all, and a client with nothing to read falls back to
- left-to-right, which is what a Persian mail written here looked like in
- someone else's inbox. `buildRawMessage` asks `outgoingDirection`, which reads
- the body by the same rule the reader uses, so a message arrives looking the
- way it looked while it was written.
-- **A right-to-left body grows a `text/html` twin; a left-to-right one grows
- nothing.** The plain part stays exactly as it was and stays listed first, and
- the twin is the least markup that can carry a direction — the text escaped,
- its line breaks kept, `dir` on the `
`, and no styling of any kind. It is
- not a rendering of the message, it is a statement about it. Left-to-right is
- already what a bare `text/plain` means to every client, so stating it would
- make every message ever sent `multipart` in order to repeat the default —
- the same reason `Html.js` gives a document no `dir` when nothing chose one.
-- **A nested MIME boundary is a prefix, never a suffix.** `splitMultipart` finds
- a delimiter by searching for `--` and the boundary anywhere in the body, so an
- inner boundary that began with the outer one would be found by the outer scan
- as well and the message would come apart at the wrong line. `nestedBoundary`
- puts its tag in front for that reason, and `ui/tests/test_message.js` asserts the
- inner delimiter cannot be read as the outer one.
-- The calendar reply keeps its two parts and gains no twin. An RSVP's sentence
- is generated rather than composed, so there is no writer's direction to carry,
- and `multipart/alternative` holding exactly `text/plain` and `text/calendar`
- is the shape every calendar server recognises a reply in.
-- Qt ignores `dir` on a `` — on a wrapping `` inside one, too. Nothing
- is done about it: text inside a cell still resolves from its own first strong
- character, which covers the case that actually arrives.
-
-## Popups and their triggers
-
-- A control that opens a popup holds a selected style for as long as that popup
- is on screen. A trigger that looks untouched while its own menu is up leaves
- the menu looking unattached to anything, and leaves the user without an answer
- to "which of these opened it".
-- Anchor a popup to the trigger's own edge, not to the pointer. `mapToGlobal(0, 0)`
- on the control, never the click position: the menu should land in the same
- place however the control was pressed.
-- Place a popup *after* it opens, and again whenever its height changes. A
- `QQC.Popup` does not build its contents until the first `open()`, so its
- height is still zero while any placement code is deciding whether it fits —
- the first open lands somewhere different from every one after it, which is the
- bug this rule exists to prevent.
-- A popup that would overflow flips to the other side of its trigger, then
- clamps to the window edge, then clamps to zero. All three, in that order.
-
-## Keys and focus
-
-The design and the full table are in `docs/KEYS.md`; read it before touching a
-key. What matters while working:
-
-- Every binding lives in `ui/keys/Keymap.js` and nothing else describes one. The
- shortcut sheet and the status hints render from it, and a test asserts
- `docs/KEYS.md` matches it. Three hand-written copies used to exist and had
- already drifted apart.
-- The context is the only guard. Name the contexts a key means something in;
- there is no second question to answer. A text-entry context binds no bare key
- but `Escape`.
-- The context owns the keyboard: changing it moves the focus, and a context that
- types into nothing parks the keyboard on a plain `Item`. Never hand focus back
- by calling `forceActiveFocus()` on the focus scope — that re-elects the field
- being left, so it does nothing and the dismissed field keeps eating keys.
-- `focus: true` may not sit on a component that can be invisible while holding
- it, and a component in a context does not place its own focus — the context
- does. Two mechanisms for one thing is the bug this design replaces.
-- Route keys through `KeyRouter`, never a `Keys.on...Pressed` handler: a window
- `Shortcut` beats a focused item's `Keys` handler, so a local one looks live and
- never runs. Anything `Escape` should do belongs in `goBack()`.
-- **A key is not a button.** A capability the provider does not declare loses
- its button, but `e` and `s` are bound in every mail context whatever mailbox
- is open — so the same action has to be refused in `MailAccount.act` *before*
- the optimistic update, and the status row's hints are filtered by
- `Keymap.hintsFor`'s second argument. Without both, HEY — which has neither an
- archive nor a star — moved the row out of the Imbox and said "Archived" for a
- request no server ever saw.
-- **No chords.** Qt puts a deadline on an unfinished key sequence —
- `styleHints.keyboardInputInterval`, 400ms — so `g` then `i` half a second
- later does nothing at all and says nothing about why. The mailboxes were
- reached that way and are numbered now. A modifier has no deadline.
-- A held modifier is the one thing `KeyRouter` cannot own, because a modifier
- alone cannot be a `Shortcut`. `App.qml` watches `Key_Alt` with a `Keys`
- handler to name the rail's rows, accepts nothing, and clears on `activeFocus`
- rather than on the release — Alt+Tab takes the release to another window.
-- `KeyRouter` builds its shortcuts with an `Instantiator`. A `Repeater` builds
- only `Item`s, so it creates no `Shortcut`s at all and every key goes dead.
-- A `QQC.Popup` with `CloseOnEscape` consumes `Escape` itself. Do not add a
- branch for an open popup; do add one for a plain overlay like the sheet.
-- **An open `QQC.Popup` consumes every other key too**, and that is the one
- place the rule above inverts. It takes the key before the shortcut map sees
- it — `focus` true or false, bare or modified — so inside a popup a `KeyRouter`
- binding is what looks live and never runs, and a `Keys` handler on the
- popup's `contentItem` is the only thing that works. The account switcher
- and the agent prompt are the components that answer keys themselves, for
- this reason.
- `ui/tests/qml/tst_popup_keys.qml` asserts both halves, so the exception cannot
- be tidied back into the rule by someone who only read the rule.
-- The mouse does not move the keyboard's cursor. Qt re-reports hover when
- content moves under a still pointer and the list scrolls to follow the
- keyboard, so a hover that wrote `cursorId` pulled it back to whatever the
- mouse was resting on and `j` went nowhere. A row draws its own hover.
-- The list cursor and the open message are two different things. `cursorId` is
- where the keyboard is; `selectedId` is what the reader shows. Move the cursor
- with `Model.cursorAfterOffset`, and bring the row on screen with
- `Model.contentYToReveal` — the list is a `Column`, so there is no
- `positionViewAtIndex`.
-
-## Providers
-
-- A mailbox is a **provider**: `gmail`, `outlook`, `hey`, `jmap`, or `imap`, listed in that order because IMAP is the answer for a server the other four do not name and a chooser that opened with it would ask the question backwards. JMAP goes in front of it for that reason and one more — a server speaking both is better read over JMAP, so somebody who has one should meet it before settling for the catch-all. `Provider.js` is the only place that knows the differences — which mailboxes exist, what a query string means, what the service can be asked to do, and how it signs in. Nothing above it branches on a provider id.
-- Two objects make a provider work: something that signs in (`AuthManager`, `OutlookAuth`, `HeyAuth`, `JmapAuth`, `ImapAuth`) and something that fetches (`GmailApiClient`, `HeyClient`, `JmapClient`, `ImapClient`). `MailAccount` builds one pair through a `Loader` and drives them through an identical interface — same method names, same arguments, same callback shape. Adding a provider is those two files and a registry entry.
-- **Every client hands back Gmail's message resource**: a headers array, a MIME
- tree, part bodies in base64url — and, from a provider whose listing collapses
- to conversations, a `thread` block on each row (`Message.threadOf`), which
- every other provider leaves absent and the row reads as a count of 0. That is
- what lets one list, one reader, one cache and one set of actions serve every
- provider. `Message.parseRfc822` is
- the adapter that rebuilds that shape from the wire format, and it is worth
- keeping even where IMAP's own structures would have been more natural.
- HEY never serves an RFC 822 message at all, so `HeyClient.toMessage`
- *composes* the resource from a posting and a thread read rather than parsing
- one — same shape, no parse.
-- A detail read is authoritative about what it carries and silent about the
- rest, which is `Model.detailSummary`. HEY reads a conversation rather than a
- message and so answers with no subject line of its own; replacing the row
- wholesale blanked the subject the list had drawn.
-- A capability the provider does not declare is a **button the panel does not
- draw**. Offering one that fails is worse than omitting it: it fails after the
- user has committed to it, with the row already moved. IMAP therefore has no
- "report spam" — moving a message to a Junk folder teaches a server nothing,
- and a button that quietly meant that is a promise the provider cannot keep.
-- **A provider's capability list is a ceiling**: an account may refuse one the provider declares and may never add one it does not, which is what the `refusals` argument to `Registry.can` and `Registry.refusal` weighs beside it, and what `Registry.mailboxes` reads to drop a rail row whose role never resolved — so a JMAP server with no Archive mailbox loses the row, the button and the `e` hint together, and says why.
-- **`conversations` is a different question from `threads`**: a server-side thread id does not settle whether the *listing* collapses, so they are two capabilities, and a provider declaring the first gets one row per conversation and a rail of that conversation's members down the side of the reader, walked with `n` and `p`.
-- An account id is the address for Gmail and ` :` for the others, the address lower-cased either way: `hey:you@example.org`, `jmap:you@example.org`, `imap:you@example.org`. One address can legitimately be more than one mailbox, and a Gmail account keeping the bare address is what stops an upgrade from having to migrate cache directories, keyring entries and the active account.
-- Where a message and a mailbox live on the web is a provider question, not
- `MailAccount`'s. `Registry.webMessageUrl` and `webBoxUrl` are that seam; the
- Gmail call that used to sit in `MailAccount` would have opened Gmail for the
- second provider that declared a web UI.
-
-## HEY and the `hey` client
-
-- HEY publishes no API, no IMAP and no POP, so the interface is `hey`, the
- command line client 37signals ship. **Do not fill that gap by driving the
- private endpoints app.hey.com uses**, which is what this provider waited for
- `hey` rather than doing: it would ask a user for their HEY password so it
- could be replayed against an interface carrying no compatibility promise, and
- it would break on a deploy nobody announced.
-- `hey` owns the whole credential. It performs the OAuth flow, keeps the token
- in the keyring and refreshes it; `HeyAuth` holds a yes or a no and the path to
- the program, and has nothing worth redacting. Signing out is `hey auth
- logout`, which signs the machine's HEY client out of everything that uses it —
- the setup page says so next to the button, because a sign-out that only forgot
- locally would be undone by the next status read.
-- `HeyCli.js` is the argument vectors and the answers, the way `Imap.js` is the
- protocol: no process, no message format. Every command asks for `--json`, so
- nothing ever parses a rendered table, and the envelope's `ok` is the check
- rather than the exit status — the CLI reports some refusals in JSON and still
- exits 0.
-- **A thread answers to two numbers.** The posting id is its place in a box and
- is what `seen`, `move`, `trash` and `spam` take; the topic id is the
- conversation and is what `threads` and `reply` take. A message id here is
- `:` for that reason, the way an IMAP one carries its folder.
-- **Unseen is the absence of a seen.** HEY's JSON omits an empty field, so a
- posting nobody has read carries no `seen` key at all. There is no unseen count
- and no unseen box either, so the badge is a listing and a tally — which is why
- the unread query is the one that names a `--limit`.
-- **`--limit` and paging cannot both be had.** The CLI reads pages until it has
- the number asked for, then truncates *and drops the cursor*, so a limited
- listing can never be continued. Ordinary listings therefore ask for no limit
- and take HEY's own page, and the page size the user configured is applied in
- `HeyCli.pageOf` — its token is an offset into that page plus HEY's cursor for
- it.
-- An optional flag the installed `hey` has never heard of fails the whole
- command, and the release most people have is older than `--allow-partial`.
- `HeyClient` drops the flag the usage error names and asks again, then
- remembers — which is also how `--html` upgrades a HEY mailbox from text
- bodies to the sender's own markup with nothing here to change. Every flag
- dropped this way must be boolean; dropping one that took a value would leave
- its value behind as a positional argument.
-- HEY has no star and no archive, and neither is faked. A star that quietly
- moved a thread to Set Aside, or an archive that filed it in Paper Trail, is
- exactly the promise `Registry.capabilities` exists to stop being made.
-
-## Imap.js and the transport
-
-- **Proton Bridge requires STARTTLS.** Native loopback connections upgrade before authentication, including custom Bridge ports; 993/465 select implicit TLS. The explicit `insecure` exception accepts the self-signed certificate only on loopback; it never disables encryption or allows a failed upgrade to fall back to plaintext. Remote connections retain standard STARTTLS ports and implicit TLS on other ports, always with certificate verification. Synthetic plaintext peers require an explicit `testPlaintext` setting compiled only for unit tests or `integration-test-credentials`, never normal builds.
-
-- `Imap.js` is the protocol and nothing else: every string sent to a server and
- every decision about what came back. No transport, and no message format —
- an RFC 822 message is `Message.js`'s subject.
-- The transport is `scripts/mail-transport.sh`, which is curl. Fields cross to
- it base64-encoded on one line of stdin, so a password never reaches the
- process table and nothing needs escaping on the way; the config carrying it
- goes to curl's own stdin rather than to a file that would be on disk.
-- The JMAP transport is `scripts/jmap-transport.sh` beside it — the same curl and the same base64 stdin line, with five verbs and a four-line reply — except `stream`, which holds the event connection open. `scripts/jmap-stream.py` owns curl and bounds each event before forwarding it to the desktop, normalizing CR, LF and CRLF to LF. A QML size check after `SplitParser` is too late: the parser has already buffered the event. Stopping or refusing the stream must also terminate curl.
-- JMAP discovery starts at the address domain’s HTTPS well-known URL, or at the server URL the user supplied. An unauthenticated DNS SRV answer must never authorize a credential destination; an HTTPS probe of the target only authenticates that target, not its relationship to the mailbox domain.
-- **The response comes back base64 too, and that is load-bearing.** IMAP
- measures a literal in octets. Read as UTF-8 text, 2048 octets of a message
- with an accent in it is fewer than 2048 characters, and the parser walks off
- the end of one response into the middle of the next — which is also how a
- message body could forge a response of its own. Base64 keeps one character
- per octet, so counting characters is counting octets.
-- **UID order is not date order.** Proton Bridge can assign imported messages UIDs newest-first. Native listing takes a compact `UID FETCH 1:* (UID)` snapshot, fetches INTERNALDATE in explicit UID batches of at most 4096 messages, searches stable UID windows, and sorts matching UIDs by arrival date before paging. Descending UID is only a deterministic date tie-breaker. Never return a high-UID window as a settled newest prefix, even when it fills a page, and never replace UID windows with sequence-number windows that move when another client expunges mail. Unsolicited UID/FLAGS updates must not erase a previously fetched date.
-- `BODY.PEEK`, never `BODY`. Reading a list must not mark the mailbox seen, and
- that is the most common way a hand-rolled IMAP client ruins a mailbox.
-- `UID EXPUNGE`, never bare `EXPUNGE`: the latter removes every `\Deleted`
- message in the folder, including ones another client marked — somebody else's
- mail disappearing because this one archived.
-- A message id is `:`. A UID is unique only within its folder, so a
- bare one collides between folders in the list and in the body cache on disk.
-- Folder names are never guessed. `LIST` reports them and SPECIAL-USE names
- them: "Sent" is "Sent Items" on Exchange and "[Gmail]/Sent Mail" on Gmail, and
- a client that guessed would create folders rather than find them.
-
-## Review: security is a release-blocking requirement
-
-- Every review includes a separate security verdict: **PASS**, **BLOCK**, or **NOT VERIFIED**. Functional correctness, appearance and passing general tests cannot compensate for a security failure. A change that introduces or leaves its affected security boundary unverified must not be approved or released; name the missing evidence rather than assuming safety.
-- Trace untrusted data from its author to its final consumer: mail headers and bodies, MIME names, server responses, URLs, credentials and persisted settings. Record each decoding, normalization, interpolation and process boundary. Validate the exact bytes consumed, not just a normalized interpretation. Base64 transports bytes; it does not make them safe for shell, curl config, IMAP, HTTP headers or HTML.
-- Every value interpolated into curl config must pass `scripts/curl-config.sh` before any curl process starts. Validate the entire batch, including later commands and recipients. Reject control characters and noncanonical text, including NUL and trailing LF that shell command substitution would otherwise discard. Keep legitimate multiline mail/event bodies out of config values. Quoting a string and escaping backslashes are insufficient; refusing inside the left side of `build_config | curl` is too late.
-- Invoke curl with `-q` as its first argument and `--globoff` so a user's default config and URL expansion cannot silently change the reviewed request. Review redirects, protocol restrictions, TLS verification, credential scope, deadlines and response-size bounds independently. An error or a failure status does not prove no earlier or later request happened.
-- Public-host spelling is not proof of a public destination. For sender-controlled network requests, review raw and decoded URL semantics, DNS answers, the actual connected address, proxies and redirects. `Html.isPublicHost` checks names only; `scripts/public_http.py` rejects non-public DNS answers and binds the connection to a checked numeric address while retaining TLS verification against the original hostname. A preflight lookup followed by independent resolution is not sufficient. No environment switch or production fallback may bypass this policy. Configured mail/CalDAV servers can legitimately be private and have a different trust boundary.
-- Credentials must stay out of argv, logs, world-readable settings and attacker-selected origins. Resource-bearing HTML and attachment paths are security boundaries regardless of which appearance or convenience option enabled them. Never trade these guarantees for compatibility or silently fall back to a less constrained path.
-- Security fixes require regression tests that fail on the vulnerable behavior and verify the forbidden effect did not happen: no process/network request, no credential disclosure, no file write. Cover alternate providers and sibling call sites, CR/LF/CRLF, trailing controls, NUL, malformed encoding and valid inputs with quotes, backslashes, Unicode and legitimate multiline bodies. Use controlled local targets and synthetic credentials; never real mailboxes or secrets.
-- Separate confirmed exploit behavior, a demonstrated boundary violation, and an unverified delivery hypothesis. Report tested runtime versions and environmental gaps. A fabricated Gmail resource is not evidence that Gmail delivers the same bytes; a curl stub is not evidence of curl's parsing or network behavior. Track pre-existing limitations explicitly and do not describe a scoped fix as a complete security audit.
-
-## Secrets
-
-- Refresh tokens go to GNOME Keyring over stdin, never through a command line.
-- Outlook access tokens reach curl over stdin and its `oauth2-bearer` config option; the account password never enters Omamail.
-- The OAuth client goes to a 0600 file, never to plugin settings: `shell.json`
- is world-readable.
-- Anything that could carry a credential passes through `OAuth.redact` before
- it can reach a label.
-- **CalDAV credentials go only to the configured source's own origin.** A
- server-written event `href` is resolved against the collection and refused
- when its scheme, host or port differs — `Calendar.caldavEventUrl` is the
- one place that decides, and the controller judges it before the keyring is
- touched.
-- **Every request that crosses the network is given up on eventually, and in
- QML that costs a `Timer`.** Qt's QML `XMLHttpRequest` has no `timeout` and no
- `ontimeout`: the properties do not exist, and assigning one reads back
- exactly what was written — so the obvious fix looks like it works and does
- nothing at all. A `Timer` calling `abort()` is the whole of what is
- available, and `abort()` drives `readyState` to `DONE` with status 0, which
- is why the deadline needs no callback of its own: it lands in the failure
- path the request already had, decrementing `inFlight` once. Both facts were
- measured against a socket that accepts and never answers, not read from a
- specification. `tests/test_source.sh` fails an assignment to `.timeout`,
- because that is the mistake that looks correct; "this request has a deadline"
- is not something grep can ask, so it is stated here and proved by the
- offscreen harness rather than by a test that would pass whatever happened.
-- **A gate that judges only the first address is not a gate.** `isPostableUrl`
- and `imageSourceKind` refuse loopback, private, link-local and single-label
- hosts — but they judge the address *the sender wrote*, and Qt's
- `XMLHttpRequest` follows a 3xx by itself and re-sends the request, body
- intact, wherever that answer points. Measured, not assumed: a loopback target
- answering `302 Location: /landed` recorded the POST arriving there. So the
- one-click unsubscribe goes out through `scripts/unsubscribe.py`, whose HTTP client never follows redirects. A 3xx is reported as a list that did not unsubscribe rather than as an address to chase. No sender-controlled value is interpolated into a shell or curl config.
-- **Qt never fetches a remote message image itself.** Its loader takes no policy
- from QML, follows redirects, and draws a broken placeholder while a resource
- is pending. Once the reader has allowed images, `scripts/image_fetch.py`
- fetches each approved public HTTP(S) source through `public_http.py`, with checked DNS answers, pinned connections, no redirects, a size ceiling and a whole-process request deadline covering DNS too. The declared image type must match a supported raster signature; an SVG labelled PNG is refused. Only a successful supported image comes back as a
- `data:` URI; until then the source is absent from both rich documents. Do not
- hand the original remote URL back to Qt or replace this with a QML request,
- because that reopens both redirect SSRF and the loading-placeholder defect.
-- Remote images in a message body are blocked until the reader asks for them.
- Fetching one still tells its host that this address opened this message at
- this moment, so tracking pixels and hidden images never enter the fetch list.
-- The answer is a standing one, off until it is given. Asking per message meant
- answering the same question on every newsletter and remembering none of it,
- so the cost of asking fell on somebody who had already decided. The notice's
- button says "Always show", because that is what it does, and Settings is the
- one place that turns it back off.
-
-## Html.js
-
-- Qt is the renderer; this is the gate in front of it. `TextEdit` with
- `textFormat: RichText` is a real HTML engine and it is what draws every
- message — what Qt gives a QML plugin no say over is what that engine does
- while it works, and it fetches ` `, lays a ` |