From 8da55751dc58b703a2148cd10bd952b37374b2b6 Mon Sep 17 00:00:00 2001 From: leemour Date: Wed, 25 Nov 2026 23:39:20 +0100 Subject: [PATCH 1/3] feat(people): a sender of a newsletter only is a bot, a human author too Owner's ruling of 2026-11-25 (contact-kinds plan, PR #3323): a person whose mail all came from a list (List-Id, List-Unsubscribe, one-click unsubscribe, Feedback-ID, bulk Precedence or the bulk box), with no tie to the owner, no messenger identity and no discussion-list mail, moves to a sender bot with the reason `newsletter-only` on the next people list. - kindOf names the new `newsletter-only` kind signal; KIND_RULES 10 works every kind out again once. - ruleBotsBack also gives a newsletter-only rule bot back once a 1-to-1 mail (no list headers, at most SMALL_GROUP_MEMBERS in To and Cc) comes from it, besides the owner writing to it. - Mail types do not treat a newsletter-only bot as a program, so its mail stays `newsletter` rather than `promotion`. - The owner's moveToPerson/moveToBot (and the sorting rules through them) still win. Co-Authored-By: Claude Opus 5.5 --- changes/feat-newsletter-bots.md | 11 +++ src/domain/person-kinds.ts | 1 + src/store/newsletter-bots.test.ts | 147 ++++++++++++++++++++++++++++++ src/store/people-list.test.ts | 18 ++-- src/store/sqlite/email-types.ts | 4 +- src/store/sqlite/people-list.ts | 92 ++++++++++++++++--- src/store/sqlite/sender-bots.ts | 32 +++++-- 7 files changed, 275 insertions(+), 30 deletions(-) create mode 100644 changes/feat-newsletter-bots.md create mode 100644 src/store/newsletter-bots.test.ts diff --git a/changes/feat-newsletter-bots.md b/changes/feat-newsletter-bots.md new file mode 100644 index 000000000..5ddb2e053 --- /dev/null +++ b/changes/feat-newsletter-bots.md @@ -0,0 +1,11 @@ +### Changed + +- **A sender of a newsletter only is a bot, a human author too.** The owner's ruling of 25.11.2026, in place of the + earlier one that kept a human-written newsletter a person. A person all of whose mail came from a list (List-Id, + List-Unsubscribe, a one-click unsubscribe, a Feedback-ID, bulk `Precedence` or the bulk box), with no tie to the + owner, no messenger identity and no discussion list among their mail, moves to a bot with the reason + `newsletter-only` on the next people list; `kindSignals` names `newsletter-only`. Its mail stays typed `newsletter`: + a newsletter's bot is not a program for the mail types. A rule's newsletter bot goes back to a person once the owner + writes to it, as before, and also once a mail written to the owner alone (no list headers, at most a small group in + To and Cc) comes from it; the newsletter's own mail keeps reach `broadcast`. The owner's `moveToPerson` and + `moveToBot` and the sorting rules still win. The people list works out every kind again once after the upgrade. diff --git a/src/domain/person-kinds.ts b/src/domain/person-kinds.ts index d3f5c13ea..8e0d26e3c 100644 --- a/src/domain/person-kinds.ts +++ b/src/domain/person-kinds.ts @@ -17,6 +17,7 @@ export type KindSignal = | "null-return-path" | "bulk-mail" | "bulk-never-replied" + | "newsletter-only" | "automated-name" | "organization" | "role-address" diff --git a/src/store/newsletter-bots.test.ts b/src/store/newsletter-bots.test.ts new file mode 100644 index 000000000..bff157163 --- /dev/null +++ b/src/store/newsletter-bots.test.ts @@ -0,0 +1,147 @@ +import { mkdtempSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { afterEach, expect, it } from "vitest" +import { syncMail } from "../mail/sync.js" +import { type FakeMail, type FakeMailbox, fakeMailSource } from "../mail/testing/index.js" +import { openCache } from "./open.js" +import { type MessageStore, openStore } from "./store.js" + +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], subject: string, overrides: Partial = {}): FakeMail => { + n += 1 + return { + uid: String(100 + n), + messageId: ``, + threadId: String(9000 + n), + receivedAt: `2026-09-${String(10 + (n % 15)).padStart(2, "0")}T08:00:00Z`, + subject, + from, + to: [[null, ME]], + text: `Synthetic body ${n}`, + ...overrides, + } +} + +const AUTHOR: [string, string] = ["Ada Quill", "ada@quill.substack.example.com"] + +const issue = (subject: string) => + mail(AUTHOR, subject, { + extraHeaders: [ + "List-Unsubscribe: ", + "List-Unsubscribe-Post: List-Unsubscribe=One-Click", + "DKIM-Signature: v=1; a=rsa-sha256; d=quill.substack.example.com; s=s1; h=from:to:subject:list-unsubscribe-post; b=abc", + "Authentication-Results: mx.example.com; dkim=pass header.i=@quill.substack.example.com header.s=s1 header.b=abc", + ], + listId: "", + }) + +const handles: { close(): unknown }[] = [] +afterEach(async () => { + for (const handle of handles.splice(0)) await handle.close() +}) + +const opened = async (messages: FakeMail[]) => { + const path = join(mkdtempSync(join(tmpdir(), "newsletter-bots-")), "store.db") + const store = await openStore({ path }) + handles.push(store) + const mailbox: FakeMailbox = { messages } + const sync = () => + syncMail(fakeMailSource(mailbox), store, { account: { address: ME }, since: SINCE, now: () => NOW }) + await sync() + const db = await openCache(path) + handles.push(db) + return { store, db, mailbox, sync } +} + +const sorted = async (store: MessageStore) => { + await store.people.list({ limit: 0 }) + return (await store.people.listBots({ limit: 50 })).items +} + +const botNames = async (store: MessageStore) => + (await sorted(store)).map(({ displayName, reason }) => ({ displayName, reason })) + +const listed = async (store: MessageStore) => + (await store.people.list({ limit: 50, kind: "all" })).items.map(({ displayName }) => displayName) + +const reaches = async (store: MessageStore) => + Object.fromEntries( + (await store.mail.emails({ limit: 50 })).flatMap((email) => + email.outgoing ? [] : [[email.subject, { type: email.mailType, reach: email.reach }]], + ), + ) + +it("makes a sender of a newsletter only a bot, a human author too, and keeps its mail typed a newsletter", async () => { + const { store } = await opened([issue("Notes from the road"), issue("Notes from the sea")]) + + expect(await botNames(store)).toEqual([{ displayName: "Ada Quill", reason: "newsletter-only" }]) + expect(await listed(store)).not.toContain("Ada Quill") + expect(await reaches(store)).toEqual({ + "Notes from the road": { type: "newsletter", reach: "broadcast" }, + "Notes from the sea": { type: "newsletter", reach: "broadcast" }, + }) +}) + +it("gives the bot back once the owner replies, and only its newsletter mail keeps reach broadcast", async () => { + const { store, db, mailbox, sync } = await opened([issue("Notes from the road")]) + expect(await botNames(store)).toHaveLength(1) + + mailbox.messages.push( + mail(["Me", ME], "Re: Notes from the road", { to: [[null, AUTHOR[1]]], sent: true }), + mail(AUTHOR, "Re: Re: Notes from the road"), + ) + await sync() + db.prepare("UPDATE persons SET kind = NULL WHERE owner = 1").run() + + expect(await botNames(store)).toEqual([]) + const ada = (await store.people.list({ limit: 50, kind: "all" })).items.find( + ({ displayName }) => displayName === "Ada Quill", + ) + expect(ada).toMatchObject({ displayName: "Ada Quill", reach: "direct", ties: ["mail"] }) + expect(await reaches(store)).toEqual({ + "Notes from the road": { type: "newsletter", reach: "broadcast" }, + "Re: Re: Notes from the road": { type: "personal", reach: "direct" }, + }) +}) + +it("gives the bot back after a 1-to-1 mail from its address, though the owner never wrote", async () => { + const { store, db, mailbox, sync } = await opened([issue("Notes from the road")]) + expect(await botNames(store)).toHaveLength(1) + + mailbox.messages.push(mail(AUTHOR, "A question for you")) + await sync() + db.prepare("UPDATE persons SET kind = NULL WHERE owner = 1").run() + + expect(await botNames(store)).toEqual([]) + expect(await listed(store)).toContain("Ada Quill") +}) + +it("keeps a person the owner writes to who also sends a newsletter, and a discussion list's members", async () => { + const list = "" + const { store } = await opened([ + mail(["Me", ME], "Lunch?", { to: [[null, AUTHOR[1]]], sent: true }), + issue("Notes from the road"), + mail(["Bo Lind", "bo@dev.example.org"], "[dev] release plan", { listId: list }), + mail(["Cy Moor", "cy@dev.example.org"], "[dev] re: release plan", { listId: list }), + mail(["Di Park", "di@dev.example.org"], "[dev] re: re: release plan", { listId: list }), + ]) + + expect(await botNames(store)).toEqual([]) + expect(await listed(store)).toEqual(expect.arrayContaining(["Ada Quill", "Bo Lind", "Cy Moor", "Di Park"])) +}) + +it("keeps the owner's choice over the newsletter rule", async () => { + const { store } = await opened([issue("Notes from the road")]) + const [bot] = await sorted(store) + + await store.people.moveToPerson(String(bot?.bot), "owner") + await store.people.list({ limit: 0, kind: "all" }) + + expect(await botNames(store)).toEqual([]) + expect(await listed(store)).toContain("Ada Quill") +}) diff --git a/src/store/people-list.test.ts b/src/store/people-list.test.ts index fc9e59974..3ccaff002 100644 --- a/src/store/people-list.test.ts +++ b/src/store/people-list.test.ts @@ -355,7 +355,8 @@ describe("the kind of a person", () => { ) .get(account, NOW, NOW)?.id, ) - for (const n of [1, 2, 3]) { + // One mail outside the bulk box: all of it there would make her a newsletter's bot. + for (const n of [1, 2, 3, 4]) { const email = Number( db .prepare( @@ -364,18 +365,19 @@ describe("the kind of a person", () => { ) .get(account, thread, `m${n}`, identityPk(db, "email", "lena@acme.ru"), NOW + n, NOW, NOW)?.id, ) - db.prepare("INSERT INTO email_mailboxes (email_id, mailbox_id, created_at) VALUES (?, ?, ?)").run( - email, - bulk, - NOW, - ) + if (n < 4) + db.prepare("INSERT INTO email_mailboxes (email_id, mailbox_id, created_at) VALUES (?, ?, ?)").run( + email, + bulk, + NOW, + ) } const [lena] = (await store.people.list({ limit: 10, kind: "automated" })).items expect(lena).toMatchObject({ kindSignals: ["bulk-mail"], - messagesFrom: 3, - lastContact: new Date(NOW + 3).toISOString(), + messagesFrom: 4, + lastContact: new Date(NOW + 4).toISOString(), contact: "lena@acme.ru", }) }) diff --git a/src/store/sqlite/email-types.ts b/src/store/sqlite/email-types.ts index e2745c381..334e0048d 100644 --- a/src/store/sqlite/email-types.ts +++ b/src/store/sqlite/email-types.ts @@ -5,6 +5,7 @@ import { MAIL_TYPES, type MailType, type MailTypeOf, mailTypeOf, schemaTypesOf } import { sortRuleFor } from "../../mail/sort-rules.js" import { type CacheDatabase, isQueryOnly } from "../driver.js" import { typeRulesOf } from "./mail-sorting.js" +import { NEWSLETTER_ONLY } from "./sender-bots.js" import { LIST_ID, LIST_SENDERS, REACHES, type Reach, senderKey } from "./sender-signals.js" import { read, writeBatch } from "./transaction.js" @@ -27,7 +28,8 @@ const INPUTS = "WHERE a.attachable_type = 'email' AND a.attachable_id = e.id AND a.mime IS NOT NULL) AS parts, " + "e.outgoing IS 1 OR EXISTS (SELECT 1 FROM email_recipients r JOIN emails o ON o.id = r.email_id " + "WHERE r.identity_id = e.from_identity_id AND o.outgoing = 1) AS owner_wrote, " + - "EXISTS (SELECT 1 FROM sender_bot_identities b WHERE b.identity_id = e.from_identity_id) AS bot, " + + "EXISTS (SELECT 1 FROM sender_bot_identities b JOIN sender_bots s ON s.id = b.bot_id " + + `WHERE b.identity_id = e.from_identity_id AND s.reason IS NOT '${NEWSLETTER_ONLY}') AS bot, ` + "(SELECT json_extract(g.metadata, '$.sector') FROM organization_identities oi " + "JOIN organizations g ON g.id = oi.organization_id " + "WHERE oi.identity_id = e.from_identity_id AND g.deleted_at IS NULL ORDER BY g.id LIMIT 1) AS sector " + diff --git a/src/store/sqlite/people-list.ts b/src/store/sqlite/people-list.ts index fdd94a601..089485472 100644 --- a/src/store/sqlite/people-list.ts +++ b/src/store/sqlite/people-list.ts @@ -19,8 +19,15 @@ import { fold } from "../normalize.js" import { groupByDomain, type Sorted } from "./domain-organizations.js" import { mergedAwaySql } from "./merged-persons.js" import { ALWAYS_SHOWN, type ShownBecause, shownReasons } from "./person-ties.js" -import { hasLegacyBots, ownerPeopleOf, ruleBotsBack, ruleToBot, settleLegacyBots } from "./sender-bots.js" -import { type Reach, type SenderSignal, senderSignalsOf, sentMailOf } from "./sender-signals.js" +import { + hasLegacyBots, + NEWSLETTER_ONLY, + ownerPeopleOf, + ruleBotsBack, + ruleToBot, + settleLegacyBots, +} from "./sender-bots.js" +import { LIST_ID, 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" @@ -144,12 +151,16 @@ const TWO_WAY = "AND EXISTS (SELECT 1 FROM messages o WHERE o.chat_id = c.id AND o.outgoing = 1))" 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, " + - "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 " + + "SELECT person, count(*) AS n, sum(bulk) AS bulk, sum(auto) AS auto, sum(null_return) AS null_return, " + + "sum(bulk OR listed) AS listed FROM (SELECT l.person_id AS person, 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, " + + "json_extract(e.headers, '$.\"auto-submitted\"') IS NOT NULL AS auto, " + + "json_extract(e.headers, '$.\"null-return-path\"') IS 1 AS null_return, " + + `${LIST_ID} IS NOT NULL OR json_extract(e.headers, '$."list-unsubscribe"') IS 1 ` + + "OR json_extract(e.headers, '$.\"list-unsubscribe-post\"') IS 1 OR json_extract(e.headers, '$.\"feedback-id\"') IS 1 " + + "OR json_extract(e.headers, '$.precedence') IN ('bulk', 'junk') AS listed " + "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` + `WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND ${IN_SCOPE(scope, "l.person_id")}) GROUP BY 1` const IDENTITIES = (scope: Scope) => "SELECT l.person_id AS person, i.id, i.provider, i.external_id, i.name, i.username, i.phone, i.email, i.bot " + @@ -185,6 +196,8 @@ interface Facts { identities: number /** Identities a program holds by their own mark: the platform's bot flag, a no-reply or notification address. */ programIdentities: number + /** Identities of a messenger, a CRM or another source than mail. */ + notMail: number } const perIdentity = (database: CacheDatabase, sql: string, params: SqlValue[]): Map => @@ -238,6 +251,7 @@ const factsOf = (database: CacheDatabase, scope: Scope): Map => { messages: 0, identities: held.length, programIdentities: 0, + notMail: 0, } const source = (row: Record) => ({ provider: String(row.provider), @@ -257,6 +271,7 @@ const factsOf = (database: CacheDatabase, scope: Scope): Map => { one.organization ||= owned.has(identity) one.twoWay ||= twoWay.has(identity) one.messages += messages.get(identity) ?? 0 + if (row.provider !== "email") one.notMail += 1 if (Number(row.bot) === 1 || (email !== null && (isNoReplyAddress(email) || isNotificationAddress(email)))) one.programIdentities += 1 } @@ -302,6 +317,8 @@ interface Classified extends Omit { if (test) return { kind: "test", signals: ["test-data"] } const emails = facts?.emails ?? [] const automated: KindSignal[] = [ + ...(newsletterOnly ? ([NEWSLETTER_ONLY] as const) : []), ...(facts?.bot ? (["bot"] as const) : []), ...(emails.some(isNoReplyAddress) ? (["no-reply"] as const) : []), ...(emails.some(isNotificationAddress) ? (["notification-address"] as const) : []), @@ -386,6 +407,27 @@ const isProgram = ( (facts.bot || (!facts.twoWay && !ties.includes("mail"))) && (facts.identities === 1 || facts.programIdentities === facts.identities) +/** + * The owner ruled on 2026-11-25 that a sender who only sends a newsletter is a bot, a human author too: all their mail + * came as a list's, and they and the owner never exchanged a word. Any tie keeps them a person. + */ +const mayBeNewsletterOnly = (facts: Facts | undefined, ties: ShownBecause[], mail: MailCounts | undefined) => + facts !== undefined && + mail !== undefined && + ties.length === 0 && + !facts.bot && + !facts.twoWay && + facts.messages === 0 && + facts.notMail === 0 && + mail.n > 0 && + mail.listed === mail.n + +/** A candidate whose mail came through a discussion list writes to a group, not to subscribers. */ +const newsletterOnlyOf = (database: CacheDatabase, candidates: readonly number[]): Set => { + const sent = sentMailOf(database, candidates) + return new Set(candidates.filter((id) => (sent.get(id) ?? []).every((one) => !one.discussionList))) +} + /** Each person with their kind, contact and counts; the last contact is added for the page alone. */ const classified = ( database: CacheDatabase, @@ -403,20 +445,42 @@ const classified = ( .all(...scopeParams(scope)) .map((row) => [ Number(row.person), - { n: Number(row.n), bulk: Number(row.bulk), auto: Number(row.auto), nullReturn: Number(row.null_return) }, + { + n: Number(row.n), + bulk: Number(row.bulk), + auto: Number(row.auto), + nullReturn: Number(row.null_return), + listed: Number(row.listed), + }, ]), ) + const newsletters = newsletterOnlyOf( + database, + people.flatMap(({ id, owner }) => + !owner && + !ownerPeople.has(id) && + !test.has(id) && + mayBeNewsletterOnly(facts.get(id), reasons.get(id) ?? [], mail.get(id)) + ? [id] + : [], + ), + ) return people.map(({ id, name, owner }) => { const own = facts.get(id) const contact = { username: own?.username ?? null, phone: own?.phone ?? null, email: own?.email ?? null } const shown = displayName(name, { ...contact, name: own?.name ?? null }) const ties = reasons.get(id) ?? [] const kept = ownerPeople.has(id) - const worked = kindOf(shown, own, ties, mail.get(id), test.has(id), kept) - const toBot = !kept && !owner && worked.kind !== "test" && isProgram(worked, own, ties) + const worked = kindOf(shown, own, ties, mail.get(id), test.has(id), kept, newsletters.has(id)) + const program = !kept && !owner && worked.kind !== "test" && isProgram(worked, own, ties) + const botReason = program + ? worked.signals.filter((signal) => signal !== NEWSLETTER_ONLY).join(", ") + : newsletters.has(id) + ? NEWSLETTER_ONLY + : undefined return { id, - ...(toBot ? { move: "bot" as const } : {}), + ...(botReason === undefined ? {} : { move: "bot" as const, botReason }), nameOrder: nameOrderOf(shown), person: `person:${id}`, name, @@ -452,7 +516,7 @@ const withLastContact = ( database, people.map(({ id }) => id), ) - return people.map(({ id, nameOrder: _, emails, twoWay, move: __, ...person }) => { + return people.map(({ id, nameOrder: _, emails, twoWay, move: __, botReason: ___, ...person }) => { const time = at.get(id) const { ties } = person return { @@ -477,7 +541,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 = "9" +const KIND_RULES = "10" 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 @@ -536,7 +600,7 @@ const keep = (database: CacheDatabase, worked: Worked[]): void => { for (const person of worked) if (person.move === "bot" && person.kind !== MERGED) { bots.push({ - id: ruleToBot(database, person.id, person.kindSignals.join(", "), at), + id: ruleToBot(database, person.id, person.botReason ?? person.kindSignals.join(", "), at), displayName: person.displayName, holds: true, bot: true, diff --git a/src/store/sqlite/sender-bots.ts b/src/store/sqlite/sender-bots.ts index ec1993257..627e29243 100644 --- a/src/store/sqlite/sender-bots.ts +++ b/src/store/sqlite/sender-bots.ts @@ -8,7 +8,8 @@ import { groupByDomain, releaseDomainHolds } from "./domain-organizations.js" import { currentPerson } from "./merged-persons.js" import type { StoreContext } from "./open.js" import { isOwner, mergePerson, move, recordOf, renameAfterLeaving } from "./person-links.js" -import { type Reach, type SenderSignal, senderSignalsOf, sentMailOf } from "./sender-signals.js" +import { SMALL_GROUP_MEMBERS } from "./person-ties.js" +import { LIST_ID, type Reach, type SenderSignal, senderSignalsOf, sentMailOf } from "./sender-signals.js" import { read, write } from "./transaction.js" export type BotAuthor = "rules" | "owner" @@ -269,25 +270,42 @@ export const ruleToBot = (database: CacheDatabase, person: number, reason: strin return bot } +/** The reason of a bot that only sent a newsletter: a mail written to the owner alone gives it back to a person. */ +export const NEWSLETTER_ONLY = "newsletter-only" + +/** Mail from the identity `s` that no list sent, to the owner and at most a small group. */ +const ONE_TO_ONE = + "EXISTS (SELECT 1 FROM emails e WHERE e.from_identity_id = s.identity_id AND e.outgoing IS NOT 1 " + + `AND e.deleted_at IS NULL AND ${LIST_ID} IS NULL AND json_extract(e.headers, '$."list-unsubscribe"') IS NOT 1 ` + + "AND json_extract(e.headers, '$.\"list-unsubscribe-post\"') IS NOT 1 " + + "AND json_extract(e.headers, '$.\"feedback-id\"') IS NOT 1 " + + "AND json_extract(e.headers, '$.precedence') IS NOT 'bulk' AND json_extract(e.headers, '$.precedence') IS NOT 'junk' " + + "AND NOT EXISTS (SELECT 1 FROM email_mailboxes m " + + "JOIN mailboxes x ON x.id = m.mailbox_id WHERE m.email_id = e.id AND x.kind = 'bulk') " + + "AND (SELECT count(*) FROM email_recipients r WHERE r.email_id = e.id AND r.role IN ('to', 'cc')) " + + `BETWEEN 1 AND ${SMALL_GROUP_MEMBERS})` + /** - * A rule's bot the owner wrote to, by mail or in a private chat both wrote in, goes back to the people its identities + * A rule's bot the owner wrote to, or a newsletter's that wrote to the owner alone, by mail or in a private chat both wrote in, goes back to the people its identities * came from; a messenger's own bot flag holds anyway. The caller holds the write lock. */ export const ruleBotsBack = (database: CacheDatabase, at: number): void => { const back = database .prepare( - "SELECT b.id FROM sender_bots b WHERE b.author = 'rules' AND NOT EXISTS (SELECT 1 FROM sender_bot_identities s " + - "JOIN identities i ON i.id = s.identity_id WHERE s.bot_id = b.id AND i.bot = 1) " + + "SELECT b.id, b.reason FROM sender_bots b WHERE b.author = 'rules' AND NOT EXISTS (SELECT 1 FROM " + + "sender_bot_identities s JOIN identities i ON i.id = s.identity_id WHERE s.bot_id = b.id AND i.bot = 1) " + "AND EXISTS (SELECT 1 FROM sender_bot_identities s WHERE s.bot_id = b.id AND (" + "EXISTS (SELECT 1 FROM email_recipients r JOIN emails e ON e.id = r.email_id WHERE r.identity_id = s.identity_id " + "AND e.outgoing = 1 AND e.deleted_at IS NULL AND e.draft IS NOT 1) OR " + "EXISTS (SELECT 1 FROM messages m JOIN chats c ON c.id = m.chat_id WHERE m.sender_identity_id = s.identity_id " + "AND m.outgoing IS NOT 1 AND c.kind = 'dialog' AND EXISTS (SELECT 1 FROM messages o WHERE o.chat_id = c.id " + - "AND o.outgoing = 1))))", + `AND o.outgoing = 1)) OR (b.reason = '${NEWSLETTER_ONLY}' AND ${ONE_TO_ONE})))`, ) .all() - const log = { author: "rules" as const, reason: "the owner wrote to it", at } - for (const row of back) outOfBot(database, botIdentitiesOf(database, Number(row.id)), undefined, log) + for (const row of back) { + const reason = row.reason === NEWSLETTER_ONLY ? "a 1-to-1 mail or the owner wrote to it" : "the owner wrote to it" + outOfBot(database, botIdentitiesOf(database, Number(row.id)), undefined, { author: "rules", reason, at }) + } } /** Whether a build before version 75 sorted a bot onto a person row since the last kept list. */ From c8208ac478393c9731df46c0285f67f14ebc2056 Mon Sep 17 00:00:00 2001 From: leemour Date: Wed, 25 Nov 2026 23:45:37 +0100 Subject: [PATCH 2/3] fix(people): a 1-to-1 mail gives a newsletter's bot back with no other change to wake the list Co-Authored-By: Claude Opus 5.5 --- src/store/newsletter-bots.test.ts | 11 +++------- src/store/sqlite/people-list.ts | 9 +++++++- src/store/sqlite/sender-bots.ts | 35 +++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 9 deletions(-) diff --git a/src/store/newsletter-bots.test.ts b/src/store/newsletter-bots.test.ts index bff157163..65427ddd3 100644 --- a/src/store/newsletter-bots.test.ts +++ b/src/store/newsletter-bots.test.ts @@ -4,7 +4,6 @@ import { join } from "node:path" import { afterEach, expect, it } from "vitest" import { syncMail } from "../mail/sync.js" import { type FakeMail, type FakeMailbox, fakeMailSource } from "../mail/testing/index.js" -import { openCache } from "./open.js" import { type MessageStore, openStore } from "./store.js" const ME = "owner@home.example.com" @@ -53,9 +52,7 @@ const opened = async (messages: FakeMail[]) => { const sync = () => syncMail(fakeMailSource(mailbox), store, { account: { address: ME }, since: SINCE, now: () => NOW }) await sync() - const db = await openCache(path) - handles.push(db) - return { store, db, mailbox, sync } + return { store, mailbox, sync } } const sorted = async (store: MessageStore) => { @@ -88,7 +85,7 @@ it("makes a sender of a newsletter only a bot, a human author too, and keeps its }) it("gives the bot back once the owner replies, and only its newsletter mail keeps reach broadcast", async () => { - const { store, db, mailbox, sync } = await opened([issue("Notes from the road")]) + const { store, mailbox, sync } = await opened([issue("Notes from the road")]) expect(await botNames(store)).toHaveLength(1) mailbox.messages.push( @@ -96,7 +93,6 @@ it("gives the bot back once the owner replies, and only its newsletter mail keep mail(AUTHOR, "Re: Re: Notes from the road"), ) await sync() - db.prepare("UPDATE persons SET kind = NULL WHERE owner = 1").run() expect(await botNames(store)).toEqual([]) const ada = (await store.people.list({ limit: 50, kind: "all" })).items.find( @@ -110,12 +106,11 @@ it("gives the bot back once the owner replies, and only its newsletter mail keep }) it("gives the bot back after a 1-to-1 mail from its address, though the owner never wrote", async () => { - const { store, db, mailbox, sync } = await opened([issue("Notes from the road")]) + const { store, mailbox, sync } = await opened([issue("Notes from the road")]) expect(await botNames(store)).toHaveLength(1) mailbox.messages.push(mail(AUTHOR, "A question for you")) await sync() - db.prepare("UPDATE persons SET kind = NULL WHERE owner = 1").run() expect(await botNames(store)).toEqual([]) expect(await listed(store)).toContain("Ada Quill") diff --git a/src/store/sqlite/people-list.ts b/src/store/sqlite/people-list.ts index 089485472..225d690ad 100644 --- a/src/store/sqlite/people-list.ts +++ b/src/store/sqlite/people-list.ts @@ -22,10 +22,12 @@ import { ALWAYS_SHOWN, type ShownBecause, shownReasons } from "./person-ties.js" import { hasLegacyBots, NEWSLETTER_ONLY, + newsletterBotsMail, ownerPeopleOf, ruleBotsBack, ruleToBot, settleLegacyBots, + settleNewsletterBots, } from "./sender-bots.js" import { LIST_ID, type Reach, type SenderSignal, senderSignalsOf, sentMailOf } from "./sender-signals.js" import { mergedAssignees } from "./task-board.js" @@ -338,7 +340,10 @@ interface MailCounts { /** One misfiled letter is no newsletter. */ const BULK_MIN = 3 -/** A program writes: enough to move a sender to a bot. A name or a bulk mailbox alone may be a human's newsletter. */ +/** + * A program writes: enough to move a sender to a bot. A name or a bulk mailbox alone does not; a sender all of whose + * mail a list sent becomes a bot by `NEWSLETTER_ONLY` instead, which a 1-to-1 mail gives back. + */ const PROGRAM_SIGNALS: readonly KindSignal[] = [ "bot", "no-reply", @@ -648,6 +653,8 @@ export const storeKinds = (database: CacheDatabase): boolean => { // A 1.0 build keeps the kinds of the people it sorts onto a bot, so nothing else would bring their bot here. if (!isQueryOnly(database) && hasLegacyBots(database)) writeBatch(database, () => settleLegacyBots(database, Date.now())) + const newest = isQueryOnly(database) ? undefined : newsletterBotsMail(database) + if (newest !== undefined) writeBatch(database, () => settleNewsletterBots(database, newest, Date.now())) if (isQueryOnly(database)) return ( rulesOf(database) === KIND_RULES && diff --git a/src/store/sqlite/sender-bots.ts b/src/store/sqlite/sender-bots.ts index 627e29243..4d714b5c7 100644 --- a/src/store/sqlite/sender-bots.ts +++ b/src/store/sqlite/sender-bots.ts @@ -308,6 +308,41 @@ export const ruleBotsBack = (database: CacheDatabase, at: number): void => { } } +const MAIL_CHECKED = "people.newsletter_bots_mail_checked" + +/** + * Mail a newsletter's bot sent since the last check: no trigger makes a kind stale for it, so a 1-to-1 mail would wait + * for someone else's change to give the bot back. Answers the newest email id to check up to, or `undefined`. + */ +export const newsletterBotsMail = (database: CacheDatabase): number | undefined => { + const newest = Number(database.prepare("SELECT coalesce(max(id), 0) AS n FROM emails").get()?.n) + const checked = Number( + database.prepare("SELECT value FROM store_settings WHERE key = ?").get(MAIL_CHECKED)?.value ?? 0, + ) + return newest > checked ? newest : undefined +} + +/** Gives back the newsletter bots a 1-to-1 mail came from, and keeps how far the mail was checked. */ +export const settleNewsletterBots = (database: CacheDatabase, newest: number, at: number): void => { + const checked = Number( + database.prepare("SELECT value FROM store_settings WHERE key = ?").get(MAIL_CHECKED)?.value ?? 0, + ) + const sent = database + .prepare( + "SELECT 1 FROM sender_bots b CROSS JOIN sender_bot_identities s ON s.bot_id = b.id CROSS JOIN emails e " + + `ON e.from_identity_id = s.identity_id WHERE b.author = 'rules' AND b.reason = '${NEWSLETTER_ONLY}' ` + + "AND e.id > ? AND e.id <= ? LIMIT 1", + ) + .get(checked, newest) + if (sent !== undefined) ruleBotsBack(database, at) + database + .prepare( + "INSERT INTO store_settings (key, value, at) VALUES (?, ?, ?) " + + "ON CONFLICT (key) DO UPDATE SET value = excluded.value, at = excluded.at", + ) + .run(MAIL_CHECKED, String(newest), at) +} + /** Whether a build before version 75 sorted a bot onto a person row since the last kept list. */ export const hasLegacyBots = (database: CacheDatabase): boolean => database.prepare("SELECT 1 FROM sender_bots WHERE person_id > 0 LIMIT 1").get() !== undefined From 0bba9c733fa8f7a38648b6139c9a14d68b88e222 Mon Sep 17 00:00:00 2001 From: leemour Date: Thu, 26 Nov 2026 00:11:32 +0100 Subject: [PATCH 3/3] =?UTF-8?q?docs(changes):=20newsletter=20bots=20fragme?= =?UTF-8?q?nt=20under=20Changed=20=E2=80=94=20experimental?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- changes/feat-newsletter-bots.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changes/feat-newsletter-bots.md b/changes/feat-newsletter-bots.md index 5ddb2e053..2e2384e56 100644 --- a/changes/feat-newsletter-bots.md +++ b/changes/feat-newsletter-bots.md @@ -1,4 +1,4 @@ -### Changed +### Changed — experimental - **A sender of a newsletter only is a bot, a human author too.** The owner's ruling of 25.11.2026, in place of the earlier one that kept a human-written newsletter a person. A person all of whose mail came from a list (List-Id,