# Architecture

> Data flow, synchronization and the on-disk storage layout.

---

LLMS index: [llms.txt](/llms.txt)

---

Pigeon is one process and one binary. The web UI assets, REST API, MCP server
and CLI all read the same local SQLite store. Every interface — the built-in
web UI today and a desktop GUI later — is a **pure REST API client**, exactly
like scripts and AI agents; the server has no UI-only endpoints or side
channels.

## Request paths

```
browser / curl ──► api.REST ──┐
MCP client  ──► /mcp ──► mcpsrv ──┤──► store (SQLite)
stdio MCP   ──► mcpsrv ───────────┤
pigeon digest ────────────────────┘

mailer ──► IMAP servers (sync, bodies, flags)
       └─► SMTP server   (send)
detect ──► ISPDB / DNS MX
```

`pigeon serve` builds the API handler, mounts the embedded assets at `/` and
runs the HTTP server. `pigeon mcp` runs the same tool set over stdio without an
HTTP listener. Both open the same data directory; SQLite serializes writes so
running several processes against one directory is safe but not optimized for
high concurrency.

## Synchronization flow

1. Connect to IMAP using the account's host, port and security mode, then log
   in.
2. `LIST` all mailboxes; skip `\Noselect` and non-existent entries; upsert
   each mailbox and read fresh counts with `STATUS`.
3. Remember the server's `\Sent` mailbox so sent copies are archived in the
   right place.
4. Select the target mailbox read-only.
5. Compare `UIDVALIDITY` with the stored value. If it changed, discard cached
   messages for that mailbox — old UIDs are meaningless.
6. Fetch messages:
   - **First sync**: search for messages received in the last 7 days (IMAP
     `SEARCH SINCE`); bodies are included when the batch is at most 200.
   - **Incremental**: search for UIDs above the stored maximum; at most 200
     per run, newest-first if there is a backlog. Bodies are included when the
     batch is at most 200.
7. Parse envelopes and MIME, store messages, then update counts and
   `lastSyncAt`.

Older mail beyond the cached window is backfilled on demand: “Load more” calls
`POST /api/mailboxes/{id}/fetch-older`, which walks backwards day by day from
the oldest cached message (envelopes only) and, when a silent week turns up
nothing, probes everything earlier before declaring the mailbox exhausted. See
[Mailboxes & Sync](../mailboxes/) for the details.

Body parsing extracts `text/plain`, `text/html`, a snippet and attachment
parts; attachment bytes are stored in the local `attachments` table (each file
up to 25 MB, larger ones skipped) so downloads never hit IMAP again. When a
mail has only HTML, a plain-text version is derived so search and readers have
text. Fetching always uses `BODY.PEEK`; opening an uncached body later performs
a single-message read-only fetch, and a message cached before attachment
storage existed gets its attachments backfilled the first time it is opened.

## Storage layout

The data directory contains:

| File | Purpose |
| --- | --- |
| `pigeon.db` (+ `-wal`, `-shm`) | SQLite database in WAL mode |
| `secret.key` | AES-256-GCM key for account passwords, mode `0600` |
| `logs/pigeon-YYYY-MM-DD.log` | Daily log files, one per local date; logs are also mirrored to stderr |

| Table | Contents |
| --- | --- |
| `accounts` | Account settings; `password_enc` holds the encrypted password |
| `mailboxes` | Mailbox metadata, UID state and counts; cascades from accounts |
| `messages` | Cached message metadata and bodies; cascades from mailboxes |
| `attachments` | Attachment bytes and metadata; cascades from messages |
| `tokens` | Token ID, name, SHA-256 hash and timestamps |
| `settings` | Client preferences shared by all clients: language, refresh interval, the remote-image auto-load toggle and sender grouping |

Deleting an account cascades to its mailboxes and messages, but never touches
the IMAP server.

## Design decisions

- **Cache, don't mirror.** Pigeon keeps a recent window for offline reading and
  search and leaves the server as the source of truth. Anything not cached is
  fetched on demand.
- **Lazy bodies.** Metadata sync is cheap; bodies are fetched during sync only
  within the batches above, and on first open otherwise.
- **Local-first auth.** Loopback clients skip tokens; remote clients never see
  mail without one. No third-party service sits in the path.
- **One tool set, two transports.** The MCP tools are transport-agnostic; stdio
  and HTTP share the same handlers and storage.
- **UI as an API client.** The web UI and any GUI manage accounts and mail
  through the same REST endpoints documented here. Nothing in the UI gets
  privileged access, so the API stays the single contract to test and secure.
- **Stateless MCP HTTP.** The HTTP endpoint answers each request independently
  with JSON, which keeps deployments simple behind any load balancer.

## Limits

| Limit | Value |
| --- | --- |
| Initial sync window per mailbox | last 7 days |
| Messages per incremental sync | 200 |
| Messages per backfill call | 200 |
| Message list page size | default 50, max 200 |
| Search results | default 20, max 100 |
| Text body stored | 256 KiB |
| HTML body stored | 1 MiB |
| Snippet length | 180 characters |

---

Backlinks:

- [Documentation](/docs/)
