diff --git a/changes/feat-contact-signals.md b/changes/feat-contact-signals.md
new file mode 100644
index 000000000..8879511e5
--- /dev/null
+++ b/changes/feat-contact-signals.md
@@ -0,0 +1,23 @@
+### Added
+
+- **`people.list` rows say how a sender's mail reached the owner.** Each row has `reach` (`direct`, `group`,
+ `broadcast` or `null`) and `signals` (`auto-submitted`, `null-return-path`, `no-reply`, `one-click-unsubscribe`,
+ `feedback-id`, `bulk-mail`, `discussion-list`, `many-recipients`, `undisclosed-recipients`), worked out for the page
+ and not stored ([ARCHITECTURE.md](../docs/dev/ARCHITECTURE.md)). A List-Id three addresses write to is a discussion
+ (`group`), one sender under many `+tag` addresses a newsletter. The types `Reach`, `SenderSignal` and `REACHES` are
+ exported from `./store`.
+- **Mail sync keeps `Auto-Submitted`, one-click `List-Unsubscribe-Post` and `Feedback-ID`** in `emails.headers`,
+ each only when a DKIM signature of the From's own domain that Gmail passed covers it, and an empty Return-Path
+ ([MAIL.md](../docs/dev/MAIL.md#syncmailsource-store-options)). Mail of an IMAP server without Gmail's stamp keeps
+ none of the three. No store version.
+
+### Fixed
+
+- **A sender whose mail a program sends is `automated`, not a stranger.** Most of their mail with a signed
+ `Auto-Submitted` (not an auto-reply) or an empty Return-Path makes them `automated` (signals `auto-submitted`,
+ `null-return-path`), unless the owner wrote to them. Every stored kind is worked out again on the next list.
+
+### Changed — may break callers
+
+- **`KindSignal` has two more values, `auto-submitted` and `null-return-path`, and `ListedPerson` two more fields,
+ `reach` and `signals`.** Code that maps every `KindSignal` or builds a `ListedPerson` by hand adds them.
diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md
index 38baa615d..c887720c4 100644
--- a/docs/dev/ARCHITECTURE.md
+++ b/docs/dev/ARCHITECTURE.md
@@ -660,7 +660,9 @@ proposes them instead. A no-reply address (`isNoReplyAddress`) is no one's: it n
one kind and lists one kind at a time. The owner, people added by hand and task assignees are a `person`; then
`automated` (a bot, a no-reply address, whose local part has a no-reply word as one of its parts or, `bounce`
aside, starts or ends with one; a notification address, with `notify`, `notification(s)` or `alert(s)` as one part;
- mostly bulk mail, memo's `bulk_never_replied`, a notification name); then
+ mostly bulk mail, memo's `bulk_never_replied`, a notification name; most of their mail with an `Auto-Submitted`
+ their own domain signed or an empty Return-Path ([MAIL.md](MAIL.md#syncmailsource-store-options)), unless the owner
+ wrote to them); then
`organization` (`organization_identities`, a role address, a legal form or company word in the name); then a named
`person` with a tie; a named one with no tie is a `stranger`;
one with nothing to show as a name is `unsorted`. Before any of these, `test` holds what a test run left
@@ -682,6 +684,13 @@ proposes them instead. A no-reply address (`isNoReplyAddress`) is no one's: it n
(`PRAGMA data_version`), else the list answers from memory. `KIND_RULES` in `people-list.ts`
is bumped when the rules change in code, which works out everyone again; a read-only open with anything to work out
answers from memory (cli-testing `performance/memo/people-list`).
+ Each row of a page also carries `reach` and `signals` (`sender-signals.ts`), worked out for that page only and
+ never stored: `broadcast` for mail with a one-click unsubscribe or a `Feedback-ID` its domain signed, in the bulk
+ box, or with no To or Cc; `group` for a List-Id that `DISCUSSION_SENDERS` (3) addresses send to, `+tag` aside, or
+ more than `SMALL_GROUP_MEMBERS` recipients; else `direct`. The owner missing from a To or Cc that names others says
+ nothing, since an alias the store does not know looks the same. The reach most of their mail had wins, the wider on a
+ tie; mail the owner wrote them or a private chat both wrote in makes it `direct`, and with no mail a one-to-one chat
+ or a small group does. `null` when nothing says. The page reads every stored email's List-Id once for this.
`people.similar` serves a form that adds a person: names starting like the typed words, the same `variantKey` first;
a `name:` search looks for the typed text in both scripts (`spellings`). Each row's `usernameSource` names the
messenger its `@username` belongs to.
diff --git a/docs/dev/MAIL.md b/docs/dev/MAIL.md
index 9b8d32808..2b794bccb 100644
--- a/docs/dev/MAIL.md
+++ b/docs/dev/MAIL.md
@@ -44,6 +44,16 @@ account `{ provider: "email", account:
}`.
(`store.mail.markOwnMail`), and the account is saved again, so `linkOwnIdentities` joins their identities to the
owner. Partial completion, `readEmailWhole` and a server search read the same list. A mail tie needs mail the owner
wrote, so this is what gives the people an alias writes to their tie. Nothing is taken from a name.
+- **Stored headers.** An email stored in full keeps some header fields as JSON in `emails.headers`
+ (`mailHeadersOf`, `src/mail/headers.ts`): `list-id`, `list-unsubscribe`, `precedence`, `reply-to`, Gmail's `spf`,
+ `dkim` and `dmarc`, and what marks a program or a list. Those last are `auto-submitted` (its value, unless `no` or
+ `auto-replied`, [RFC 3834](https://www.rfc-editor.org/rfc/rfc3834)), `list-unsubscribe-post` (one-click,
+ [RFC 8058](https://www.rfc-editor.org/rfc/rfc8058)) and `feedback-id`. The sender writes every header itself, so
+ they are kept only when a DKIM signature Gmail passed covers them and the signature's domain has the From's
+ registrable domain (`signedFieldsOf`). **Gap:** only Gmail's own `mx.google.com` stamp is read, so mail of an IMAP
+ server never keeps these three; another server's Authentication-Results may be the sender's own. An empty
+ Return-Path, which the receiving server writes, is kept as `null-return-path` unless the mail is an auto-reply: a
+ person's out-of-office comes that way too. Mail stored before these keys keeps none of them until read again.
- **Quick folders.** A folder whose `search` says `quick` is not listed with headers: the sync lists the UID, flags,
date and size of every message in the window, and reads the raw bytes of the newest `max` not done and not located
(a budgeted run: `fetchBatch` a round). It takes the id from the Message-ID, so stored mail keeps its id and the same
diff --git a/docs/storage/schema.md b/docs/storage/schema.md
index 474880fbd..f728269f2 100644
--- a/docs/storage/schema.md
+++ b/docs/storage/schema.md
@@ -732,7 +732,7 @@ One email.
| `flagged` | integer | | | 1 when it is flagged or starred |
| `draft` | integer | | | 1 for a draft not yet sent |
| `size` | integer | | | the raw email's size, in bytes |
-| `headers` | text | | | JSON: every header, as received |
+| `headers` | text | | | JSON: the header fields `mailHeadersOf` keeps (docs/dev/MAIL.md) |
| `metadata` | text | | | JSON: what the source sends that has no column, and is not searched |
| `created_at` | integer | not null | | when this row was saved here |
| `updated_at` | integer | not null | | when this row last changed here |
diff --git a/scripts/schema/spec.mjs b/scripts/schema/spec.mjs
index b953a4f22..4cf5c211c 100644
--- a/scripts/schema/spec.mjs
+++ b/scripts/schema/spec.mjs
@@ -658,7 +658,7 @@ const NEW = {
c("flagged", "integer"),
c("draft", "integer"),
c("size", "integer"),
- c("headers", "text", { note: "JSON: every header, as received" }),
+ c("headers", "text", { note: "JSON: the header fields `mailHeadersOf` keeps (docs/dev/MAIL.md)" }),
meta(),
...ts(),
del(),
diff --git a/src/domain/person-kinds.ts b/src/domain/person-kinds.ts
index 3db3f5c44..8d863a0ac 100644
--- a/src/domain/person-kinds.ts
+++ b/src/domain/person-kinds.ts
@@ -11,6 +11,8 @@ export type KindSignal =
| "bot"
| "no-reply"
| "notification-address"
+ | "auto-submitted"
+ | "null-return-path"
| "bulk-mail"
| "bulk-never-replied"
| "automated-name"
diff --git a/src/mail/headers.test.ts b/src/mail/headers.test.ts
new file mode 100644
index 000000000..bc4d1bcc9
--- /dev/null
+++ b/src/mail/headers.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from "vitest"
+import { mailHeadersOf, signedFieldsOf, unfold } from "./headers.js"
+
+const head = (lines: string[]) => unfold(`${lines.join("\r\n")}\r\n`)
+const raw = (lines: string[]) => new TextEncoder().encode(`${lines.join("\r\n")}\r\n\r\nBody`)
+
+const SIGNATURE = "DKIM-Signature: v=1; d=news.shop.example; s=s1;\r\n h=From:Subject:Auto-Submitted:Feedback-ID; b=x"
+
+describe("signedFieldsOf", () => {
+ it("names the fields a passing signature of the From's own domain covers", () => {
+ const stamp = "Authentication-Results: mx.google.com; dkim=pass header.i=@news.shop.example header.s=s1"
+ expect([...signedFieldsOf(head([SIGNATURE, stamp]), "deals@shop.example")]).toEqual([
+ "from",
+ "subject",
+ "auto-submitted",
+ "feedback-id",
+ ])
+ })
+
+ it("reads a signer named with a local part", () => {
+ const stamp = "Authentication-Results: mx.google.com; dkim=pass header.i=bot@news.shop.example"
+ expect(signedFieldsOf(head([SIGNATURE, stamp]), "deals@shop.example").has("auto-submitted")).toBe(true)
+ })
+
+ it("trusts nothing from another domain's signature, a failed one or a stamp not Gmail's", () => {
+ const pass = "Authentication-Results: mx.google.com; dkim=pass header.i=@news.shop.example"
+ expect(signedFieldsOf(head([SIGNATURE, pass]), "deals@other.example").size).toBe(0)
+ const failed = "Authentication-Results: mx.google.com; dkim=fail header.i=@news.shop.example"
+ expect(signedFieldsOf(head([SIGNATURE, failed]), "deals@shop.example").size).toBe(0)
+ const foreign = "Authentication-Results: relay.shop.example; dkim=pass header.i=@news.shop.example"
+ expect(signedFieldsOf(head([SIGNATURE, foreign]), "deals@shop.example").size).toBe(0)
+ })
+})
+
+describe("mailHeadersOf", () => {
+ it("keeps Auto-Submitted, one-click unsubscribe and Feedback-ID only when signed, and an empty Return-Path", () => {
+ const fields = [
+ "From: Deals ",
+ "Return-Path: <>",
+ "Auto-Submitted: auto-generated",
+ "Feedback-ID: 1:2:shop",
+ "List-Unsubscribe-Post: List-Unsubscribe=One-Click",
+ SIGNATURE,
+ "Authentication-Results: mx.google.com; dkim=pass header.i=@news.shop.example",
+ ]
+ expect(mailHeadersOf(raw(fields))).toEqual({
+ dkim: "pass",
+ "auto-submitted": "auto-generated",
+ "feedback-id": true,
+ "null-return-path": true,
+ })
+ })
+
+ it("takes an auto-reply's empty Return-Path for no program", () => {
+ expect(mailHeadersOf(raw(["From: pia@office.example", "Return-Path: <>", "Auto-Submitted: auto-replied"]))).toEqual(
+ {},
+ )
+ })
+})
diff --git a/src/mail/headers.ts b/src/mail/headers.ts
index 9d1fa3453..11152e2a6 100644
--- a/src/mail/headers.ts
+++ b/src/mail/headers.ts
@@ -1,4 +1,5 @@
import { decodeWords } from "postal-mime"
+import { registrableOf } from "./score.js"
/**
* The header fields memo reads at list time: enough to group mail by sender, apply the owner's rules and keep
@@ -41,11 +42,15 @@ const fieldsOf = (unfolded: string, name: string): string[] =>
[...unfolded.matchAll(new RegExp(`^${name}:[ \\t]*(.*?)\\r?$`, "gim"))].map(([, value]) => value as string)
/**
- * The verdicts in Gmail's own Authentication-Results. Only the copy Gmail stamps as mx.google.com counts: a sender
- * can add one under any other name, and Gmail removes forged copies under its own (RFC 8601 §5).
+ * Gmail's own Authentication-Results. Only the copy Gmail stamps as mx.google.com counts: a sender can add one under
+ * any other name, and Gmail removes forged copies under its own (RFC 8601 §5).
*/
+const gmailStampOf = (unfolded: string): string | undefined =>
+ fieldsOf(unfolded, "Authentication-Results").find((value) => /^mx\.google\.com\s*;/i.test(value))
+
+/** The verdicts in Gmail's own Authentication-Results. */
export const authOf = (unfolded: string): AuthVerdicts | undefined => {
- const stamped = fieldsOf(unfolded, "Authentication-Results").find((value) => /^mx\.google\.com\s*;/i.test(value))
+ const stamped = gmailStampOf(unfolded)
if (stamped === undefined) return undefined
const results = [...stamped.matchAll(/\b(spf|dkim|dmarc)=([a-z]+)/gi)].map(([, method, result]) => [
(method as string).toLowerCase(),
@@ -60,6 +65,61 @@ export const authOf = (unfolded: string): AuthVerdicts | undefined => {
return Object.keys(verdicts).length ? verdicts : undefined
}
+const tagsOf = (value: string): Map =>
+ new Map(
+ value.split(";").flatMap((tag) => {
+ const at = tag.indexOf("=")
+ return at === -1 ? [] : [[tag.slice(0, at).trim().toLowerCase(), tag.slice(at + 1).replace(/\s+/g, "")]]
+ }),
+ )
+
+/**
+ * The header fields a DKIM signature Gmail passed covers, when that signature's domain is the From's own (its
+ * registrable domain). A sender writes every header itself; only a signature of its own domain vouches for one.
+ * Without Gmail's stamp nothing is trusted: other servers' Authentication-Results may be the sender's own.
+ */
+export const signedFieldsOf = (unfolded: string, from: string | undefined): Set => {
+ const stamped = gmailStampOf(unfolded)
+ if (stamped === undefined || from === undefined) return new Set()
+ const passed = [...stamped.matchAll(/\bdkim=pass\b[^;]*?\bheader\.[id]=([^\s;]+)/gi)].map(([, identity]) =>
+ (identity as string).slice((identity as string).lastIndexOf("@") + 1).toLowerCase(),
+ )
+ const own = registrableOf(from)
+ const signed = new Set()
+ for (const signature of fieldsOf(unfolded, "DKIM-Signature")) {
+ const tags = tagsOf(signature)
+ const domain = tags.get("d")?.toLowerCase()
+ if (domain === undefined || registrableOf(domain) !== own) continue
+ if (!passed.some((one) => one === domain || one.endsWith(`.${domain}`))) continue
+ for (const name of (tags.get("h") ?? "").split(":")) if (name !== "") signed.add(name.toLowerCase())
+ }
+ return signed
+}
+
+/**
+ * What says a program or a list sent the mail, each only when DKIM vouches for it (`signedFieldsOf`):
+ * `Auto-Submitted` other than `no` (RFC 3834), the one-click unsubscribe of RFC 8058 and Google's `Feedback-ID`.
+ * An empty Return-Path is the receiving server's, not the sender's, and marks a program unless it is an auto-reply,
+ * which RFC 3834 sends that way too: a person's out-of-office makes no bot.
+ */
+const programSignalsOf = (unfolded: string, from: string | undefined): Record => {
+ const signed = signedFieldsOf(unfolded, from)
+ const submitted = field(unfolded, "Auto-Submitted")
+ ?.trim()
+ .toLowerCase()
+ .split(/[\s;(]/)[0]
+ const generated = submitted !== undefined && submitted !== "" && submitted !== "no" && submitted !== "auto-replied"
+ const oneClick = /list-unsubscribe\s*=\s*one-click/i.test(field(unfolded, "List-Unsubscribe-Post") ?? "")
+ return {
+ ...(generated && signed.has("auto-submitted") ? { "auto-submitted": submitted } : {}),
+ ...(oneClick && signed.has("list-unsubscribe-post") ? { "list-unsubscribe-post": true } : {}),
+ ...(field(unfolded, "Feedback-ID") !== undefined && signed.has("feedback-id") ? { "feedback-id": true } : {}),
+ ...(/^\s*<\s*>/.test(field(unfolded, "Return-Path") ?? "") && submitted !== "auto-replied"
+ ? { "null-return-path": true }
+ : {}),
+ }
+}
+
export const addressesOf = (value: string | undefined): string[] => {
if (value === undefined) return []
// A display name may itself look like an address ("bob@y.com" ), so quoted names and comments go first.
@@ -115,19 +175,22 @@ const headTextOf = (raw: Uint8Array): string => {
export const headersOfRaw = (raw: Uint8Array): MailHeaders => headersOf(headTextOf(raw))
/**
- * List-Id, the bulk-mail fields, Reply-To and Gmail's SPF, DKIM and DMARC verdicts of a whole email, kept on mail
- * stored in full so a rule or a sender score can be worked out from the store later. Names are lower case.
+ * List-Id, the bulk-mail fields, Reply-To, Gmail's SPF, DKIM and DMARC verdicts and what marks a program or a list
+ * (`programSignalsOf`) of a whole email, kept on mail stored in full so a rule, a sender score or a person's kind can
+ * be worked out from the store later. Names are lower case.
*/
export const mailHeadersOf = (raw: Uint8Array): Record => {
const unfolded = unfold(headTextOf(raw))
const listId = listIdOf(field(unfolded, "List-Id"))
const precedence = field(unfolded, "Precedence")?.trim().toLowerCase()
const [replyTo] = addressesOf(field(unfolded, "Reply-To"))
+ const [from] = addressesOf(field(unfolded, "From"))
return {
...(listId ? { "list-id": listId } : {}),
...(replyTo === undefined ? {} : { "reply-to": replyTo }),
...authOf(unfolded),
...(field(unfolded, "List-Unsubscribe") === undefined ? {} : { "list-unsubscribe": true }),
...(precedence ? { precedence } : {}),
+ ...programSignalsOf(unfolded, from),
}
}
diff --git a/src/mail/sender-signals.test.ts b/src/mail/sender-signals.test.ts
new file mode 100644
index 000000000..b839561d3
--- /dev/null
+++ b/src/mail/sender-signals.test.ts
@@ -0,0 +1,120 @@
+import { mkdtempSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { afterEach, describe, expect, it } from "vitest"
+import { type MessageStore, openStore } from "../store/index.js"
+import { syncMail } from "./sync.js"
+import { type FakeMail, fakeMailSource } from "./testing/index.js"
+
+// Subdomains of example.com are reserved but are not test data to the store, so these senders get a real kind.
+const ME = "owner@home.example.com"
+const NOW = Date.parse("2026-10-04T12:00:00Z")
+const SINCE = new Date("2026-09-01T00:00:00Z")
+
+let n = 0
+const mail = (from: [string, string], overrides: Partial = {}): FakeMail => {
+ n += 1
+ return {
+ uid: String(100 + n),
+ messageId: String(9000 + n),
+ threadId: String(9000 + n),
+ receivedAt: `2026-09-${String(10 + (n % 15)).padStart(2, "0")}T08:00:00Z`,
+ subject: `Synthetic subject ${n}`,
+ from,
+ to: [[null, ME]],
+ text: `Synthetic body ${n}`,
+ ...overrides,
+ }
+}
+
+/** Gmail's stamp for a passing signature of `domain` that covers `fields`. */
+const signed = (domain: string, fields: string[]) => [
+ `DKIM-Signature: v=1; a=rsa-sha256; d=${domain}; s=s1; h=from:to:subject:${fields.join(":")}; b=abc`,
+ `Authentication-Results: mx.google.com; dkim=pass header.i=@${domain} header.s=s1 header.b=abc`,
+]
+
+const opened: MessageStore[] = []
+afterEach(async () => {
+ for (const each of opened.splice(0)) await each.close()
+})
+
+const synced = async (messages: FakeMail[]) => {
+ const env = { ...process.env, MESSAGING_STORE: join(mkdtempSync(join(tmpdir(), "sender-signals-")), "store.db") }
+ const store = await openStore({ env })
+ opened.push(store)
+ await syncMail(fakeMailSource({ messages }), store, { account: { address: ME }, since: SINCE, now: () => NOW })
+ const { items } = await store.people.list({ kind: "all", limit: 100 })
+ return Object.fromEntries(
+ items
+ .filter(({ owner }) => !owner)
+ .map(({ email, kind, kindSignals, reach, signals }) => [email, { kind, kindSignals, reach, signals }]),
+ )
+}
+
+describe("a sender's signals from mail headers", () => {
+ it("calls a sender automated by an Auto-Submitted or an empty Return-Path its own domain vouches for", async () => {
+ const people = await synced([
+ mail(["Bank Statements", "statements@bank.example.com"], {
+ extraHeaders: ["Auto-Submitted: auto-generated", ...signed("mail.bank.example.com", ["auto-submitted"])],
+ }),
+ mail(["Ola Brandt", "ola@forged.example.com"], {
+ extraHeaders: ["Auto-Submitted: auto-generated", ...signed("relay.example.org", ["auto-submitted"])],
+ }),
+ mail(["Hosting", "system@hosting.example.com"], { extraHeaders: ["Return-Path: <>"] }),
+ mail(["Pia Lund", "pia@office.example.com"], {
+ extraHeaders: [
+ "Return-Path: <>",
+ "Auto-Submitted: auto-replied",
+ ...signed("office.example.com", ["auto-submitted"]),
+ ],
+ }),
+ ])
+
+ expect(people["statements@bank.example.com"]).toMatchObject({
+ kind: "automated",
+ kindSignals: ["auto-submitted"],
+ signals: ["auto-submitted"],
+ reach: "direct",
+ })
+ expect(people["ola@forged.example.com"]).toMatchObject({ kind: "stranger", signals: [] })
+ expect(people["system@hosting.example.com"]).toMatchObject({ kind: "automated", kindSignals: ["null-return-path"] })
+ expect(people["pia@office.example.com"]).toMatchObject({ kind: "stranger", signals: [] })
+ })
+
+ it("tells a newsletter, a discussion list, a large group and undisclosed recipients from mail written to the owner", async () => {
+ const list = "talk.lists.example.com"
+ const crowd = Array.from({ length: 11 }, (_, at): [null, string] => [null, `guest${at}@crowd.example.com`])
+ const people = await synced([
+ mail(["Weekly News", "news@letters.example.com"], {
+ extraHeaders: [
+ "List-Unsubscribe: ",
+ "List-Unsubscribe-Post: List-Unsubscribe=One-Click",
+ ...signed("letters.example.com", ["list-unsubscribe", "list-unsubscribe-post"]),
+ ],
+ }),
+ mail(["Ann Ode", "ann@one.example.com"], { listId: list }),
+ mail(["Ben Ode", "ben@two.example.com"], { listId: list }),
+ mail(["Cyd Ode", "cyd@three.example.com"], { listId: list }),
+ mail(["Dag Moe", "dag@crowd.example.com"], { to: crowd }),
+ mail(["Eli Moe", "eli@quiet.example.com"], { to: [] }),
+ mail(["Fay Moe", "fay@direct.example.com"]),
+ ])
+
+ expect(people["news@letters.example.com"]).toMatchObject({ reach: "broadcast", signals: ["one-click-unsubscribe"] })
+ expect(people["ann@one.example.com"]).toMatchObject({ reach: "group", signals: ["discussion-list"] })
+ expect(people["dag@crowd.example.com"]).toMatchObject({ reach: "group", signals: ["many-recipients"] })
+ expect(people["eli@quiet.example.com"]).toMatchObject({ reach: "broadcast", signals: ["undisclosed-recipients"] })
+ expect(people["fay@direct.example.com"]).toMatchObject({ kind: "stranger", reach: "direct", signals: [] })
+ })
+
+ it("keeps a sender the owner wrote to a person, and direct, whatever their headers say", async () => {
+ const people = await synced([
+ mail(["Gus Holm", "gus@firm.example.com"], {
+ extraHeaders: ["Auto-Submitted: auto-generated", ...signed("firm.example.com", ["auto-submitted"])],
+ }),
+ mail(["Owner", ME], { to: [["Gus Holm", "gus@firm.example.com"]], labels: ["Sent"] }),
+ ])
+
+ expect(people["gus@firm.example.com"]).toMatchObject({ kind: "person", reach: "direct" })
+ })
+})
diff --git a/src/store/index.ts b/src/store/index.ts
index f74aeb1c9..0bff585bf 100644
--- a/src/store/index.ts
+++ b/src/store/index.ts
@@ -503,6 +503,7 @@ export {
type SearchIndexState,
searchIndexState,
} from "./sqlite/search-index.js"
+export { REACHES, type Reach, type SenderSignal } from "./sqlite/sender-signals.js"
export type { ChallengeInput, SourceReviewDecision } from "./sqlite/source-review.js"
export type {
PriceFilter,
diff --git a/src/store/sqlite/people-list.ts b/src/store/sqlite/people-list.ts
index 147a9dfd4..3b04a2e0a 100644
--- a/src/store/sqlite/people-list.ts
+++ b/src/store/sqlite/people-list.ts
@@ -18,6 +18,7 @@ import { type CacheDatabase, isQueryOnly, type SqlValue } from "../driver.js"
import { fold } from "../normalize.js"
import { mergedAwaySql } from "./merged-persons.js"
import { ALWAYS_SHOWN, type ShownBecause, shownReasons } from "./person-ties.js"
+import { type Reach, type SenderSignal, senderSignalsOf, sentMailOf } from "./sender-signals.js"
import { mergedAssignees } from "./task-board.js"
import { hiddenTestPeople } from "./test-people.js"
import { read, writeBatch } from "./transaction.js"
@@ -63,6 +64,10 @@ export interface ListedPerson {
lastContact: string | null
/** Why they are shown; empty for someone hidden by default. */
ties: ShownBecause[]
+ /** How their messages reached the owner (`senderSignalsOf`); `null` when nothing says. Worked out for the page. */
+ reach: Reach | null
+ /** What their mail and addresses show about who writes and how it reached the owner. Worked out for the page. */
+ signals: SenderSignal[]
}
export interface PeopleList {
@@ -138,7 +143,9 @@ const TWO_WAY =
const MAIL_COUNTS = (scope: Scope) =>
"SELECT l.person_id AS person, count(*) AS n, sum(EXISTS (SELECT 1 FROM email_mailboxes m " +
- "JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk')) AS bulk " +
+ "JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk')) AS bulk, " +
+ "sum(json_extract(e.headers, '$.\"auto-submitted\"') IS NOT NULL) AS auto, " +
+ "sum(json_extract(e.headers, '$.\"null-return-path\"') IS 1) AS null_return " +
"FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
`WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND ${IN_SCOPE(scope, "l.person_id")} GROUP BY 1`
@@ -282,10 +289,20 @@ interface Candidate {
owner: boolean
}
-interface Classified extends Omit {
+interface Classified extends Omit {
id: number
/** Worked out once: a collator over 50,000 names takes most of a list's time. */
nameOrder: string
+ emails: string[]
+ twoWay: boolean
+}
+
+interface MailCounts {
+ n: number
+ bulk: number
+ /** Mail with an `Auto-Submitted` its own domain signed, and mail with an empty Return-Path (`mailHeadersOf`). */
+ auto: number
+ nullReturn: number
}
/** One misfiled letter is no newsletter. */
@@ -296,7 +313,7 @@ const kindOf = (
shown: string | null,
facts: Facts | undefined,
ties: ShownBecause[],
- mail: { n: number; bulk: number } | undefined,
+ mail: MailCounts | undefined,
test: boolean,
): { kind: PersonKind; signals: (ShownBecause | KindSignal)[] } => {
if (test) return { kind: "test", signals: ["test-data"] }
@@ -310,6 +327,11 @@ const kindOf = (
...(mail !== undefined && mail.n >= BULK_MIN && mail.bulk * 2 > mail.n ? (["bulk-mail"] as const) : []),
...(facts?.neverReplied ? (["bulk-never-replied"] as const) : []),
...(isAutomatedName(shown) ? (["automated-name"] as const) : []),
+ // A guess from headers never outweighs mail the owner wrote them.
+ ...(mail !== undefined && !ties.includes("mail") && mail.auto * 2 > mail.n ? (["auto-submitted"] as const) : []),
+ ...(mail !== undefined && !ties.includes("mail") && mail.nullReturn * 2 > mail.n
+ ? (["null-return-path"] as const)
+ : []),
]
// One mailbox's newsletter signal must not hide someone the owner talks to in a private chat.
if (automated.length > 0 && (facts?.bot || !facts?.twoWay)) return { kind: "automated", signals: automated }
@@ -340,7 +362,10 @@ const classified = (
database
.prepare(MAIL_COUNTS(scope))
.all(...scopeParams(scope))
- .map((row) => [Number(row.person), { n: Number(row.n), bulk: Number(row.bulk) }]),
+ .map((row) => [
+ Number(row.person),
+ { n: Number(row.n), bulk: Number(row.bulk), auto: Number(row.auto), nullReturn: Number(row.null_return) },
+ ]),
)
return people.map(({ id, name, owner }) => {
const own = facts.get(id)
@@ -364,6 +389,8 @@ const classified = (
usernameSource: own?.usernameSource ?? null,
messagesFrom: (own?.messages ?? 0) + (mail.get(id)?.n ?? 0),
ties,
+ emails: own?.emails ?? [],
+ twoWay: own?.twoWay ?? false,
}
})
}
@@ -379,9 +406,22 @@ const withLastContact = (
database,
people.map(({ id }) => id),
)
- return people.map(({ id, nameOrder: _, ...person }) => {
+ const sent = sentMailOf(
+ database,
+ people.map(({ id }) => id),
+ )
+ return people.map(({ id, nameOrder: _, emails, twoWay, ...person }) => {
const time = at.get(id)
- return { ...person, lastContact: time === undefined ? null : new Date(time).toISOString() }
+ const { ties } = person
+ return {
+ ...person,
+ lastContact: time === undefined ? null : new Date(time).toISOString(),
+ ...senderSignalsOf(sent.get(id) ?? [], {
+ addresses: emails,
+ ownerWrote: twoWay || ties.includes("mail"),
+ chatted: ties.includes("chat") || ties.includes("small-group"),
+ }),
+ }
})
}
@@ -395,7 +435,7 @@ const byName = (a: Classified, b: Classified) =>
* Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
* every stored one is worked out again on the next list.
*/
-const KIND_RULES = "5"
+const KIND_RULES = "6"
const RULES_KEY = "people.kind_rules"
/** Past this many people to work out, one pass over everyone beats a lookup per person. */
const WHOLE_PASS = 20_000
diff --git a/src/store/sqlite/sender-signals.test.ts b/src/store/sqlite/sender-signals.test.ts
new file mode 100644
index 000000000..1ad0e7682
--- /dev/null
+++ b/src/store/sqlite/sender-signals.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest"
+import { type SentMail, senderSignalsOf } from "./sender-signals.js"
+
+const one = (more: Partial = {}): SentMail => ({
+ autoSubmitted: false,
+ nullReturnPath: false,
+ oneClick: false,
+ feedbackId: false,
+ bulk: false,
+ discussionList: false,
+ recipients: 1,
+ ...more,
+})
+const alone = { addresses: [], ownerWrote: false, chatted: false }
+
+describe("senderSignalsOf", () => {
+ it("takes the reach most of their mail had, the wider on a tie", () => {
+ expect(senderSignalsOf([one(), one(), one({ bulk: true })], alone).reach).toBe("direct")
+ expect(senderSignalsOf([one(), one({ bulk: true })], alone)).toEqual({ signals: ["bulk-mail"], reach: "broadcast" })
+ })
+
+ it("is direct when the owner wrote to them or, with no mail, chats with them; else says nothing", () => {
+ expect(senderSignalsOf([one({ feedbackId: true })], { ...alone, ownerWrote: true }).reach).toBe("direct")
+ expect(senderSignalsOf([], { ...alone, chatted: true }).reach).toBe("direct")
+ expect(senderSignalsOf([], alone).reach).toBeNull()
+ })
+
+ it("names a program only when most of their mail says so, and no recipients from an envelope", () => {
+ expect(senderSignalsOf([one({ autoSubmitted: true }), one()], alone).signals).toEqual([])
+ expect(senderSignalsOf([one({ recipients: null })], { ...alone, addresses: ["no-reply@x.example"] })).toEqual({
+ signals: ["no-reply"],
+ reach: "direct",
+ })
+ })
+})
diff --git a/src/store/sqlite/sender-signals.ts b/src/store/sqlite/sender-signals.ts
new file mode 100644
index 000000000..87ad4f236
--- /dev/null
+++ b/src/store/sqlite/sender-signals.ts
@@ -0,0 +1,140 @@
+import { isNoReplyAddress } from "../../domain/addresses.js"
+import type { CacheDatabase } from "../driver.js"
+import { SMALL_GROUP_MEMBERS } from "./person-ties.js"
+
+/**
+ * How a sender's messages reached the owner: written to them or a few people, in a large group or a discussion list,
+ * or sent to many readers who cannot answer in place.
+ */
+export const REACHES = ["direct", "group", "broadcast"] as const
+export type Reach = (typeof REACHES)[number]
+
+/** What the mail of one sender shows about who writes and how it reached the owner. */
+export type SenderSignal =
+ | "auto-submitted"
+ | "null-return-path"
+ | "no-reply"
+ | "one-click-unsubscribe"
+ | "feedback-id"
+ | "bulk-mail"
+ | "discussion-list"
+ | "many-recipients"
+ | "undisclosed-recipients"
+
+/** One email a sender sent the owner, as the store keeps it (`mailHeadersOf`, the mailboxes, the recipients). */
+export interface SentMail {
+ autoSubmitted: boolean
+ nullReturnPath: boolean
+ oneClick: boolean
+ feedbackId: boolean
+ /** In the bulk box: List-Id, List-Unsubscribe or `Precedence: bulk`. */
+ bulk: boolean
+ /** A List-Id at least `DISCUSSION_SENDERS` addresses send to. */
+ discussionList: boolean
+ /** To and Cc together; `null` when the store holds no recipients for it (mail recorded as an envelope). */
+ recipients: number | null
+}
+
+/** A list three people write to is a discussion; one sender, even under `+tag` addresses, is a newsletter. */
+export const DISCUSSION_SENDERS = 3
+
+const reachOfOne = (mail: SentMail): { reach: Reach; signal?: SenderSignal } => {
+ if (mail.discussionList) return { reach: "group", signal: "discussion-list" }
+ if (mail.oneClick) return { reach: "broadcast", signal: "one-click-unsubscribe" }
+ if (mail.feedbackId) return { reach: "broadcast", signal: "feedback-id" }
+ if (mail.bulk) return { reach: "broadcast", signal: "bulk-mail" }
+ // The owner missing from a To or Cc that names others proves nothing: an alias the store does not know looks so.
+ if (mail.recipients === 0) return { reach: "broadcast", signal: "undisclosed-recipients" }
+ if (mail.recipients !== null && mail.recipients > SMALL_GROUP_MEMBERS)
+ return { reach: "group", signal: "many-recipients" }
+ return { reach: "direct" }
+}
+
+/** More than half of their mail: one misfiled letter decides nothing. */
+const most = (mail: readonly SentMail[], holds: (one: SentMail) => boolean) =>
+ mail.filter(holds).length * 2 > mail.length
+
+/**
+ * A sender's signals and reach, worked out from their mail alone. Reach is the one most of their mail reached the
+ * owner by, the wider on a tie. Mail the owner wrote them, or a private chat both wrote in, makes it `direct`
+ * whatever their other mail shows; with no mail, a one-to-one chat or a small group does. `null`: nothing says.
+ */
+export const senderSignalsOf = (
+ mail: readonly SentMail[],
+ { addresses, ownerWrote, chatted }: { addresses: readonly string[]; ownerWrote: boolean; chatted: boolean },
+): { signals: SenderSignal[]; reach: Reach | null } => {
+ const signals = new Set()
+ if (mail.length > 0 && most(mail, (one) => one.autoSubmitted)) signals.add("auto-submitted")
+ if (mail.length > 0 && most(mail, (one) => one.nullReturnPath)) signals.add("null-return-path")
+ if (addresses.some(isNoReplyAddress)) signals.add("no-reply")
+ const votes = new Map()
+ for (const one of mail) {
+ const { reach, signal } = reachOfOne(one)
+ votes.set(reach, (votes.get(reach) ?? 0) + 1)
+ if (signal !== undefined) signals.add(signal)
+ }
+ const voted = [...REACHES].reverse().reduce((best, reach) => {
+ const n = votes.get(reach) ?? 0
+ return n > 0 && (best === null || n > (votes.get(best) ?? 0)) ? reach : best
+ }, null)
+ const reach = ownerWrote ? "direct" : (voted ?? (chatted ? "direct" : null))
+ return { signals: [...signals], reach }
+}
+
+const LIST_ID = "coalesce(json_extract(e.headers, '$.\"list-id\"'), json_extract(e.metadata, '$.listId'))"
+
+/** `bob+news@x` and `bob@x` are one sender. */
+const senderKey = (address: string) => address.toLowerCase().replace(/\+[^@]*@/, "@")
+
+/**
+ * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: it
+ * reads every stored email's List-Id once to tell a discussion list from a newsletter.
+ */
+export const sentMailOf = (database: CacheDatabase, people: readonly number[]): Map => {
+ const found = new Map()
+ if (people.length === 0) return found
+ const rows = database
+ .prepare(
+ "SELECT l.person_id AS person, " +
+ `${LIST_ID} AS list, json_extract(e.headers, '$."auto-submitted"') IS NOT NULL AS auto, ` +
+ "json_extract(e.headers, '$.\"null-return-path\"') IS 1 AS null_return, " +
+ "json_extract(e.headers, '$.\"list-unsubscribe-post\"') IS 1 AS one_click, " +
+ "json_extract(e.headers, '$.\"feedback-id\"') IS 1 AS feedback, " +
+ "EXISTS (SELECT 1 FROM email_mailboxes m JOIN mailboxes b ON b.id = m.mailbox_id " +
+ "WHERE m.email_id = e.id AND b.kind = 'bulk') AS bulk, " +
+ "CASE WHEN json_extract(e.metadata, '$.rule') IS NOT NULL THEN NULL ELSE " +
+ "(SELECT count(*) FROM email_recipients r WHERE r.email_id = e.id AND r.role IN ('to', 'cc')) END AS recipients " +
+ "FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
+ "WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND l.person_id IN (SELECT value FROM json_each(?))",
+ )
+ .all(JSON.stringify(people))
+ const lists = [...new Set(rows.flatMap((row) => (typeof row.list === "string" ? [row.list] : [])))]
+ const senders = new Map>()
+ if (lists.length > 0)
+ for (const row of database
+ .prepare(
+ `SELECT DISTINCT ${LIST_ID} AS list, e.from_address AS address FROM emails e ` +
+ `WHERE e.from_address IS NOT NULL AND ${LIST_ID} IN (SELECT value FROM json_each(?))`,
+ )
+ .all(JSON.stringify(lists))) {
+ const list = String(row.list)
+ const held = senders.get(list) ?? new Set()
+ held.add(senderKey(String(row.address)))
+ senders.set(list, held)
+ }
+ for (const row of rows) {
+ const person = Number(row.person)
+ const held = found.get(person) ?? []
+ held.push({
+ autoSubmitted: Number(row.auto) === 1,
+ nullReturnPath: Number(row.null_return) === 1,
+ oneClick: Number(row.one_click) === 1,
+ feedbackId: Number(row.feedback) === 1,
+ bulk: Number(row.bulk) === 1,
+ discussionList: typeof row.list === "string" && (senders.get(row.list)?.size ?? 0) >= DISCUSSION_SENDERS,
+ recipients: row.recipients == null ? null : Number(row.recipients),
+ })
+ found.set(person, held)
+ }
+ return found
+}