pikuri-thunderbird 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,827 @@
1
+ # pikuri-thunderbird — design & threat model
2
+
3
+ Audience: someone extending this gem or auditing its security posture.
4
+ Rationale for individual classes lives in their YARD headers; this file
5
+ covers the cross-cutting design and the threat model.
6
+
7
+ ## What it does
8
+
9
+ Gives a pikuri agent read-only access to the user's **local** Thunderbird
10
+ data — stored mail and cached calendars — by reading Thunderbird's own
11
+ on-disk profile. It never speaks IMAP/POP3/SMTP or CalDAV itself; it reads
12
+ files Thunderbird already wrote.
13
+
14
+ - **Mail** rides Thunderbird's Gloda index (`global-messages-db.sqlite`),
15
+ which has already MIME-decoded, HTML-stripped, and split every message
16
+ into body / subject / attachment-names / author / recipients. pikuri
17
+ treats it as a pre-decoded corpus. Gloda never had attachment *bytes*, so
18
+ reading one goes to Thunderbird's offline mbox store (§ "Mail: mbox on
19
+ disk").
20
+ - **Calendar** reads the `calendar-data/*.sqlite` stores, whose events are
21
+ normalized columns (no ICS parser for the common case).
22
+
23
+ ## Threat model: the lethal trifecta
24
+
25
+ Email is the textbook lethal trifecta. The three legs:
26
+
27
+ 1. **Private data** — the mailbox and calendars. Inherently present.
28
+ 2. **Untrusted content** — every message body, subject, attachment name and
29
+ attachment is authored by whoever sent the mail, i.e. potentially an
30
+ attacker. Inherently present.
31
+ 3. **Egress** — the ability to send data out.
32
+
33
+ **The default surface removes leg 3 entirely.** The tools
34
+ `thunderbird_mail_search`, `thunderbird_mail_read`,
35
+ `thunderbird_mail_attachment_read`, `thunderbird_contact_search`,
36
+ `thunderbird_calendar_search`, and `thunderbird_calendar_read` are all
37
+ inbound-only, and they are all `Extension`
38
+ gives unless a host opts into an outbound leg. An agent wired with just these (plus, say, a calculator) has legs 1
39
+ and 2 but no way to send anything anywhere, so a prompt injection buried in a
40
+ message body has no exfiltration channel. That is the "trifecta broken by
41
+ construction" posture `pikuri-briefing --with-mail` demos.
42
+
43
+ A host can also take *fewer* than six: `Extension.new(surfaces: %i[mail])`
44
+ wires the mailbox and neither the address book nor the calendar. That changes
45
+ nothing about legs 1 and 2 — mail search alone carries both, and presence is a
46
+ union — so the trifecta map prints the same advisory and the same leg count
47
+ either way. What it buys is severity: each surface is one more thing an
48
+ injected message can make the agent query over the private pool, and three
49
+ fewer query surfaces is three fewer. Since the detector cannot show that
50
+ (`design/decisions.md` `D_thunderbird_surfaces`), a host that narrows owes its user a
51
+ sentence naming what the remaining pool actually is — "your whole mailbox", not
52
+ "your correspondence with this customer".
53
+
54
+ **Attachments raise severity, not the leg count.** `thunderbird_mail_attachment_read`
55
+ pours an attachment's text into the context: the same leg 2 as a body, so
56
+ it carries the same legs as `thunderbird_mail_read`. It is worse in degree —
57
+ a PDF carries far more injection text than a body, and no human ever reads
58
+ it — and every attachment is a stranger's *file* fed to a parser, which a
59
+ workspace file mostly is not. The PDF arm the host picks is therefore a
60
+ posture choice: pikuri-pdf is pure Ruby, so memory-safe, and its realistic
61
+ risk is a parser DoS (no per-call timeout: Ruby's `Timeout` is unsafe around
62
+ native code, pages are parsed lazily, and `MessageStore`'s 40 MB message cap
63
+ bounds the input; revisit if a hostile PDF ever hangs a turn); pikuri-extractors runs native converters but in
64
+ a networkless one-shot container, the stronger choice for a mail host.
65
+ An HTML attachment renders through pikuri-html, which keeps text the markup
66
+ hides but labels it `[hidden in the original: …]`. It can't spot white-on-white,
67
+ so the label is evidence for whoever reads the transcript, not a defense.
68
+ An image goes to the model as the picture itself: pikuri only sniffs its
69
+ magic bytes and never decodes it — the model server does — but a vision
70
+ model reads text *drawn* into it, which no human reviews either.
71
+ Reading an attachment is *inbound*, so it does not touch the outbound "no
72
+ attachment ever ships" invariant below.
73
+
74
+ The bundled `bin/pikuri-thunderbird` deliberately goes one step further — it
75
+ wires both outbound `allow_` flags to demo the *whole* surface — so it does
76
+ carry leg 3. But that leg is human-gated: compose can only open a Thunderbird
77
+ compose window the user Sends themselves (below), so there is an egress leg yet
78
+ no *autonomous* egress. A poisoned message can influence a draft, but cannot make it leave the
79
+ machine without the user clicking Send on a window they can see. So the demo's
80
+ trifecta is *intact-but-gated*, not severed — an honest smoke-alarm, not a
81
+ firewall.
82
+
83
+ Defense in depth on leg 2: **Spam/Junk/Trash are not searched.** On the
84
+ Gloda path this is *free* — Gloda already assigns those folders indexing
85
+ priority `-1` (never indexed), so the search backend structurally cannot
86
+ return them. This attenuates but does **not** sever leg 2: a *targeted*
87
+ injection lands in the Inbox (a reply, a newsletter, a calendar invite), not
88
+ in Spam. Record it as a mitigation, never a boundary. Honest wrinkle
89
+ (confirmed on a live box): Gmail's account-level Trash folders are `-1`, but
90
+ the `[Gmail]/Trash` *label* folder is indexed at priority 20, so a handful of
91
+ trashed Gmail messages can surface — the free skip is nearly, not perfectly,
92
+ complete.
93
+
94
+ ## The snapshot mechanism
95
+
96
+ Thunderbird holds its SQLite DBs open with `locking_mode=EXCLUSIVE`, so a
97
+ plain read fails "database is locked" while it runs, and a lock-bypassing
98
+ `immutable=1` read of the live file risks a torn read. pikuri never queries
99
+ the live file. Instead {Pikuri::Thunderbird::DatabaseSnapshot} takes a **bracketed
100
+ `cp --reflink=auto`** of the main file, then its `-wal` if there is one. It
101
+ reads the *generation* (the SQLite change counter at header bytes 24–27, plus
102
+ the `-wal`'s salt and size) and checks for a rollback `-journal` before and
103
+ after the copy, and accepts the copy only if the generation didn't move and
104
+ no journal was present at either edge (otherwise it discards and retries, 4
105
+ tries 250 ms apart). Copies alternate between two slots, so a failed try never
106
+ touches the copy in use: when the tries run out, that older copy keeps serving,
107
+ one poll stale. Only with no older copy yet does the tool answer an error
108
+ telling the model Thunderbird is busy. Retrying forever is not an option: a
109
+ crash mid-write leaves a hot `-journal` that stays until Thunderbird next starts.
110
+ The copy is opened normally, so SQLite applies the copied WAL. Reflink makes
111
+ the copy a near-free metadata-only extent share on a copy-on-write
112
+ filesystem.
113
+
114
+ The validated generation doubles as a freshness stamp: each query compares
115
+ the live one against it and re-copies (and, for mail, rebuilds the FTS5
116
+ index) only when it moved. One signal drives both consistency and freshness.
117
+ The WAL parts are why it is not the counter alone: a WAL store bumps the
118
+ counter only on a checkpoint.
119
+
120
+ **Mail search index.** Gloda's own full-text index (`messagesText`) is an
121
+ fts3 virtual table behind Mozilla's custom `mozporter` tokenizer, which the
122
+ `sqlite3` gem cannot open. So pikuri builds its *own* ephemeral FTS5 index
123
+ over the decoded columns (`messagesText_content`) inside the snapshot copy —
124
+ external-content, so it stores only the index, not a second copy of the
125
+ text. Rebuilt (~1 s) only when the Gloda generation moves.
126
+
127
+ ### Privacy caveat
128
+
129
+ The snapshot is the decoded mailbox/calendar landing **outside** the
130
+ Thunderbird profile, in a `0700` dir under `~/.cache/pikuri/thunderbird/`.
131
+ This is a second at-rest copy — but at the *same trust level* as the source:
132
+ the Gloda and calendar DBs are already unencrypted plaintext on disk in the
133
+ profile, and the copy is user-owned with the same permissions. It is not a
134
+ new exposure class. The copy is `Pikuri::Finalizers`-reaped on a clean exit;
135
+ a crash can strand it until it's next overwritten or the dir is cleared
136
+ (re-derivable data, low harm).
137
+
138
+ The credential stores that share the profile directory (`logins.*`,
139
+ `key4.db`, `cert9.db`, `openpgp.sqlite`, …) are **never** opened — the
140
+ backends touch only the allowlist in § "Files never touched".
141
+
142
+ The attachment reader adds **no** at-rest copy: it decodes in memory, from
143
+ the mbox Thunderbird already keeps in plaintext.
144
+
145
+ ## Outbound is a human-gated hand-off, never an autonomous send
146
+
147
+ Composing a mail or creating a calendar event is egress (a send, an invite,
148
+ a CalDAV sync). The design invariant, locked in before any of it ships:
149
+
150
+ > **pikuri-thunderbird performs no network egress and no autonomous send.**
151
+ > Every outbound action is a hand-off to Thunderbird's own UI — a pre-filled
152
+ > compose window (via a `mailto:` URI) or an `.ics` import wizard — where the
153
+ > *human* reviews and commits. pikuri writes nothing to Thunderbird's stores
154
+ > and sends nothing itself. No send tool ever ships.
155
+ >
156
+ > **And no attachment ever ships.** The outbound surface carries only fields
157
+ > that *render literally*: a plain-text body, a subject, addresses. No
158
+ > attachment of any kind (`.png`, `.zip`, `.txt` — the extension is
159
+ > irrelevant), no HTML body, no iCalendar `ATTACH` property.
160
+
161
+ This converts egress from *agent-automatic* to *human-action-required*. Note
162
+ what that does and does not buy — the leg is **downgraded, not removed**, and
163
+ the threat-model section above is the authority: once an `allow_` flag is on,
164
+ leg 3 is present. Only the default surface (both flags off) severs it.
165
+
166
+ What the downgrade rests on is narrow and worth naming, because it's the one
167
+ property a rubber-stamping human can't destroy: **the human sees the exact
168
+ bytes that leave.** The compose window shows the literal recipient, subject
169
+ and body that will be sent; the `.ics` wizard shows the event that will be
170
+ imported. Contrast a shell agent that asks "run `curl …`?" — there the human
171
+ approves a *program*, and what it actually uploads was never on screen. So a
172
+ poisoned message can influence a draft, but every byte of that draft was
173
+ displayed to someone before it moved.
174
+
175
+ That is a real reduction and not a boundary: it kills *silent* exfil — every
176
+ byte was on a screen — and leaves the covert channel, a secret spelled into
177
+ prose the reader skims past, sent as a reply to the injector (see "What the
178
+ body guards do *not* close" below).
179
+
180
+ **Resist the temptation to call the survivors low-bandwidth.** They aren't.
181
+ A first-letter acrostic carries roughly one letter per word, and a secret is
182
+ already text — so an agent *transcribes* it rather than computing anything.
183
+ Price the channel that way, since this gem wires no shell and no calculator:
184
+ a pasted `id_ed25519` is its ~400 base64 characters, so ~400 words; a whole
185
+ RSA PEM ~1600. A thread, not a wall — and the mailbox is exactly where
186
+ someone pasted the key "just to have it" five years ago. (An agent that
187
+ *does* hold local compute prices it lower still, by the secret's entropy —
188
+ ~55 words for that ed25519 key; a network-severed sandbox cuts egress, never
189
+ arithmetic. See `book/os-assistant.md` §"Why 'too big to hide' is not a
190
+ defense".) The bytes-visible property is worth stating because it is
191
+ structural; "the payload is too big to hide" is not, and shouldn't be
192
+ offered as reassurance.
193
+
194
+ ### Why no attachments — it's the same invariant as plain-text-only
195
+
196
+ An attachment is the cleanest way to defeat the whole gate. A key encoded in
197
+ the low bits of a `.png` is invisible to any reader: the human approves a
198
+ *filename* and a thumbnail, never the bytes. That is exactly the shape of a
199
+ shell agent asking "run `curl …`?" — an approved *reference* to content
200
+ nobody saw — and it would demote this hand-off from "human sees the payload"
201
+ to the same class as an autonomous send, no matter how careful the human is.
202
+
203
+ So "plain text only" and "no attachments" are not two policies but one:
204
+ **the outbound surface may contain only fields whose rendering is their
205
+ content.** HTML fails it (`<span style="display:none">`), attachments fail it,
206
+ and so would any richer field added later. Today this is enforced by
207
+ construction rather than by filtering — {Pikuri::Thunderbird::MailtoUri}
208
+ *builds* an allowlist of five parameters (`to`/`cc`/`bcc`/`subject`/`body`),
209
+ so there is no `attach=` to strip, and {Pikuri::Thunderbird::IcsEvent} emits
210
+ no `ATTACH` property. Enforced-by-absence is fragile against a future
211
+ "improvement" — `mailto:?attach=` was a real Thunderbird feature — which is
212
+ why the invariant is written down rather than left implied by the code.
213
+
214
+ **Compose is shipped, opt-in.** `thunderbird_mail_compose`
215
+ ({Pikuri::Thunderbird::MailCompose}) is wired only when a host passes
216
+ `Extension.new(allow_compose_mail: true)` — off by default, so an unopted wiring has no
217
+ egress leg *by construction*. `bin/pikuri-thunderbird` opts in (to demo the
218
+ full surface). Turning compose on re-introduces leg 3, but only as a
219
+ human-committed hand-off: the tool opens a
220
+ `mailto:` compose window ({Pikuri::Thunderbird::MailtoUri} percent-encodes every
221
+ field so a body can't smuggle `&bcc=`), the body is plain-text-only (no hidden
222
+ content, no remote beacons), and a mechanical recipient guard
223
+ ({Pikuri::Thunderbird::ComposeGuard}) runs first: a suspicious *body* fails
224
+ closed; suspicious/non-ASCII/punycode *recipients* are dropped for the human to
225
+ retype; a recipient domain the user has never sent mail to (per
226
+ {Pikuri::Thunderbird::Gloda::Contacts#domains_sent_to}) is flagged, not blocked; and a body
227
+ carrying a long base64 *blob* earns a located soft-warn (see
228
+ {Pikuri::Thunderbird::ComposeGuard#body_blob_note}). The launch
229
+ is detached (`setsid --fork`) so closing the agent never kills the user's
230
+ Thunderbird.
231
+
232
+ **What the body guards do *not* close.** They raise attention on the lazy exfil
233
+ — a control-byte/homoglyph body fails closed, a base64/hex/base32 dump earns a
234
+ note — but
235
+ they are not a barrier against an *adaptive* injector, who splits the blob with
236
+ whitespace or spells it in prose for free (the same injection payload carries
237
+ the evasion). A reply to the injector is flagged, since only domains the user has
238
+ *sent* to count as known and an attacker can't earn that by writing first. It
239
+ stays silent where the attacker writes from a domain the user has mailed before:
240
+ a compromised contact's account, or a shared provider's domain (`gmail.com`),
241
+ because the check is per-*domain*.
242
+
243
+ **What each guard really buys is a rung, not a wall.** Every check here
244
+ narrows the *form* the payload may take, never the payload itself, so an
245
+ adaptive injector simply steps down: fail the body on control bytes,
246
+ zero-width joiners and homoglyphs, and it drops to plain ASCII; note a
247
+ base64 dump and it moves to hex, then base32, then splits the run below the
248
+ threshold; catch those and what remains is **linguistic steganography** — the
249
+ secret spelled out by the first letters of an innocuous sentence ("I think
250
+ dogs are super cute"), by word choice, by sentence count. That bottom rung
251
+ reads as ordinary prose to the guards *and* to the human, which is where an
252
+ injector who has read this file starts. It is slower, and slow is not a
253
+ barrier: `book/os-assistant.md` §"Why 'too big to hide' is not a defense"
254
+ prices what fits. The human-gated, irreversible-send compose window — not the
255
+ guard — is the backstop all of this leans on.
256
+
257
+ **Create-event is shipped, opt-in.** `thunderbird_calendar_create`
258
+ ({Pikuri::Thunderbird::CalendarCreate}) is wired only when a host passes
259
+ `Extension.new(allow_create_calendar_event: true)`. Same human-gated shape:
260
+ it builds an event `.ics` ({Pikuri::Thunderbird::IcsEvent} RFC-5545-escapes
261
+ every field so a description can't inject a second `VEVENT`), stages it where a
262
+ snap-confined Thunderbird can read it ({Pikuri::Thunderbird::Profile#outbox_dir}),
263
+ and hands it to TB's import wizard, where the human picks the destination
264
+ calendar (local-vs-CalDAV = their no-egress-vs-egress choice) and confirms.
265
+ Both outbound tools launch via the shared {Pikuri::Thunderbird::Launcher}; each
266
+ one's rationale is in its class yardoc.
267
+
268
+ ## Discovery
269
+
270
+ {Pikuri::Thunderbird::Profile} never guesses: it resolves one profile
271
+ unambiguously (parsing `profiles.ini`), raises with a fix if two install
272
+ roots both hold a profile with a mail account (a stale apt profile left after
273
+ an apt→snap migration), or returns `nil` (tools simply not registered) when Thunderbird
274
+ isn't installed. An explicit `profile_dir:` override bypasses discovery.
275
+ Linux snap and apt roots are supported; flatpak is out of scope.
276
+
277
+ ## Storage landscape (empirically confirmed)
278
+
279
+ The reference data the design rests on, probed against a live snap install
280
+ (Thunderbird 152.0, Linux, 2026-07). It's here — not in the class yardocs —
281
+ because it spans the whole gem and is expensive to re-derive (it needs a real,
282
+ populated Thunderbird). The per-symbol *why* lives in the class yardocs; this
283
+ is the shared evidence base, and the ground truth the next tool's builder will need.
284
+
285
+ Caveat: all of this is one real install (snap; Gmail + iCloud IMAP; CalDAV
286
+ calendars); the attachment facts were re-probed on it at Thunderbird 157
287
+ (2026-10), against the Gmail account. The specs run against synthetic fixtures
288
+ built to this schema; the testbed (§ below) adds a profile a real Thunderbird
289
+ 159 built, with an IMAP account synced from a local dovecot — generic IMAP,
290
+ not Gmail's labels-as-folders, and with every body offline, so on-demand IMAP
291
+ attachments are still checked only on that one install.
292
+
293
+ ### Profile & install roots
294
+
295
+ - `profiles.ini` is a small INI; the active profile is the `Default=1`
296
+ section (`Path`, relative when `IsRelative=1`). The confirmed real file has
297
+ **no `[Install…]` sections** (Firefox's per-install mechanism), so the plain
298
+ `Default=1` scan suffices.
299
+ - Roots: **snap** `~/snap/thunderbird/common/.thunderbird/` (confirmed),
300
+ **apt** `~/.thunderbird/` (recalled). Flatpak
301
+ (`~/.var/app/org.mozilla.Thunderbird/…`) is out of scope.
302
+ - `.parentlock` at the profile root is Thunderbird's running-instance lock — a
303
+ cheap "is TB open?" probe. The `lock` symlink beside it (`lock ->
304
+ <ip>:+<pid>`) **outlives a clean exit**, so its presence proves nothing.
305
+ - `thunderbird -profile <dir>` runs on any directory and neither creates nor
306
+ touches `profiles.ini`.
307
+ - **The snap launcher links its root to an existing `~/.thunderbird`.** Started
308
+ while `~/.thunderbird` existed and the snap root didn't, snap 159 created
309
+ `~/snap/thunderbird/common/.thunderbird -> ~/.thunderbird`. For a user
310
+ migrated from the deb, both roots are then one directory, so discovery
311
+ compares roots by realpath.
312
+
313
+ ### Mail: the Gloda index (`global-messages-db.sqlite`) — the mail source
314
+
315
+ A complete, pre-decoded search index, kept current only while Thunderbird's
316
+ *Enable Global Search and Indexer* setting is on. Switching it off writes
317
+ `user_pref("mailnews.database.global.indexer.enabled", false);` to `prefs.js`
318
+ and stops the indexer, and **the file stays, frozen**: Gloda deletes it only
319
+ when it's corrupt or its schema changes (testbed, Thunderbird 160, 2026-11-21).
320
+ So the mail tools are wired only when the file exists *and* that pref isn't
321
+ false ({Pikuri::Thunderbird::Profile#gloda_indexing?}). Tables that matter:
322
+
323
+ - **`messagesText`** — an FTS3 virtual table over `body`, `subject`,
324
+ `attachmentNames`, `author`, `recipients` (already MIME-decoded,
325
+ HTML-stripped, attachment *names* extracted). Its backing store is the plain
326
+ table **`messagesText_content(docid, c0body, c1subject, c2attachmentNames,
327
+ c3author, c4recipients)`**.
328
+ - **`messages`** — `id` (= FTS `docid`), `folderID`, `messageKey`,
329
+ `conversationID`, `date` (**PRTime = µs since epoch**, ÷1e6 for Unix
330
+ seconds, second granularity), `headerMessageID` (the RFC822 `Message-ID`),
331
+ **`deleted`**, `jsonAttributes`, `notability`.
332
+ - **`folderLocations`** — `id`, `folderURI`, `dirtyStatus`, `name`,
333
+ **`indexingPriority`**: `-1` = never indexed (Gloda's sentinel), else `20`
334
+ (normal) / `50` (INBOX) / `60` (Sent). Resolves a hit's `folderID` → folder.
335
+ - **`contacts` / `identities` / `contactAttributes`** — the email↔name
336
+ correspondence graph. `contacts` is **dead for resolution** — `frecency` /
337
+ `popularity` are 0 for every row and `name` is unreliable (often a bare
338
+ address or junk), so {Pikuri::Thunderbird::Gloda::Contacts#resolve} reads the
339
+ *decoded* `c3author` / `c4recipients` columns instead (name + address
340
+ together, with a natural per-message frequency). `identities(kind, value)` is
341
+ unused too: it holds **every author**, so a domain that only ever wrote *to*
342
+ the user would count as known the moment its mail is indexed, and an attacker
343
+ earns that by writing first. {Gloda::Contacts#domains_sent_to}, the
344
+ recipient-novelty check, reads `c4recipients` of Sent-folder messages instead
345
+ (on the testbed the look-alike `northwlnd-bank.example` and the attacker's
346
+ `kettle-co-payments.example` now warn, `lumo-studio.example` doesn't).
347
+ - **A literal `undefined` in the author/recipient text.** Gloda writes
348
+ `Mira Koskinen <mira@lumo-studio.example> undefined` into
349
+ `c3author` / `c4recipients` for every address but the owner's own as
350
+ author (the owner as a recipient gets it too), probably an address-book
351
+ field for a contact that isn't in the address book. Both views strip it
352
+ through {Pikuri::Thunderbird::Gloda.strip_undefined}.
353
+ - **Gloda keeps at most ~20 KB of each body part.** It indexes with
354
+ `saneBodySize` (`MAX_SANE_BODY_PART_SIZE = 20 * 1024`,
355
+ `MimeMessageEmitter.sys.mjs`), so a longer body is cut mid-sentence
356
+ (testbed's `house-rules`: 20632 bytes kept), and an HTML part is cut
357
+ before its markup is stripped. `thunderbird_mail_read` ends a body that
358
+ reached the cap with a note to open it in Thunderbird; it doesn't fetch the
359
+ rest from the mbox, since a mail that long is rare and the fallback would
360
+ cost a store scan per read.
361
+ - **The FTS subject drops `Re:`** — a reply's `c1subject` is the bare subject,
362
+ so a search by subject can't tell a thread's replies from its opener.
363
+ - A `messages` row with a null `folderID` is a **ghost**: Gloda's placeholder
364
+ for a message a thread references but the store doesn't hold. Counting real
365
+ messages means `WHERE folderID IS NOT NULL`.
366
+ - **`attributeDefinitions` / `messageAttributes`** — extensible per-message
367
+ attributes; ids seen: 57 `tag`, 58 `star`, 59 `read`, 60 `repliedTo`,
368
+ 61 `forwarded`. (Relevant to churn — see the change counter below.) Ids are
369
+ assigned per profile, so code looks one up by `name`.
370
+ - **`attachmentInfos`** (id 51 there) — the attachment list, stored in
371
+ `messages.jsonAttributes` under the attribute's id as **positional arrays**
372
+ `[name, contentType, size, part, externalUrl, isExternal]`. Verified over
373
+ all 1286 attachments of the IMAP account: every `part` resolved to the right
374
+ leaf of the stored message (root `1`, children `1.1`, `1.2`, …); `contentType`
375
+ beats the part's own header (7 parts said `application/octet-stream` where
376
+ Gloda, going by the file name, said `text/csv` etc.); `size` is the decoded
377
+ size for every binary part, but `-1` when unknown, a few percent off for
378
+ text, and noise for a `message/rfc822`: `0` for every one on the Gmail
379
+ account, an unrelated non-zero number on the testbed's dovecot account (526
380
+ to 6941, Thunderbird 159). `isExternal` marks a part
381
+ whose bytes are at a remote URL — never set on IMAP, and **not** the flag
382
+ for a detached attachment (that is a `text/x-moz-deleted` part). The FTS
383
+ column `c2attachmentNames` **omits forwarded mails**, which is why the
384
+ listing numbers this list instead — yet it *carries* the names of the
385
+ attachments inside a forward, at any depth, which this list omits
386
+ (testbed, 159: a forward of a forward still indexes the CV two levels
387
+ down), so a search can find a mail by an attachment name its listing
388
+ never shows. The forward's own listing shows it, numbered under the
389
+ forward's handle (`D_attachment_path_handle`).
390
+ - **What `attachmentInfos` lists** (testbed, 159). Thunderbird's C++
391
+ MIME code decides this, so the rule is measured, not read off source;
392
+ `ForwardedMail` follows it, and `dev/testbed/mail/*.eml` holds the
393
+ Apple Mail, Outlook and odd-leaf trees it was measured on;
394
+ `dev/testbed/compare-forwards` re-checks the two agree.
395
+ - A **file name, or `Content-Disposition: attachment` alone**, lists a
396
+ leaf at any depth: Apple Mail's PDF inside
397
+ `alternative > mixed > [html, pdf, html]` too. A leaf with no name
398
+ is listed as `Part 1.2`, after its part path.
399
+ - **Inside `multipart/related`, nothing** is listed, named or not: an
400
+ image an HTML part shows by `cid:` (Outlook's `image001.png`). The
401
+ same image `inline` under `mixed` is listed.
402
+ - An **unnamed leaf** is body when it is text/plain or text/html, under
403
+ `mixed` too (a trailing footer). Any other unnamed leaf is listed,
404
+ unless it is an `alternative`'s rendition, like an invitation's
405
+ `text/calendar`. So the HTML half of a newsletter's `alternative` is
406
+ never listed.
407
+ - A forward's text body is appended to the outer message's `c0body`
408
+ with no separator, at any depth.
409
+ - Ignore: `imConversations*`, `ext_mimeTypes`.
410
+
411
+ **The mozporter sharp edge.** Both FTS tables use Mozilla's custom `mozporter`
412
+ tokenizer, so a stock SQLite (CLI *or* the `sqlite3` gem) cannot `… MATCH …`
413
+ against them — it errors *"unknown tokenizer: mozporter"*. Worse, the gem's
414
+ precompiled SQLite (3.53.2) is built **FTS5-only**, so it can't even *open*
415
+ Gloda's fts3 `messagesText` (`no such module: fts3`). Registering a mozporter
416
+ tokenizer `.so` was tested and is a dead end on the default stack (it needs a
417
+ bespoke FTS3-compiled SQLite build, not just a loadable tokenizer). Escape:
418
+ read the plain `messagesText_content` columns directly (openable fine) and
419
+ build our own FTS5 over them — which is exactly what {Pikuri::Thunderbird::Gloda}
420
+ does. (`c0body LIKE '%invoice%'` scanned cleanly, 234 hits, on the real box.)
421
+
422
+ **Freshness/consistency: the change counter.** `journal_mode=delete` (classic
423
+ rollback journal, no WAL), `user_version=30` (a drift anchor). The file change
424
+ counter (header bytes 24–27) is authoritative per commit here, bumped only on
425
+ unlock-after-write (a read never moves it). Measured: it bumps on *any* Gloda
426
+ write — **including read/star/tag flips during triage** (marking one message
427
+ unread advanced it +1), not only new-mail arrivals — because Gloda indexes
428
+ those as attributes. Consequence for the FTS5 rebuild: it re-fires during
429
+ ordinary triage, not just after a poll: a ~1 s papercut, kept, since a gate on
430
+ content would miss a move and a late body download, which Gloda writes in place
431
+ (why not: {Pikuri::Thunderbird::Gloda}). The `-journal` is **transient, not persistently
432
+ retained** (probed: present in 1 of 3 idle samples, exactly while the counter
433
+ was mid-bump), so its presence is a valid "write in flight → retry" signal for
434
+ the snapshot bracket.
435
+
436
+ **Across a real poll** (testbed, Thunderbird 159, an IMAP poll bringing N new
437
+ messages to an offline INBOX, `-journal` sampled every 20 ms). Gloda indexes such
438
+ a message only once its body is local, so the burst starts at the body download,
439
+ not at the header fetch. It commits in batches, not per message: N=3 → +3, N=20
440
+ → +2, N=100 → +2, N=400 → +3 on the counter. One transaction holds the
441
+ `-journal` for most of the burst, and it **grows with the poll, about 11 ms a
442
+ message**: 0.65 s at N=20, 1.1 s at N=100, 4.4 s at N=400. After that, nothing
443
+ for the next 40–60 s; a rerun of the 100-message poll held it 2.0 s. No fixed
444
+ retry budget covers every poll, hence the stale fallback above: during that
445
+ rerun, a search every 100 ms through one shared `Gloda` never failed. The two
446
+ that landed inside the window waited ~0.8 s and answered from the older copy,
447
+ and the first one after the burst took 0.27 s to copy and re-index. (In a headless session autosync never fetched the new bodies
448
+ on its own within 90 s; the measurement fetched them with
449
+ `downloadMessagesForOffline`, which is what autosync does.)
450
+
451
+ **Gmail label fan-out (why dedup is mandatory).** Gmail exposes each label as
452
+ an IMAP folder, so a message with N labels yields N Gloda rows.
453
+ **`[Gmail]/All Mail` is indexed** (`indexingPriority` 20, **5974 messages** —
454
+ the largest folder, vs. 8239 distinct Message-IDs / 9654 total rows → ~1415
455
+ duplicate rows). Search dedups by `headerMessageID` before the top-N cap. The
456
+ 7 `-1` never-indexed folders are exactly Trash/Spam/Junk/Unsent across the
457
+ accounts — so the "skip Spam" leg-2 attenuation is free on the Gloda path —
458
+ **except `[Gmail]/Trash` is indexed at prio 20** (5 msgs), so that skip is
459
+ nearly, not perfectly, complete. (Also seen: 1571 rows with a null/blank
460
+ `folderID` — irrelevant to Gloda-only reads, which take the body from
461
+ `c0body`.)
462
+
463
+ ### Mail: mbox on disk — where attachment bytes live
464
+
465
+ Read only by {Pikuri::Thunderbird::MessageStore}, for
466
+ `thunderbird_mail_attachment_read`; search and body reads stay on Gloda. Mail
467
+ is **mbox** (extensionless files, `file(1)` "Mailbox text"), under
468
+ `ImapMail/<server>/` (IMAP, subfolders nest via `<Folder>.sbd/`) and `Mail/`
469
+ (Local Folders, Feeds), each shadowed by a `<Folder>.msf` **Mork** summary.
470
+
471
+ - **Format:** CRLF line endings; the dash-prefixed `From - <ctime>` separator
472
+ (not classic `From <addr>`); server-defined folder names (Gmail INBOX is
473
+ uppercase — never hardcode); the `X-Mozilla-Status` **expunged** bit
474
+ (`0x0008`) marks a deleted-but-not-compacted copy — common enough that a
475
+ reader must skip it.
476
+ - **Which directory:** `prefs.js` is the only map from an account to its store
477
+ directory (`mail.server.serverN.directory-rel` / `.hostname` / `.userName` /
478
+ `.type`); a second account on one host gets a `-1` directory. The store kind
479
+ is per server (`.storeContractID`, `…/berkeleystore;1` = mbox,
480
+ `…/maildirstore;1` = one file per message); the global
481
+ `mail.serverDefaultStoreContractID` was absent from `prefs.js` because
482
+ Thunderbird ships it as mbox for every account type, POP3 and IMAP alike
483
+ (159's `defaults/pref/mailnews.js`). Maildir is a per-account opt-in, so
484
+ only mbox is read and a Maildir account is refused with a message. Should
485
+ that change, the testbed indexes Maildir as-is (one file per message
486
+ dropped into `<folder>/cur/`), and a `Message-ID:` header scan over its
487
+ 177 files took ~1 ms. Gloda's `folderURI`s are
488
+ **not RFC 3986** (raw `[Gmail]` brackets and spaces — Ruby's `URI()` raises),
489
+ so they are split by regex and percent-decoded.
490
+ - **Which message:** `messageKey` is the IMAP UID under `ImapMail/`, and the
491
+ byte offset lives only in the `.msf`; whether it is an offset for local
492
+ `Mail/` was not re-verified. So the reader finds a message by **scanning for
493
+ its `Message-ID:` header**: ~0.5 s through a 440 MB `[Gmail]/All Mail` (warm
494
+ page cache), fast enough that no offset memo is kept. A `Message-ID:` line
495
+ inside a *body* (a forwarded mail) is skipped; the few Message-IDs seen twice
496
+ in one mbox were byte-identical copies, so the first live one wins.
497
+ - **Coverage:** all 1088 attachment-bearing IMAP messages were in the offline
498
+ store with full bodies. A message whose body was never offline doesn't reach
499
+ this store at all: Gloda indexes it from headers alone, with `c0body` NULL
500
+ and no `attachmentInfos`, even with the server reachable (testbed, 159: 14
501
+ attachment mails in a folder with its Offline flag cleared). A NULL
502
+ `c2attachmentNames` is the tell — a parsed message with none has `""` — so
503
+ `thunderbird_mail_read` says the body isn't downloaded and names the setting
504
+ to change ({Pikuri::Thunderbird::Gloda::Mail#read}). Downloading the folder
505
+ later makes Gloda re-index them with body and attachment list. "Not stored" is left for a copy gone from the offline
506
+ store after Gloda indexed it with a body.
507
+ - **Read live, without a snapshot:** an mbox has no SQLite-style lock, and a
508
+ multi-GB copy per read is absurd. Thunderbird appends new mail and compacts
509
+ by renaming a new file over the old, so one fd held for the whole scan stays
510
+ self-consistent; a message appended mid-read is not in Gloda yet anyway.
511
+
512
+ ### Calendar stores (`calendar-data/`)
513
+
514
+ Three sibling DBs: **`cache.sqlite`** (cached network/CalDAV calendars),
515
+ **`local.sqlite`** (`storage`-type local calendars), `deleted.sqlite`
516
+ (`cal_deleted_items` sync tombstones). **The data gate:** a CalDAV calendar
517
+ keeps events **in memory only** unless "Offline Support" (`cache.enabled` in
518
+ `prefs.js`) is on — so all three can be empty while the UI shows full
519
+ calendars. Enabling it populated `cache.sqlite` to **62 MB / 5414 events** and
520
+ it mirrors `local.sqlite`'s schema exactly (`cal_calendar_schema_version=23`;
521
+ `user_version` is 0 — gate on the table, not the pragma). This is why the
522
+ calendar tools register regardless and self-explain the empty state.
523
+
524
+ `cal_events` is normalized columns, not opaque ICS:
525
+
526
+ - `cal_id` (the calendar's registry UUID → `prefs.js`
527
+ `calendar.registry.<uuid>.{name,type,uri,cache.enabled}` for human name +
528
+ `storage`/`caldav` type), `id` (event UID), `title`.
529
+ - `event_start`/`event_end` — **PRTime µs of the UTC instant** (confirmed on
530
+ 5414 events: sane 2010→2031 histogram; times read as business hours only
531
+ under UTC→local; user-confirmed against the live UI — a 10:00 meeting reads
532
+ 10:00 local, not 07:00 UTC). Displayed via the `_tz` column.
533
+ - `event_start_tz`/`event_end_tz` — a tzid string, and the two **can differ**
534
+ (cross-zone events). Valid forms, all meaningful: Olson names
535
+ (`Europe/Helsinki` dominant), literal **`floating`** (wall-clock; every
536
+ all-day event uses it), **`UTC`**, rare fixed-offset **`GMT+0300`**. Default
537
+ defensively even though no null was observed. An imported `DTSTART` without
538
+ a `TZID` is stored `floating`; an Olson `TZID` with no `VTIMEZONE` block is
539
+ resolved by name (Thunderbird 159).
540
+ - `flags` = calStorageCalendar's `CAL_ITEM_FLAG` bitfield (verify against
541
+ comm-central before relying on a bit): 2=attendees, 4=properties, **8=all-day**,
542
+ 16=recurrence, 32=exceptions, 64=attachments, 128=relations, 256=alarms,
543
+ 512=recurrence-id-all-day. **All-day = bit 8** — airtight (a clean diagonal:
544
+ 126 rows, `flags&8` ⟺ midnight-aligned start ⟺ `tz=floating`, zero
545
+ off-diagonal). All-day DTEND is iCal **exclusive** (1-day event spans exactly
546
+ 1 day), so render `[start, end − 1 day]` and don't zone-convert.
547
+ - `ical_status`, `priority`, `privacy`, recurrence fields. **`recurrence_id`**
548
+ is the fold key: a recurring series is stored as a *master* row
549
+ (`recurrence_id` NULL, `flags & 16` set, RRULE in `cal_recurrence`) **plus one
550
+ row per modified occurrence** ("exception") — same event UID, distinct
551
+ `recurrence_id` (the occurrence's PRTime), and *no* `flags & 16` bit. So a
552
+ per-row recurrence filter on `flags & 16 = 0` leaks every occurrence under
553
+ "single" and floods plain search with the same event; `Calendar#search` folds
554
+ rows by UID (`#fold_series`) and classifies the *series* recurring if any row
555
+ is a master or an occurrence.
556
+ - The master's `event_start` is the series' **first** occurrence; no row holds
557
+ any later one that wasn't edited. So a date range can't select a master:
558
+ `Calendar#search` fetches every master alongside the range's rows and
559
+ `Recurrence` expands it; a search without a range, and a read, date it at
560
+ its current occurrence instead. An edited occurrence's `recurrence_id` is the
561
+ instant it replaces, so the expansion drops that date and the row reports it
562
+ (`D_recurrence_expansion`).
563
+
564
+ Companions: `cal_todos` (VTODO, same shape); `cal_properties(item_id, key,
565
+ value)` (DESCRIPTION, LOCATION, …); `cal_recurrence(item_id, cal_id,
566
+ icalString)` holds a series' `RRULE` / `EXDATE` / `RDATE` content lines
567
+ verbatim, one per row, `EXDATE` and `RDATE` with their `TZID` param;
568
+ `cal_attendees`/`cal_alarms`/`cal_relations`/`cal_attachments` are likewise
569
+ iCal-shaped `icalString` fragments.
570
+
571
+ ### SQLite locking
572
+
573
+ Thunderbird opens its DBs with `locking_mode=EXCLUSIVE`, so a plain
574
+ `-readonly` open fails *"database is locked (5)"* while it runs — **even for
575
+ WAL stores** (the calendar DBs are WAL, and WAL readers are still shut out).
576
+ `immutable=1` is the universal lock-bypass; for a WAL store it reads
577
+ as-of-last-checkpoint. Right after the 62 MB sync the `-wal` held ~1 MB and
578
+ `immutable=1` saw all 5414 events — but that is a busy DB. **A handful of new
579
+ rows stays in the `-wal` until Thunderbird quits** (testbed, Thunderbird 159: an
580
+ event added live sat in a 2.3 MB `-wal`, invisible to `Calendar#search`, and
581
+ appeared after the clean quit's checkpoint). So an `immutable=1` read misses
582
+ it, and {Pikuri::Thunderbird::DatabaseSnapshot} copies the `-wal` beside the
583
+ main file and opens the copy normally. With `locking_mode=EXCLUSIVE` there is
584
+ no `-shm` to copy; SQLite rebuilds it from the WAL, even on a read-only open.
585
+ Live check: `dev/testbed/js/add-event.js` during a session, then
586
+ `Calendar#search` for "Live event".
587
+
588
+ ### Platform confinement (snap `home` interface)
589
+
590
+ Mapped by staging a probe `.ics` in three spots and opening each in a
591
+ snap-confined Thunderbird:
592
+
593
+ | Location | Readable by snap TB? |
594
+ |---|---|
595
+ | snap-owned area (`~/snap/thunderbird/common/…`) | **yes** |
596
+ | hidden home dir (`~/.cache/…`) | **no** |
597
+ | non-hidden home (`~/…`) | **yes** |
598
+
599
+ The recalled dotfile restriction is real: the `home` interface grants
600
+ non-hidden `$HOME` files, not dotfiles. **Sharp UX edge:** a blocked path does
601
+ *not* error — the `.ics` import wizard opens and reports "no events available"
602
+ (it read an empty file) — so staging correctness can't lean on error
603
+ detection. Consequence: the inbound snapshot lives in hidden `~/.cache` (read by
604
+ *pikuri*, unconfined — fine), but the outbound `.ics` hand-off must stage where the
605
+ confined TB reads (snap-owned area, or a non-hidden `$HOME` dir); the two dirs
606
+ can't be shared on snap.
607
+
608
+ ### Hand-off mechanics — for the egress tools
609
+
610
+ - **Compose → `mailto:` URI (built).** `thunderbird 'mailto:to@…?cc=…&bcc=…&subject=…&body=First%0ASecond'`
611
+ opens a pre-filled compose window, percent-decoding cleanly (`%0A`→newline,
612
+ `%20`→space), populating subject + cc + **bcc**, reusing the running
613
+ instance. Chosen over `-compose`, which **cannot do multiline** (`body='A%0AB'`
614
+ rendered the literal `A%0AB`). Because the transport is a URI, every field
615
+ value must be percent-encoded so an attacker-authored body can't smuggle a
616
+ hidden `&bcc=` — see {Pikuri::Thunderbird::MailtoUri}. pikuri launches it
617
+ detached (`setsid --fork`) so the agent's exit-sweep can't SIGTERM the user's
618
+ Thunderbird, and so a not-yet-running Thunderbird doesn't block the tool on
619
+ the GUI.
620
+ - **Create event → `.ics` import (built).** `thunderbird <path.ics>` opens TB's
621
+ "Import Calendar file" wizard as a new tab (running-instance reuse): a 4-step
622
+ flow ending in **Confirm**, with a **target-calendar picker** at step 3.
623
+ **No silent import** — Cancel leaves nothing behind. So TB's UI owns the
624
+ commit *and* the human picks local-vs-CalDAV (i.e. no-egress-vs-egress). The
625
+ `.ics` is built by {Pikuri::Thunderbird::IcsEvent} (RFC-5545 field escaping is
626
+ the injection defense), staged in {Pikuri::Thunderbird::Profile#outbox_dir}
627
+ (confined-readable, **not** the hidden `~/.cache` snapshot dir — see § "Platform
628
+ confinement"), and handed off by the shared {Pikuri::Thunderbird::Launcher}
629
+ (the same detached `setsid --fork` launch compose uses).
630
+ - **An import into a CalDAV calendar can still mail invitations — the server's.** The
631
+ wizard's commit is `CalendarFileImporter.startImport`: one `addItem` per item, a plain PUT,
632
+ no iTIP from Thunderbird. But an RFC 6638 `calendar-auto-schedule` server schedules *on the
633
+ PUT* when the `ORGANIZER` is the calendar's owner: Cyrus mailed an outside `ATTENDEE` an
634
+ iMIP `REQUEST`, put a same-server attendee's invitation into their scheduling Inbox *and*
635
+ their calendar, and mailed a `CANCEL` on DELETE. Two shapes stop it: `SCHEDULE-AGENT=CLIENT`
636
+ on an `ATTENDEE` (RFC 6638 §7.1) stops all three for that attendee, and an event with no
637
+ `ORGANIZER` isn't a scheduling object at all. Thunderbird's import keeps the parameter in
638
+ its PUT and adds no `ORGANIZER`. **A later edit in Thunderbird's event dialog strips the
639
+ mark:** its Save calls `cal.itip.adaptScheduleAgent`, which on an auto-scheduling calendar
640
+ whose iMIP identity is the organizer (and `forceEmailScheduling` off, the default) deletes
641
+ `SCHEDULE-AGENT=CLIENT` from every attendee, so the server then mails each one a *first*
642
+ `REQUEST`. Import never calls it. The wizard selects the first event and shows its details,
643
+ attendees included.
644
+ A rootless Cyrus 3.12 beside the testbed, Thunderbird 160, 2026-11-21; the import ran the
645
+ wizard's own two calls over Marionette, and the dialog's Save was replicated, not clicked.
646
+ Not seen: Sabre (Nextcloud, Baikal), iCloud, Google — Google's the likeliest to ignore it.
647
+ Why the tool carries no attendees: `D_no_calendar_attendees`.
648
+
649
+ Both are the human-gated hand-off shape the no-send seam requires: pikuri
650
+ opens a window, the human reviews and commits.
651
+
652
+ Re-confirmed on Thunderbird 159 under Xvfb (testbed, 2026-11-13):
653
+ {Pikuri::Thunderbird::Launcher}'s `setsid --fork thunderbird mailto:…` remoted into the running instance and
654
+ opened a compose window with From, To, Subject and the multi-line body intact;
655
+ an `.ics` path opened the import wizard. No second instance started.
656
+
657
+ ### Files never touched
658
+
659
+ The guarantee is an **allowlist, not a blocklist**: the backends open only
660
+ `global-messages-db.sqlite` and `calendar-data/*.sqlite` (plus their snapshot
661
+ copies), discovery reads `profiles.ini` and `prefs.js` (its `mail.server.*` and
662
+ `mailnews.database.global.indexer.enabled` lines only — passwords live in
663
+ `logins.json`, not there), and the attachment reader reads the same
664
+ `mail.server.*` lines and the mbox files under `ImapMail/` and `Mail/`. Nothing else in
665
+ the profile directory is ever opened — so no enumeration of what-to-avoid is load-bearing,
666
+ and a wrong name below changes nothing.
667
+
668
+ For orientation, the profile dir (the same dir as the Gloda file) also holds
669
+ the credential/secret stores pikuri stays clear of: the NSS key/cert databases
670
+ `key4.db` + `cert9.db`, saved passwords `logins.json` + `logins-backup.json`,
671
+ and Thunderbird's OpenPGP key material (including
672
+ `encrypted-openpgp-passphrase.txt`). These names are **recalled from the
673
+ Firefox/Thunderbird profile layout, not probe-confirmed and not exhaustive**
674
+ (verify against a real profile if it ever matters — but it doesn't, given the
675
+ allowlist). Browser/telemetry cruft (`places.sqlite`, `cookies.sqlite`,
676
+ `favicons.sqlite`, `storage/`, `datareporting/`, …) is likewise untouched.
677
+
678
+ ## The testbed: a real Thunderbird with no real mail (dev only)
679
+
680
+ `dev/testbed/` builds the profile this gem is tested against on the dev VM, and drives a running Thunderbird for live tests. Why it exists and why it is shaped
681
+ so: `D_thunderbird_testbed`. The scripts' headers say how to run them; this is the picture
682
+ across them.
683
+
684
+ **Setting up the dev VM.** Ubuntu packages only, plus the Thunderbird snap Ubuntu ships:
685
+
686
+ ```
687
+ sudo snap install thunderbird
688
+ sudo apt install xvfb ffmpeg libreoffice dovecot-imapd
689
+ sudo systemctl disable --now dovecot.service dovecot.socket
690
+ ```
691
+
692
+ `xvfb` and `ffmpeg` serve `session --display` and its screenshot; LibreOffice renders the demo
693
+ documents (`dev/demo-home/`); dovecot is the IMAP server below. Ubuntu's package enables and
694
+ starts the system dovecot on install, listening on 143 and 993 on every interface; the testbed
695
+ never uses it (it runs its own), hence the `disable --now`, which stops it, keeps it off at
696
+ boot, and stops socket activation from waking it. `ss -ltn | grep -E ':(143|993)\b'` printing
697
+ nothing confirms it.
698
+
699
+ **We write the inputs, Thunderbird writes its stores.** The builder writes only what
700
+ Thunderbird reads as input — `user.js`, mbox files, an `.ics`, and the mail an IMAP server
701
+ serves — and a real headless Thunderbird builds `prefs.js`, the IMAP offline store, the `.msf`
702
+ summaries, Gloda and `calendar-data/cache.sqlite` from them. Alex's account is IMAP
703
+ (`alex@novak.example`, the login an address as on Gmail, so its folder URIs carry `%40`),
704
+ synced from a dovecot on loopback into `ImapMail/127.0.0.1/`; it is not Local Folders, which has
705
+ no identity, so Gloda would have no "me", no Sent folder and no correspondence graph. Local
706
+ Folders holds an `Archive` (CI mail older than 90 days), so `Mail/` is a real store too. Every
707
+ domain is RFC 2606-reserved, so a Send clicked by mistake fails.
708
+
709
+ A second account, Alex's personal `alex.novak@kotiposti.example`, sits on the same dovecot (a
710
+ `mail.yml` scene's `account:`). Its `user.js` names no store directory, so Thunderbird picks
711
+ one, as for an account added in its wizard: the name taken, it inserts `-1` before what it reads
712
+ as an extension, `ImapMail/127.0.0-1.1/` (`imap.gmail-1.com` for a second Gmail), recorded only
713
+ in `prefs.js`. It picks so only when the first account's directory exists, as on a real install
714
+ it long has; on a fresh profile neither did, and both accounts got `127.0.0.1/`, so the builder
715
+ creates that one, empty.
716
+
717
+ **Gmail's folder shape, without Gmail.** Dovecot nests folders with `/` and serves
718
+ `[Gmail]/All Mail` (`\All`) and `[Gmail]/Starred` (`\Flagged`) under a non-selectable `[Gmail]`;
719
+ a `mail.yml` scene filed in two folders is two copies with one Message-ID, as a Gmail label
720
+ makes. All Mail is synced headers-only, as many keep it, so the testbed holds a message whose
721
+ read prefers its downloaded copy (INBOX's, or Starred's), one with no body at all, and an mbox
722
+ at `ImapMail/127.0.0.1/[Gmail].sbd/Starred`.
723
+
724
+ **"Not stored on this computer"** is a scene too (`dropped: true`): after the index, the
725
+ build deletes its copy through the store's own `folder.msgStore.deleteMessages`, which sets the
726
+ expunged bit in its mbox's `X-Mozilla-Status`. Gloda listens to folders, not to the store, so it
727
+ keeps the row and its text, and the attachment read finds no live copy. After the quit the
728
+ builder checks the bit landed. Editing the mbox itself would break the rule above.
729
+
730
+ **The IMAP server: a rootless dovecot, up only during a build** (`builder/dovecot.rb`). An IMAP
731
+ folder's `.msf` and its UIDs come from the server's replies, so the mail has to be downloaded
732
+ for real (why a real server: `D_thunderbird_testbed`). Dovecot 2.4 (Ubuntu's; most guides online
733
+ are 2.3 syntax) runs as the caller with `chroot =` on the login service, only the plain `imap`
734
+ listener (port 10143, fixed because it is in `user.js` and so in the cache key), a static
735
+ passdb whose password Thunderbird gets over Marionette, and every file in one fresh `/tmp`
736
+ directory, since a socket path over 108 bytes fails. It serves **Maildir**, not mbox: its mbox
737
+ driver rewrites the file to add `X-UID`, which failed on the CRLF mbox ("Sync failed for mbox"),
738
+ and Thunderbird took the failed body fetch as success. A Maildir file is never rewritten, and
739
+ its mtime is the message's `INTERNALDATE`.
740
+
741
+ After the build nothing listens on 10143, so the account has `check_new_mail`,
742
+ `login_at_startup` and `autosync_offline_stores` off; a session on the cached profile opens no
743
+ connection at all (20 s under `MOZ_LOG`, 2026-11-15). Clicking an IMAP folder in a `--display`
744
+ session would try to connect and fail.
745
+
746
+ **The demo world** is the repo root's `dev/demo-home/`: one facts file (`facts.yml`) and the
747
+ demo `~/Documents` (`documents/`) rendered from it. The testbed reads both — the scene mail
748
+ (`mail.yml`) and the calendar from the same facts, the mail's attachments from those documents —
749
+ so its `build` writes `~/Documents` too, with the same `--today`; every date is an offset from
750
+ the build day. The dependency runs one way: the demo home knows nothing of Thunderbird. Seeded
751
+ noise (`builder/noise.rb`) gives search something to rank past. `mail.yml`'s comments say which
752
+ scene each message serves.
753
+
754
+ **Driving Thunderbird: Marionette.** Release Thunderbird ships Marionette, Mozilla's remote
755
+ protocol, and in *chrome context* — Mozilla's word for the application's own privileged JS — a
756
+ script can call Thunderbird's APIs (`MailServices`, Gloda, `cal.manager`).
757
+
758
+ - It needs `--marionette` and the env var `MOZ_REMOTE_ALLOW_SYSTEM_ACCESS=1`; on 159 the
759
+ `--remote-allow-system-access` flag alone isn't enough. `marionette.port = 0` makes it pick a
760
+ free port and write it to `<profile>/MarionetteActivePort`.
761
+ - The wire is length-prefixed JSON over TCP (`len:[0, id, "Name", {params}]`, reply
762
+ `len:[1, id, error, result]`); `builder/marionette.rb` is the whole client. One WebDriver
763
+ session at a time, so a client must `DeleteSession` before the next can connect.
764
+ - **The IMAP sync is driven too**, since with mail checks off nothing connects:
765
+ `MailServices.imap.discoverAllFolders`, then per folder `setFlag(Offline)` and
766
+ `downloadAllForOffline`, which selects the folder, syncs its headers and fetches every body;
767
+ a headers-only folder gets `clearFlag(Offline)` (discovery sets it from the server's
768
+ `offline_download`) and `updateFolderWithListener` instead.
769
+ An account from `user.js` lacks the Offline flag on INBOX (the account wizard's "keep
770
+ messages on this computer" sets it), and without it INBOX's bodies are never fetched. A sync's
771
+ listener can hear an earlier URL end, and the step then finds the folder busy and does
772
+ nothing, without an error: a separate `updateFolderWithListener` before the download did so,
773
+ and so did the second account's first INBOX download, which passed a "no header lacks its
774
+ body" check on zero headers. So each folder is synced again until it holds as many headers as
775
+ the builder wrote there, each with its body (or, headers-only, none).
776
+ - **A dropped mbox is never picked up on its own:** with mail checks off nothing opens a
777
+ folder, so no `.msf` appears and Gloda's sweep skips it (four minutes, zero rows). The index
778
+ step reparses each Local Folders folder (`getDatabaseWithReparse`, which throws
779
+ `NS_ERROR_NOT_INITIALIZED` to mean "reparse started") and then queues every folder
780
+ (`GlodaMsgIndexer.indexFolder(folder, {force: true})`); `indexFolder` alone indexes
781
+ nothing. Done is detected by count, not by Gloda's internals: the builder knows it wrote N
782
+ message copies, B of them in folders with bodies, and counts a copy of the Gloda DB until it
783
+ holds N rows, B with a body — an IMAP message Gloda reaches before its body is offline is
784
+ indexed from its headers alone, and would count too early.
785
+ - A clean quit is a script that resolves and then dispatches
786
+ `Services.startup.quit(eAttemptQuit)`: about two seconds, the WAL stores checkpointed, and
787
+ open compose windows discarded without a prompt.
788
+ - A process starts as `thunderbird` and renames itself `thunderbird-bin` once the launcher
789
+ execs the real binary; a lookup checks both names (`pgrep -x` matches the 15-character name).
790
+ Never `pkill -f thunderbird`: it matches the agent's own shell, whose command line holds the
791
+ word.
792
+ - `MOZ_CRASHREPORTER_DISABLE=1`, or the crash helper creates `~/Downloads/thunderbird.tmp/`.
793
+
794
+ **Hand-offs on a headless machine.** A session started with `--display` runs on its own Xvfb
795
+ and accepts remote commands, so `DISPLAY=:N` on the agent's side makes a real hand-off land in
796
+ it (§ Hand-off mechanics). `js/compose-windows.js` reads the open compose windows back as
797
+ Thunderbird parsed them; `session screenshot` grabs the screen (`ffmpeg -f x11grab`). There is
798
+ no window manager, so windows stack; clicking goes through Marionette, not the screen.
799
+
800
+ **A quiet first run.** `user.js` carries the network prefs from Marionette's own
801
+ `RecommendedPreferences.sys.mjs` (inside Thunderbird's `omni.ja`, under
802
+ `chrome/remote/content/shared/`), among them `services.settings.server =
803
+ "data:,#remote-settings-dummy/v1"`, which stops the remote-settings fetch a plain first run
804
+ makes. `strace` can't follow into a snap without root (snap-confine is setuid), so the check is
805
+ Mozilla's logging: `MOZ_LOG="nsHostResolver:5,nsSocketTransport:5,nsHttp:3"
806
+ MOZ_LOG_FILE=~/snap/thunderbird/common/moz.log dev/testbed/build --rebuild` showed no
807
+ DNS lookup and no HTTP channel, only Marionette's loopback socket and, since the IMAP account,
808
+ dovecot's `127.0.0.1:10143` (2026-11-15, 159). Re-run it after a Thunderbird upgrade; a fetch on
809
+ a later timer would slip past a build that lasts seconds.
810
+
811
+ **Byte-stable inputs, so the cache hits.** The indexed profile is tarred under
812
+ `Paths.cache/thunderbird-testbed/`, keyed by Thunderbird's version and a digest of every input.
813
+ That needs inputs that repeat: the `mail` gem's random multipart boundaries are replaced by ones
814
+ derived from the Message-ID, zips get fixed times, and LibreOffice output (which stamps a fresh
815
+ date and ID into every PDF) is cached by source digest, under `Paths.cache/demo-home/` so the
816
+ demo home's own build reuses it. Measured on 159: 201 message copies sync and index in
817
+ ~9 s, a cached build takes 2 s.
818
+
819
+ **The guard.** Every demo directory carries a `.pikuri-demo` marker. The build refuses while
820
+ either root holds an unmarked profile, or while Thunderbird runs, and checks the demo home's
821
+ own guard (`~/Documents` non-empty and unmarked) before writing anything; it never deletes
822
+ anything unmarked and never stops a Thunderbird it didn't start.
823
+
824
+ **Not covered:** Gmail's own IMAP extension, `X-GM-EXT-1`, and so Thunderbird's Gmail-only
825
+ paths (one offline body shared across labels). Dovecot can't stand in: advertising the
826
+ capability (`imap_capability`) would make Thunderbird fetch `X-GM-MSGID`/`X-GM-LABELS`, which
827
+ dovecot answers with BAD.