Skip to content

feat(mail): each email gets its own type and reach (store version 76) - #3358

Merged
leemour merged 4 commits into
mainfrom
feat/mail-types
Nov 25, 2026
Merged

leemour merged 4 commits into
mainfrom
feat/mail-types

Conversation

@leemour

@leemour leemour commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Task

Contact-kinds plan (#3323, section "Mail categories"; research notes 2026-11-25-contact-kinds-mail-products.md §2.1, IDEA-1, IDEA-2, IDEA-7 and the taxonomy in 2026-11-25-contact-kinds-domain-sources.md). Owner's rulings, 2026-11-25: every mail gets its own type, apart from its sender; a tab is a filtered view; reach is per mail; a sender's view is a summary of its mails.

Why

A sender's single kind puts a shop's receipts and its sales in the same place. With a type per email, Subscriptions can list any sender with broadcast mail, and Bots any sender with receipts, from the same store.

What

Classifier (src/mail/mail-types.ts, pure, no network). One type per email, first match wins:

# Type Signal (typeSignal)
1 auto_reply a message/delivery-status or message/disposition-notification part; mailer-daemon@/postmaster@; an out-of-office or undeliverable subject on mail with no list headers
2 security security@, verify@, 2fa@… or a sign-in/code/password-reset subject (EN/RU/ES); not when Gmail stamped DKIM or DMARC fail
3 calendar a text/calendar or application/ics part
4 travel schema.org *Reservation (flight, train, bus, lodging, car, taxi, boat); a boarding-pass/itinerary subject; sector airline on mail with no list headers
5 event_ticket schema.org EventReservation; a tickets subject
6 order schema.org Order; orders@/receipts@; an order or receipt subject (not when it is also a shipping subject)
7 shipping schema.org ParcelDelivery; shipping@/tracking@; a shipped/on-its-way subject; sector delivery
8 bill schema.org Invoice; billing@/invoices@; an invoice/statement/payment subject
9 social_notification sector social (the sender's organization)
10 discussion_list a List-Id three or more addresses send to (DISCUSSION_SENDERS); Precedence: list with no List-Id
— account_notice Zero's exception: List-Unsubscribe with no one-click or Feedback-ID, from an automated address
11 newsletter List-Id; news@/digest@; a newsletter subject; sector news; or any list mail from a person, not a bot
12 promotion a sale/discount subject; promo@/deals@/info@…; otherwise one-click unsubscribe, Feedback-ID or Precedence: bulk
13 system_alert alerts@/monitoring@/ci@/cron@…; a [FIRING]/build-failed subject
14 account_notice a signed Auto-Submitted; a no-reply address; an automated address (Zero's list)
15 personal the owner wrote to the sender, or a sender that is no bot and no null return path
16 other a bot's mail no rule names
  • Order differs from the plan in two places (for the owner to confirm): system_alert runs before the generic account_notice signals, since an alert carries Auto-Submitted too and would never be reached; and Zero's "automated sender with plain List-Unsubscribe" is an account_notice before the list types, which keeps receipts out of promotions.
  • Zero's gate (rule 1): mail from someone the owner wrote to (and who is no bot) is never typed by an address word, a subject or a sector, only by what the mail carries (parts, markup, list headers). Subject and address words are also never used on List-Id mail.
  • Header trust as today: Auto-Submitted, one-click unsubscribe and Feedback-ID are read only as mailHeadersOf keeps them, under the From domain's DKIM. List-Id, List-Unsubscribe and Precedence are kept unsigned today and read as such; they only push mail towards bulk types.
  • Reach per mail is reachOfOne from sender-signals.ts, now exported, the same rule the people list uses.
  • Ported from Zero (MIT, commit 4b642dfd): the check order and the AUTOMATED_SENDER / MARKETING_SENDER patterns. The notice is at the top of the file and in THIRD_PARTY_NOTICES. No Inbox Zero or Mailspring code.

Storage (store version 76, reserved in #3357). emails.mail_type, reach, type_signal; indexes emails_by_mail_type and emails_type_to_work_out (id WHERE mail_type IS NULL). Columns, indexes and 14 triggers added only, forward-only, minCompatible stays 73. Triggers null an email's type when what decides it changes:

  • its own From, subject, headers, metadata, outgoing flag or HTML body; its recipients; a calendar or report attachment;
  • a new sender on its List-Id (the discussion threshold);
  • the owner's first mail to its sender (an outgoing insert, or markOwnMail flipping outgoing);
  • its sender joining or leaving sender_bot_identities or organization_identities, or that organization's sector changing.
    A read that filters by types/reaches, and mailSenders, first fill what is missing, 5,000 per write. A query-only open fills nothing and works the missing ones out in memory, so a filtered list is never short. Unfiltered reads type only their page's untyped rows, in memory. Plain reads and syncs never fill.

API (experimental).

  • Email.mailType, Email.reach, Email.typeSignal.
  • store.mail.emails({ types, reaches, … }).
  • store.mail.mailSenders({ types?, reaches?, accountId?, since?, until?, limit?, offset? }) → { items, total }. Each item is { ref (person:<id> | sender-bot:<id> | null), addresses, name, emails, types, reaches, lastAt }. A sender is listed when any of its mail passes the filter, and its counts cover all its mail.
  • No memo command: that comes after a release.

Glossary: "mail type", "reach" and a "Mail types" table in docs/dev/GLOSSARY.md.

Signals not in the store today: what mail sync would need to keep. mail-cli is not changed.

  • schema.org markup. Sync keeps no HTML (src/mail/email-input.ts:29 stores bodyText only). htmlToText drops <script> (JSON-LD) and every tag attribute (microdata) (src/mail/parse.ts:39,65). Sync would need to keep the @type values schemaTypesOf reads, for example as headers."schema-types", or keep body_html. The classifier already reads body_html when an importer keeps it (tested).
  • Auto-Submitted: auto-replied is not kept: programSignalsOf keeps only generated values (src/mail/headers.ts:111). Auto-replies are found by their subject only. Sync would need an auto-replied key under the same DKIM rule.
  • X-Auto-Response-Suppress, X-Campaign (Zero reads both), List-Post (a discussion list's own marker), the Feedback-ID value (only its presence is kept) and the calendar part's METHOD (an invitation or a cancellation).
  • Envelope mail (kept by a rule, metadata.rule) has no recipients and no body: its reach is direct and its type comes from headers and the subject only.
  • Verified as stored: text/calendar and message/delivery-status parts keep their media type in attachments.mime (src/store/mail-types.test.ts).

Line limits raised as v72 and v74 did: spec.mjs 1893→1902, schema.ts 3260→3265, the emails.ts group 1012→1024. rollBackTo in src/testing/older-store.ts now undoes versions above 73 before version 73's table copies: those copies re-create every index, including one on a later column.

Testing

  • New: src/store/mail-types.test.ts (7, through syncMail), src/mail/mail-types.test.ts (32), src/store/version-76.test.ts (4,500 emails typed in batches after the upgrade from 75, a 1.0 build's write typed again, the index used).
  • pnpm typecheck, pnpm lint (no errors), schema:check, docs:check, api-report --check. The full vitest suite before the rebase passed: 991 files, 13,717 tests. After the rebase onto feat(people): bots are their own entity, apart from people (store version 75) #3356: src/store and src/mail, 309 files, 2,481 tests.
  • Timings on 100,000 synthetic emails (load 14–20, other agents writing to the disk): the first filtered read types all of them in 1.7–11.6 s. One batch of 5,000 holds the write lock 91–628 ms. Warm filtered pages take 10–21 ms, mailSenders 190–280 ms, and a query-only read of an untyped store 0.7–1.8 s. The cost is the commit's sync to disk, not the classification (about 15 ms per 2,000). Page and script: cli-testing#411, performance/mail/types.

Not in this PR: rules by address and domain, and scoped corrections (the plan's next step); memo commands; the Desktop tabs.

🤖 Generated with Claude Code

leemour and others added 4 commits November 25, 2026 21:20
A deterministic classifier gives every email one type, first match
wins: auto_reply, security, calendar, travel, event_ticket, order,
shipping, bill, social_notification, discussion_list, newsletter,
promotion, system_alert, account_notice, personal, other. It also gives
a per-mail reach (direct, group, broadcast) by the rule senders already
use (`reachOfOne`). Inputs are local only: the stored headers (trusted
as `mailHeadersOf` keeps them), recipients, attachment media types,
schema.org markup in a kept HTML body, the sender's bot identity, its
organization's sector, and whether the owner wrote to the sender. The
check order and two sender patterns are ported from Zero's header
classifier (MIT, notice kept).

Store version 76 keeps `mail_type`, `reach` and `type_signal` on
`emails`, cleared by triggers on their inputs, as person kinds are. A
read that filters by type fills the missing ones in batches of 2,000;
a query-only open works them out in memory. `store.mail.emails` takes
`types` and `reaches`, and `store.mail.mailSenders` lists senders with
their mail counted by type and reach.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… per pass

A profile on 100,000 synthetic emails showed the classification itself
costs about 15 ms per 2,000 emails; the commit's sync to disk is the
cost. Larger batches finish sooner (first read 21.5 s -> 1.7-11.6 s
under load) and one batch still holds the lock well under 1 s. Each
List-Id's sender count is now read once per pass, not once per batch.

Also: Precedence: list marks a discussion list only without a List-Id
(its senders decide otherwise), subject and address words never type
List-Id mail, and "your order has shipped" is shipping, not order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@leemour
leemour merged commit 44ec110 into main Nov 25, 2026
47 of 48 checks passed
@leemour
leemour deleted the feat/mail-types branch November 25, 2026 20:33
leemour added a commit that referenced this pull request Nov 25, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
leemour added a commit that referenced this pull request Nov 25, 2026
…rsion 77) (#3366)

## Task

Contact-kinds plan (#3323, section "Mail categories"; research note
`2026-11-25-contact-kinds-mail-products.md`, IDEA-3 and IDEA-4, the
SaneBox and Inbox Zero notes). Owner's rulings, 2026-11-25: domain rules
on free-mail domains are allowed but never made by accident, the domain
scope is not offered first, preview before apply, every correction names
its scope and whether it covers past mail, corrections can be undone and
a sender's manual sorting reset.

## Why

#3358 gives each email a type from its headers. The owner needs to
correct it: "this mail is a receipt", "everything from this address is a
newsletter", "this whole domain is a bot". A correction must say how far
it reaches, and must never sort strangers on `gmail.com` together by
accident.

**Not `mail_rules`.** That table decides how one account's sync stores
mail (skip, envelope, tags) before an email exists, matches domains by
`endsWith`, and has no levels or authors. Sorting rules are
cross-account, decide what stored mail is, and need a fixed order. So
they get their own table and API (`store.mail.sorting`, beside the
storage `store.mail.rules`).

## What

**Order** (`src/mail/sort-rules.ts`, pure): the first scope that has a
rule wins.

| # | Scope | Value kept |
|---|---|---|
| 1 | `mail` | the email's id |
| 2 | `list` or `subject` | the List-Id (as `listIdOf` keeps it), or a
subject pattern (any case; any number matches any number) |
| 3 | `address` | the lower-case address, matched whole: `ann@` never
matches `joann@` |
| 4 | `domain` | the registrable domain (Public Suffix List), matched on
a label boundary: `shop.example` matches `mail.shop.example`, never
`myshop.example` |
| 5 | — | the header classifier of #3358 |

- Within a scope the owner's rule beats the program's, then the newest
wins (the IDEA-3 reading: owner-over-program holds within a level, not
across levels).
- A domain rule with `overAddresses` beats the address rules at its
domain (SaneBox's "override training").
- `applyTo: "new"` is a cutoff on the rule, checked against the mail's
own date, so a backfill of old mail counts as past and a later trigger
clear never retypes past mail with it.
- Outgoing mail is never typed by a rule.

**Actions.** A rule sets any of:
- the mail type;
- `sender: "bot" | "person"`, through `moveToBot` / `moveToPerson` only,
for the sender's whole history. Owner only, address or domain scope
only. An address rule that moves a sender refuses `applyTo: "new"`. A
domain rule with `applyTo: "new"` logs the domain's known senders as
left, and moves only senders first seen later. Mail sync settles the
senders of each saved batch when such a rule exists;
- `organization: "organization:<id>"`, through `holdAddress` (method
`sort-rule`), owner only.

What a rule did to each sender is logged in `mail_sort_effects`
(`before` and `after`). A removal puts each sender back, then lets the
rules still live settle it.

**Free-mail guard.** `isSharedMailDomain` = `FREE_MAIL` or the data
pack's `isFreeMailDomain` / `isPackFreeMailDomain` (#3359) or
`isDisposableDomain`.
- A domain rule there is the owner's only (a program's is refused:
`mail-sort.free-mail-program`).
- It is set only with the `confirm` of a dry run. The confirm is a hash
of the rule and its counts, so a dry run gone stale (new mail arrived)
is refused (`mail-sort.confirm`).
- No call widens a scope on its own: every add names its scope.
`scopes(email)` lists mail, list, address, domain in that order, the
domain last and flagged `freeMail`.

**API** (experimental), `store.mail.sorting`:
- `add(input, by, { dryRun?, confirm? })` → `{ applied, preview, rule?
}`. `preview` = `{ scope, value, label, applyTo, freeMail, addresses,
emails, retyped, senders, confirm }`.
- `rules({ scope?, removed? })`, `scopes(emailId)`, `remove(id, by)` (a
program removes only its own).
- `undo(by)`: the owner's newest add or removal not yet undone. Repeated
undo walks back; it does not toggle.
- `reset(sender, by)`: removes one sender's address and one-mail rules
(an address, `person:` or `sender-bot:`). Domain and list rules stay. A
direct `people.moveToBot` the owner made outside rules is not reset by
it.
- An email a rule typed has `typeSignal: "rule:<id>"`.

**Storage, store version 77** (reserved in #3360): `mail_sort_rules`,
`mail_sort_effects` (an identity's rows dropped with it by a trigger),
`emails.sort_checked` with the partial index `emails_sort_to_check`, and
a trigger that nulls it with `mail_type`.
- The upgrade marks every type already kept as checked (no rules
existed).
- A build before 77 that types mail writes no mark. Once a rule exists,
the next writable typed read works those emails out again. No trigger on
the old build's write path, so its own type loop still ends.
- Added only, forward-only, `minCompatible` stays 73.
- A rule change clears exactly the emails whose winning rule changes,
inside the same write.

Also: `listIdOf` exported from `mail/headers.ts` (reused, not copied);
16 `mail-sort.*` reasons; GLOSSARY "sorting rule"; biome line limits
raised as v72–v76 did (`spec.mjs` 1902→1908, `schema.ts` 3265→3269, the
`emails.ts` group 1024→1033).

## Timings

100,000 synthetic emails from 20,000 senders, load 6–17 ([cli-testing
page and script](WireCatLabs/cli-testing#412,
`performance/mail/rules`)):
- **Rule check:** 50 rules add about 0.35 s per 100,000 emails typed in
memory (560 → 915 ms). The first typed read is 7–18 s either way; the
commit's disk sync dominates.
- **Domain rule, company domain** (7 addresses, 35 emails): 0.3–0.7 s to
add, 0.2–0.4 s for the next typed read.
- **`gmail.com` rule** (6,000 addresses, 30,000 emails): dry run
0.14–0.19 s, add 1.0–1.2 s, next typed read 1.5–2.1 s. Undo costs the
same.
- **500 senders moved to bots** by one domain rule: 4–6 s when done in
one write (8–12 ms per `moveToBot`), past another writer's 5 s wait. So
the rule and its type clears are one write, and the senders then move
100 per write (about 1 s of lock each; 5.6 s in total). Moved back in
0.4–0.9 s.

## Testing

- New: `src/store/mail-sorting.test.ts` (10, through the store),
`src/mail/sort-rules.test.ts` (6: order, authors, override, anchoring,
cutoff, values), `src/store/version-77.test.ts` (upgrade from 76).
- `pnpm typecheck`, `biome check` (no errors), `schema:check`, the docs
checks, `cli-dev api-report --check` (stable API unchanged), full vitest
suite before the chunking change: 996 files, 13,773 tests; after it, the
sorting tests (17).

## Not in this PR

- A memo command (store API only, as asked).
- A sender rule over a free-mail domain with 6,000 senders would take
about a minute in total, in writes of 100 (an estimate from 8–12 ms per
move, not measured). Removal and undo still move senders back in one
write.
- **Removal leaves the owner's mark.** Moving a sender back goes through
`moveToPerson` / `moveToBot`, which log `author = 'owner'`. So a sender
a removed rule moved back counts as one the owner kept, and the kind
pass will not make it a bot by its own rules again.
- **A build that speaks 76 (cli-core 1.1.0)** types mail without the
rules and does not settle new senders under a sender rule. Types it
keeps are worked out again (`sort_checked`); senders it saves are
settled only on the next save by a build that speaks 77.
- **A subdomain value becomes its registrable domain.**
`mail.shop.example` is kept as `shop.example`, as the plan says. The
preview's `value` and `label` show it before apply.
- `reset` does not release a direct `people.moveToBot` / `moveToPerson`.
Those keep the owner's mark.
- Program rules set types only; no program-made sender rules.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant