From a53564eb34cbf2fd8552497388ebddd12e4697c0 Mon Sep 17 00:00:00 2001 From: leemour Date: Wed, 25 Nov 2026 05:08:42 +0100 Subject: [PATCH 1/2] feat(people): organizations from mail domains Plan step 5 of the contact-kinds plan. When kinds are kept, a sender bot or a shared mailbox at a company domain joins the organization of its registrable domain: the one already holding an address there, else a new company named by the sender (a company name or the domain's own word) or by the domain. Its addresses go to organization_identities (method domain, author rules) and a bot's sender_bots.organization_id is set. A human writing from that domain gets a member-of link, never a merge or a proposal; humans alone make no organization. Free mail, throwaway mail (disposable-email-domains-js, already a dependency) and a hand table of sending platforms are never company domains. The owner's word holds: a removed member-of leaves a rejected relationship proposal the rule checks, erasing an organization leaves a rejected organization-domain proposal per domain, and moveToPerson drops the rule's holds. No migration; KIND_RULES goes to 8. Co-Authored-By: Claude Opus 5.5 --- changes/feat-organizations-from-domains.md | 14 ++ docs/dev/ARCHITECTURE.md | 11 + docs/storage/schema.md | 2 +- scripts/schema/spec.mjs | 2 +- src/store/domain-organizations.test.ts | 175 +++++++++++++ src/store/people-list.test.ts | 2 +- src/store/sqlite/domain-organizations.ts | 270 +++++++++++++++++++++ src/store/sqlite/organizations.ts | 8 +- src/store/sqlite/people-list.ts | 19 +- src/store/sqlite/sender-bots.ts | 4 + 10 files changed, 502 insertions(+), 5 deletions(-) create mode 100644 changes/feat-organizations-from-domains.md create mode 100644 src/store/domain-organizations.test.ts create mode 100644 src/store/sqlite/domain-organizations.ts diff --git a/changes/feat-organizations-from-domains.md b/changes/feat-organizations-from-domains.md new file mode 100644 index 000000000..285ff45ab --- /dev/null +++ b/changes/feat-organizations-from-domains.md @@ -0,0 +1,14 @@ +### Added + +- **Organizations from mail domains.** A sender bot or a shared mailbox at a company domain joins that domain's + organization when people are listed: the one already holding an address there, else a new one, named by the sender + when the name is a company's, else by the domain. Subdomains count as their registrable domain. A human writing + from that domain gets a `member-of` link to it and is never merged. Free mail, throwaway mail and sending platforms + (newsletter hosts and mail services) make no organization. The owner's word holds: a membership the owner removed, + an organization the owner erased and a bot the owner moved to a person are not grouped again. See + [ARCHITECTURE.md, "Organizations from mail domains"](../docs/dev/ARCHITECTURE.md). + +### Changed — experimental + +- **`KIND_RULES` goes to 8.** The first list after the upgrade works out every kind again and groups the senders it + finds under their organizations. A shared mailbox an organization now holds gains the `organization` kind signal. diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index fafef5783..e276be802 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -707,6 +707,17 @@ proposes them instead. A no-reply address (`isNoReplyAddress`) is no one's: it n is a `sender_bot_moves` row. A bot is never joined to anyone by the matcher (`identity.not-a-person`), never assigned a task (`sender-bot.assignee`), never offered by `people.similar` and has no ties in `people.ties`. Neither table has a foreign key, so an older build erasing a person or purging an account still can; triggers drop their rows. +- **Organizations from mail domains** (`domain-organizations.ts`, plan step 5): when kinds are kept, a bot or a shared + mailbox (every address a role address) at a company domain joins the organization of its registrable domain + (`registrableOf`, so `mail.bank.example` is `bank.example`): the organization already holding an address there, else + a new `company` named by the sender when the name is a company's or the domain's own word, else by the domain. Its + addresses go to `organization_identities` with method `domain`, author `rules`, and a bot's `sender_bots.organization_id` + is set. A human with an address there gets a `member-of` link (author `rule`), never a merge and never a proposal; a + human alone makes no organization. Free mail (`FREE_MAIL`), throwaway mail (`disposable-email-domains-js`) and + sending platforms (`SENDING_PLATFORMS`) are never a company domain. Two organizations holding one domain leave it + ungrouped. The owner's word holds: a removed `member-of` leaves a rejected `relationship` proposal the rule checks; + `knowledge.eraseOrganization` leaves a rejected `organization-domain` proposal per domain, so the rule never remakes + it; `moveToPerson` drops the rule's holds on the moved identities, and a person the owner kept as one holds nothing. `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/storage/schema.md b/docs/storage/schema.md index 5ac123acc..8f0315c82 100644 --- a/docs/storage/schema.md +++ b/docs/storage/schema.md @@ -303,7 +303,7 @@ A phone, an address or an account an organization owns: a shop's number, `info@` | `id` | integer | PK | | | | `identity_id` | integer | not null | → `identities.id` | the `identity` it belongs to | | `organization_id` | integer | not null | → `organizations.id` | the `organization` it belongs to | -| `method` | text | not null | | how it was decided: `mention`, `owner`, an import | +| `method` | text | not null | | how it was decided: `mention`, `owner`, an import, `domain` | | `author` | text | not null | | `owner`, an agent by name, `rules` | | `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 70399b6cd..c3357a533 100644 --- a/scripts/schema/spec.mjs +++ b/scripts/schema/spec.mjs @@ -592,7 +592,7 @@ const NEW = { id(), fk("identity_id", "identities", { notnull: true }), fk("organization_id", "organizations", { notnull: true }), - c("method", "text", { notnull: true, note: "how it was decided: `mention`, `owner`, an import" }), + c("method", "text", { notnull: true, note: "how it was decided: `mention`, `owner`, an import, `domain`" }), c("author", "text", { notnull: true, note: "`owner`, an agent by name, `rules`" }), ...ts(), ], diff --git a/src/store/domain-organizations.test.ts b/src/store/domain-organizations.test.ts new file mode 100644 index 000000000..ab07b7fef --- /dev/null +++ b/src/store/domain-organizations.test.ts @@ -0,0 +1,175 @@ +import { mkdtempSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { afterEach, expect, it } from "vitest" +import type { CacheDatabase } from "./driver.js" +import { openCache } from "./open.js" +import { type AccountKey, type MessageStore, openStore } from "./store.js" + +const TG: AccountKey = { provider: "telegram", account: "1" } +const MAIL: AccountKey = { provider: "email", account: "me@acme.ru" } + +const handles: { close(): unknown }[] = [] +afterEach(async () => { + for (const handle of handles.splice(0)) await handle.close() +}) + +const opened = async () => { + const path = join(mkdtempSync(join(tmpdir(), "domain-organizations-")), "store.db") + const store = await openStore({ path }) + handles.push(store) + await store.people.savePeople(TG, [{ id: "1", name: "Me" }]) + await store.people.linkToOwner({ provider: "telegram", id: "1" }) + await store.accounts.saveAccount(MAIL, { name: null }) + const db = await openCache(path) + handles.push(db) + return { store, db } +} + +const sorted = (store: MessageStore) => store.people.list({ limit: 100, kind: "all" }) + +/** Makes the next list work out every kind, and so the domain rule, again. */ +const resort = async (store: MessageStore, db: CacheDatabase) => { + db.prepare("UPDATE persons SET kind = NULL").run() + await sorted(store) +} + +const holdings = (db: CacheDatabase) => + db + .prepare( + "SELECT o.name, i.external_id AS address, oi.method, oi.author FROM organizations o " + + "JOIN organization_identities oi ON oi.organization_id = o.id JOIN identities i ON i.id = oi.identity_id " + + "ORDER BY i.external_id", + ) + .all() + +const memberships = (db: CacheDatabase) => + db + .prepare( + "SELECT l.from_id AS person, o.name, l.author, l.confirmed FROM links l JOIN organizations o ON o.id = l.to_id " + + "WHERE l.kind = 'member-of' AND l.from_type = 'person' AND l.to_type = 'organization' ORDER BY l.from_id", + ) + .all() + +const uidOf = async (store: MessageStore, provider: string, id: string) => + Number((await store.people.personOf({ provider, id }))?.uid) + +it("puts a bot and a shared mailbox of one company domain, subdomains too, into one organization", async () => { + const { store, db } = await opened() + await store.people.savePeople(MAIL, [ + { id: "noreply@mail.bank.ru", name: "Bank" }, + { id: "info@bank.ru", name: "Bank Support" }, + ]) + + await sorted(store) + + expect(holdings(db)).toEqual([ + { name: "Bank", address: "info@bank.ru", method: "domain", author: "rules" }, + { name: "Bank", address: "noreply@mail.bank.ru", method: "domain", author: "rules" }, + ]) + const organization = db.prepare("SELECT id FROM organizations").get()?.id + expect(db.prepare("SELECT organization_id FROM sender_bots").all()).toEqual([{ organization_id: organization }]) + expect((await store.people.linkProposals({ limit: 10, offset: 0 })).items).toEqual([]) +}) + +it("names the organization by its domain when the sender's name is no company's", async () => { + const { store, db } = await opened() + await store.people.savePeople(MAIL, [{ id: "alerts-noreply@shop.ru", name: "Your order" }]) + + await sorted(store) + + expect(holdings(db).map(({ name }) => name)).toEqual(["shop.ru"]) +}) + +it("makes no organization for free mail or throwaway mail", async () => { + const { store, db } = await opened() + await store.people.savePeople(MAIL, [ + { id: "noreply@gmail.com", name: "Gmail Robot" }, + { id: "info@mailinator.com", name: "Mailinator" }, + ]) + + await sorted(store) + + expect(db.prepare("SELECT count(*) AS n FROM organizations").get()?.n).toBe(0) +}) + +it("never groups two newsletters by the platform that sends them", async () => { + const { store, db } = await opened() + await store.people.savePeople(MAIL, [ + { id: "alpha-noreply@substack.com", name: "Alpha Weekly" }, + { id: "beta-noreply@substack.com", name: "Beta Digest" }, + { id: "news@ghost.io", name: "Gamma" }, + ]) + + await sorted(store) + + expect(db.prepare("SELECT count(*) AS n FROM organizations").get()?.n).toBe(0) + expect(memberships(db)).toEqual([]) +}) + +it("links a human at the company domain as a member, never merged, whichever came first", async () => { + const { store, db } = await opened() + await store.people.savePeople(MAIL, [{ id: "lena@studio.ru", name: "Lena Marsh" }]) + await sorted(store) + expect(memberships(db)).toEqual([]) + + await store.people.savePeople(MAIL, [{ id: "noreply@studio.ru", name: "Studio" }]) + await sorted(store) + await store.people.savePeople(MAIL, [{ id: "oleg@studio.ru", name: "Oleg Kim" }]) + await sorted(store) + + const lena = await uidOf(store, "email", "lena@studio.ru") + const oleg = await uidOf(store, "email", "oleg@studio.ru") + expect(memberships(db)).toEqual([ + { person: lena, name: "Studio", author: "rule", confirmed: 1 }, + { person: oleg, name: "Studio", author: "rule", confirmed: 1 }, + ]) + expect(holdings(db).map(({ address }) => address)).toEqual(["noreply@studio.ru"]) + const listed = (await sorted(store)).items.find(({ person }) => person === `person:${lena}`) + expect(listed?.kind).not.toBe("organization") + expect((await store.people.linkProposals({ limit: 10, offset: 0 })).items).toEqual([]) +}) + +it("keeps the owner's separations: a removed membership, an erased organization, a bot made a person", async () => { + const { store, db } = await opened() + await store.people.savePeople(MAIL, [ + { id: "noreply@studio.ru", name: "Studio" }, + { id: "lena@studio.ru", name: "Lena Marsh" }, + { id: "noreply@bank.ru", name: "Bank" }, + { id: "noreply@shop.ru", name: "Shop" }, + ]) + await sorted(store) + const lena = await uidOf(store, "email", "lena@studio.ru") + const [relation] = (await store.knowledge.relations(null, `person:${lena}`)).filter((one) => one.kind === "member-of") + + await store.knowledge.removeRelation(null, String(relation?.id), "owner") + const bank = Number(db.prepare("SELECT id FROM organizations WHERE name = 'Bank'").get()?.id) + await store.knowledge.eraseOrganization(`organization:${bank}`, "owner", { apply: true }) + await store.people.moveToPerson(`person:${await uidOf(store, "email", "noreply@shop.ru")}`, "owner") + await resort(store, db) + + expect(memberships(db)).toEqual([]) + expect(holdings(db).map(({ name, address }) => `${name} ${address}`)).toEqual(["Studio noreply@studio.ru"]) +}) + +it("changes nothing when it runs again", async () => { + const { store, db } = await opened() + await store.people.savePeople(MAIL, [ + { id: "noreply@studio.ru", name: "Studio" }, + { id: "info@studio.ru", name: "Studio Team" }, + { id: "lena@studio.ru", name: "Lena Marsh" }, + ]) + await sorted(store) + const rows = () => ({ + organizations: db.prepare("SELECT * FROM organizations").all(), + holdings: db.prepare("SELECT * FROM organization_identities").all(), + links: db.prepare("SELECT * FROM links").all(), + bots: db.prepare("SELECT * FROM sender_bots").all(), + }) + const before = rows() + + await resort(store, db) + + expect(rows()).toEqual(before) + expect(db.prepare("SELECT count(*) AS n FROM persons WHERE kind IS NULL").get()?.n).toBe(0) +}) diff --git a/src/store/people-list.test.ts b/src/store/people-list.test.ts index 2f566b41d..a0ba0a974 100644 --- a/src/store/people-list.test.ts +++ b/src/store/people-list.test.ts @@ -294,7 +294,7 @@ describe("the kind of a person", () => { "ООО «Ромашка»": ["organization", "company-name"], Kai: ["person", "chat"], Orders: ["automated", "no-reply"], - Reception: ["organization", "role-address"], + Reception: ["organization", "organization", "role-address"], "Mia Holt": ["stranger", "no-tie"], }) }) diff --git a/src/store/sqlite/domain-organizations.ts b/src/store/sqlite/domain-organizations.ts new file mode 100644 index 000000000..2735bbae9 --- /dev/null +++ b/src/store/sqlite/domain-organizations.ts @@ -0,0 +1,270 @@ +import { disposableEmailBlocklistSet } from "disposable-email-domains-js" +import { getDomainWithoutSuffix } from "tldts" +import { isReadable } from "../../domain/display-names.js" +import { isCompanyName } from "../../domain/person-kinds.js" +import { FREE_MAIL, registrableOf } from "../../mail/score.js" +import type { CacheDatabase } from "../driver.js" +import { fold } from "../normalize.js" +import { actorOfOrigin } from "./actors.js" +import { linkKind } from "./link-kinds.js" + +/** + * Newsletter hosts and mail services that send for many customers. Their domain names none of the senders, so it never + * makes an organization; the bounce and signing domains are here for mail whose `From` carries them. + */ +export const SENDING_PLATFORMS: ReadonlySet = new Set([ + "substack.com", + "beehiiv.com", + "ghost.io", + "buttondown.email", + "buttondown.com", + "mailchimpapp.net", + "mcsv.net", + "mcdlv.net", + "rsgsv.net", + "list-manage.com", + "mandrillapp.com", + "sendgrid.net", + "amazonses.com", + "mailgun.org", + "mailgun.net", + "postmarkapp.com", + "mtasv.net", + "sparkpostmail.com", + "convertkit-mail.com", + "mlsend.com", + "sendinblue.com", + "brevosend.com", +]) + +/** How a rule's hold on an address is marked in `organization_identities.method`. */ +export const BY_DOMAIN = "domain" +/** A rejected `proposed_actions` row of this kind keeps a rule from making an organization for its domain again. */ +export const REFUSED_DOMAIN = "organization-domain" + +let disposable: Set | undefined +// `isDisposableEmailDomain` builds the whole set on every call: about 0.5 ms an address. +const isDisposable = (domain: string): boolean => { + disposable ??= disposableEmailBlocklistSet() + return disposable.has(domain) +} + +/** The registrable domain whose organization an address joins; none for free, throwaway and platform mail. */ +export const companyDomainOf = (address: string): string | undefined => { + if (!address.includes("@")) return undefined + const domain = registrableOf(address) + return domain.includes(".") && !FREE_MAIL.has(domain) && !SENDING_PLATFORMS.has(domain) && !isDisposable(domain) + ? domain + : undefined +} + +/** + * A person as the kind pass leaves them: `holds` for a bot or a shared mailbox, whose addresses the organization owns; + * never for one the owner kept as a person. + */ +export interface Sorted { + id: number + displayName: string | null + holds: boolean +} + +const nameFor = (shown: string | null, domain: string): string => { + const label = getDomainWithoutSuffix(domain) + return shown !== null && + isReadable(shown) && + (isCompanyName(shown) || (label !== null && fold(shown).trim() === fold(label))) + ? shown.trim() + : domain +} + +const mailOf = (database: CacheDatabase, people: readonly number[]) => { + const found = new Map() + for (const row of database + .prepare( + "SELECT l.person_id AS person, i.id, lower(i.external_id) AS address FROM identity_links l " + + "JOIN identities i ON i.id = l.identity_id WHERE i.provider = 'email' " + + "AND l.person_id IN (SELECT value FROM json_each(?)) ORDER BY i.id", + ) + .all(JSON.stringify(people))) { + const domain = companyDomainOf(String(row.address)) + if (domain === undefined) continue + const person = Number(row.person) + found.set(person, [...(found.get(person) ?? []), { identity: Number(row.id), domain }]) + } + return found +} + +/** Every organization by the company domains of the addresses it holds, and which identities are held at all. */ +const holdersOf = (database: CacheDatabase) => { + const byDomain = new Map>() + const held = new Map() + for (const row of database + .prepare( + "SELECT oi.identity_id, oi.organization_id, lower(i.external_id) AS address FROM organization_identities oi " + + "JOIN organizations o ON o.id = oi.organization_id JOIN identities i ON i.id = oi.identity_id " + + "WHERE o.deleted_at IS NULL AND i.provider = 'email' ORDER BY oi.id", + ) + .all()) { + const organization = Number(row.organization_id) + if (!held.has(Number(row.identity_id))) held.set(Number(row.identity_id), organization) + const domain = companyDomainOf(String(row.address)) + if (domain !== undefined) byDomain.set(domain, (byDomain.get(domain) ?? new Set()).add(organization)) + } + return { byDomain, held } +} + +const refusedDomains = (database: CacheDatabase): Set => + new Set( + database + .prepare( + "SELECT json_extract(payload, '$.domain') AS domain FROM proposed_actions WHERE kind = ? AND status = 'rejected'", + ) + .all(REFUSED_DOMAIN) + .map((row) => String(row.domain)), + ) + +/** Person → organization pairs the owner removed: a rule never links them again. */ +const removedMemberships = (database: CacheDatabase): Set => + new Set( + database + .prepare( + "SELECT target_id, json_extract(payload, '$.to') AS target FROM proposed_actions WHERE kind = 'relationship' " + + "AND status = 'rejected' AND target_type = 'person' AND json_extract(payload, '$.kind') = 'member-of' " + + "AND json_extract(payload, '$.to') LIKE 'organization:%'", + ) + .all() + .map((row) => `${row.target_id}>${row.target}`), + ) + +/** Humans the kind pass did not see who write from one of `domains`: a new organization takes them as members too. */ +const othersAt = (database: CacheDatabase, domains: ReadonlySet, seen: ReadonlySet) => { + const found = new Map() + for (const row of database + .prepare( + "SELECT l.person_id AS person, i.id, lower(i.external_id) AS address FROM identity_links l " + + "JOIN identities i ON i.id = l.identity_id JOIN persons p ON p.id = l.person_id " + + "WHERE i.provider = 'email' AND p.owner = 0 AND p.kind IS NOT NULL AND p.kind NOT IN ('test', 'merged') " + + "AND NOT EXISTS (SELECT 1 FROM sender_bots b WHERE b.person_id = p.id) " + + "AND NOT EXISTS (SELECT 1 FROM organization_identities oi WHERE oi.identity_id = i.id) ORDER BY i.id", + ) + .all()) { + const person = Number(row.person) + if (seen.has(person)) continue + const domain = companyDomainOf(String(row.address)) + if (domain === undefined || !domains.has(domain)) continue + found.set(person, [...(found.get(person) ?? []), { identity: Number(row.id), domain }]) + } + return found +} + +/** + * Plan step 5: a bot or a shared mailbox at a company domain joins that domain's organization, made when none holds + * it; a human there becomes a `member-of` it, never merged. Free mail, throwaway mail and sending platforms make none. + * The owner's word holds: a membership the owner removed and a domain whose organization the owner erased are not made + * again. The caller holds the write lock. + */ +export const groupByDomain = (database: CacheDatabase, people: readonly Sorted[], at: number): void => { + const mail = mailOf( + database, + people.map(({ id }) => id), + ) + if (mail.size === 0) return + const { byDomain, held } = holdersOf(database) + const refused = refusedDomains(database) + const created = new Set() + const create = database.prepare( + "INSERT INTO organizations (kind, name, scope, created_at, updated_at) VALUES ('company', ?, 'personal', ?, ?) " + + "RETURNING id", + ) + const hold = database.prepare( + "INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " + + `VALUES (?, ?, '${BY_DOMAIN}', 'rules', ?, ?) ON CONFLICT (identity_id, organization_id) DO NOTHING`, + ) + const sends = database.prepare( + "UPDATE sender_bots SET organization_id = ?, updated_at = ? WHERE person_id = ? AND organization_id IS NULL", + ) + const holder = (domain: string): number | undefined => { + const found = byDomain.get(domain) + return found?.size === 1 ? [...found][0] : undefined + } + for (const person of people) { + if (!person.holds) continue + for (const { identity, domain } of mail.get(person.id) ?? []) { + let organization = held.get(identity) + if (organization === undefined) { + if ((byDomain.get(domain)?.size ?? 0) > 1) continue + organization = holder(domain) + if (organization === undefined) { + if (refused.has(domain)) continue + organization = Number(create.get(nameFor(person.displayName, domain), at, at)?.id) + byDomain.set(domain, new Set([organization])) + created.add(domain) + } + hold.run(identity, organization, at, at) + held.set(identity, organization) + } + sends.run(organization, at, person.id) + } + } + const removed = removedMemberships(database) + const member = database.prepare( + "INSERT INTO links (from_type, from_id, to_type, to_id, kind, source, confirmed, author, evidence, created_at, " + + `updated_at) SELECT 'person', ?, 'organization', ?, ${linkKind("member-of")}, 'owner', 1, 'rule', ?, ?, ? ` + + "WHERE NOT EXISTS (SELECT 1 FROM links WHERE from_type = 'person' AND from_id = ? AND to_type = 'organization' " + + `AND to_id = ? AND kind = ${linkKind("member-of")})`, + ) + const join = (person: number, addresses: { identity: number; domain: string }[]) => { + for (const domain of new Set(addresses.map((one) => one.domain))) { + const organization = holder(domain) + if (organization === undefined || removed.has(`${person}>organization:${organization}`)) continue + member.run(person, organization, `writes from ${domain}`, at, at, person, organization) + } + } + const seen = new Set(people.map(({ id }) => id)) + for (const person of people) if (!person.holds) join(person.id, mail.get(person.id) ?? []) + if (created.size > 0) for (const [person, addresses] of othersAt(database, created, seen)) join(person, addresses) +} + +/** The owner erased an organization: no rule makes one for the company domains it held again. */ +export const refuseDomainsOf = (database: CacheDatabase, organization: number, at: number): void => { + const domains = new Set( + database + .prepare( + "SELECT lower(i.external_id) AS address FROM organization_identities oi JOIN identities i ON i.id = oi.identity_id " + + "WHERE oi.organization_id = ? AND i.provider = 'email'", + ) + .all(organization) + .flatMap((row) => companyDomainOf(String(row.address)) ?? []), + ) + if (domains.size === 0) return + const rule = actorOfOrigin(database, "rule") + const owner = database.prepare("SELECT id FROM persons WHERE owner = 1 ORDER BY id LIMIT 1").get() + const refuse = database.prepare( + "INSERT INTO proposed_actions (kind, payload, reason, status, proposed_by_type, proposed_by_id, decided_by_type, " + + "decided_by_id, decided_at, created_at, updated_at) VALUES (?, ?, ?, 'rejected', ?, ?, ?, ?, ?, ?, ?)", + ) + const already = refusedDomains(database) + for (const domain of [...domains].filter((one) => !already.has(one))) + refuse.run( + REFUSED_DOMAIN, + JSON.stringify({ domain }), + `the owner erased organization:${organization}`, + rule.type, + rule.id, + owner === undefined ? null : "person", + owner === undefined ? null : Number(owner.id), + owner === undefined ? null : at, + at, + at, + ) +} + +/** The owner moved these identities to a person: the holds a rule gave them go, so they read as a person's again. */ +export const releaseDomainHolds = (database: CacheDatabase, identities: readonly number[]): void => { + database + .prepare( + `DELETE FROM organization_identities WHERE method = '${BY_DOMAIN}' AND author = 'rules' ` + + "AND identity_id IN (SELECT value FROM json_each(?))", + ) + .run(JSON.stringify(identities)) +} diff --git a/src/store/sqlite/organizations.ts b/src/store/sqlite/organizations.ts index 4667d657a..f93dc36b7 100644 --- a/src/store/sqlite/organizations.ts +++ b/src/store/sqlite/organizations.ts @@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base" import { evaluate, type QueryAst, timezoneOf, walkQuery } from "@wirecat/cli-base/query" import type { Decider } from "../decisions.js" import { ORGANIZATIONS_QUERY } from "../knowledge-query.js" +import { refuseDomainsOf } from "./domain-organizations.js" import type { Organization } from "./knowledge.js" import type { StoreContext } from "./open.js" import { categorySql, type OrganizationFilter } from "./organization-categories.js" @@ -42,7 +43,12 @@ export interface OrganizationsStore { export const organizationsStoreOver = (context: StoreContext): OrganizationsStore => ({ eraseOrganization: async (organization, by, { apply }) => - write(context.database, () => eraseOrganization(context, organization, by, apply)), + write(context.database, () => { + const id = Number(/([1-9]\d*)$/u.exec(organization.trim())?.[1]) + // Read before the erase takes the addresses; kept only if the erase goes through. + if (apply && Number.isInteger(id)) refuseDomainsOf(context.database, id, context.now()) + return eraseOrganization(context, organization, by, apply) + }), ...organizationsReadsOver(context), }) diff --git a/src/store/sqlite/people-list.ts b/src/store/sqlite/people-list.ts index 131cddc7e..385541a55 100644 --- a/src/store/sqlite/people-list.ts +++ b/src/store/sqlite/people-list.ts @@ -16,6 +16,7 @@ import { } from "../../domain/person-kinds.js" import { type CacheDatabase, isQueryOnly, type SqlValue } from "../driver.js" import { fold } from "../normalize.js" +import { groupByDomain } from "./domain-organizations.js" import { mergedAwaySql } from "./merged-persons.js" import { ALWAYS_SHOWN, type ShownBecause, shownReasons } from "./person-ties.js" import { type HeldBot, ownerPeopleOf, ruleMove, SENDER_BOT_PREFIX, senderBotsOf } from "./sender-bots.js" @@ -494,7 +495,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 = "7" +const KIND_RULES = "8" 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 @@ -551,6 +552,22 @@ const keep = (database: CacheDatabase, worked: Worked[]): void => { for (const person of worked) if (person.move !== undefined && person.kind !== MERGED) ruleMove(database, person.id, person.move, person.kindSignals.join(", "), at) + const keptAsPeople = ownerPeopleOf(database) + groupByDomain( + database, + worked + .filter((person) => !person.owner && person.kind !== MERGED && person.kind !== "test") + .map((person) => ({ + id: person.id, + displayName: person.displayName, + holds: + !keptAsPeople.has(person.id) && + (person.bot !== null || + person.move === "bot" || + (person.kind === "organization" && person.kindSignals.includes("role-address"))), + })), + at, + ) const row = database.prepare( "UPDATE persons SET kind = ?, name_order = ?, messages_from = ?, task_count = ?, last_contact = ? WHERE id = ?", ) diff --git a/src/store/sqlite/sender-bots.ts b/src/store/sqlite/sender-bots.ts index 662b89992..e0fdba7a9 100644 --- a/src/store/sqlite/sender-bots.ts +++ b/src/store/sqlite/sender-bots.ts @@ -1,6 +1,7 @@ import { CliError } from "@wirecat/cli-base" import type { CacheDatabase } from "../driver.js" import type { IdentityRef, PersonRecord } from "../types.js" +import { releaseDomainHolds } from "./domain-organizations.js" import { currentPerson } from "./merged-persons.js" import type { StoreContext } from "./open.js" import { isOwner, mergePerson, move, recordOf, renameAfterLeaving, required, unlinkIdentity } from "./person-links.js" @@ -243,16 +244,19 @@ export const moveToPerson = ( } if (bot !== undefined && identitiesOf(database, chosen.person).length === 0) database.prepare("DELETE FROM sender_bots WHERE id = ?").run(bot) + releaseDomainHolds(database, moving) logMoves(database, moving, from, { person: target }, log) return recordOf(context, target) } if (chosen.identity !== undefined && chosen.ref !== undefined && bot !== undefined) { const alone = Number(unlinkIdentity(context, chosen.ref, { method: "unlink", by: "owner" }).uid) + releaseDomainHolds(database, [chosen.identity]) logMoves(database, [chosen.identity], from, { person: alone }, log) return recordOf(context, alone) } if (bot !== undefined) database.prepare("DELETE FROM sender_bots WHERE id = ?").run(bot) const moving = chosen.identity === undefined ? identitiesOf(database, chosen.person) : [chosen.identity] + releaseDomainHolds(database, moving) logMoves(database, moving, from, { person: chosen.person }, log) return recordOf(context, chosen.person) }) From 7b391303a4ccb1756ca97076182453c592e0cac9 Mon Sep 17 00:00:00 2001 From: leemour Date: Wed, 25 Nov 2026 05:12:31 +0100 Subject: [PATCH 2/2] feat(people): mark domain memberships as derived from the mail domain Co-Authored-By: Claude Opus 5.5 --- src/store/domain-organizations.test.ts | 1 + src/store/sqlite/domain-organizations.ts | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/store/domain-organizations.test.ts b/src/store/domain-organizations.test.ts index ab07b7fef..83ddb38d6 100644 --- a/src/store/domain-organizations.test.ts +++ b/src/store/domain-organizations.test.ts @@ -141,6 +141,7 @@ it("keeps the owner's separations: a removed membership, an erased organization, await sorted(store) const lena = await uidOf(store, "email", "lena@studio.ru") const [relation] = (await store.knowledge.relations(null, `person:${lena}`)).filter((one) => one.kind === "member-of") + expect(relation).toMatchObject({ derived: "mail-domain" }) await store.knowledge.removeRelation(null, String(relation?.id), "owner") const bank = Number(db.prepare("SELECT id FROM organizations WHERE name = 'Bank'").get()?.id) diff --git a/src/store/sqlite/domain-organizations.ts b/src/store/sqlite/domain-organizations.ts index 2735bbae9..409d71d0f 100644 --- a/src/store/sqlite/domain-organizations.ts +++ b/src/store/sqlite/domain-organizations.ts @@ -208,8 +208,9 @@ export const groupByDomain = (database: CacheDatabase, people: readonly Sorted[] } const removed = removedMemberships(database) const member = database.prepare( - "INSERT INTO links (from_type, from_id, to_type, to_id, kind, source, confirmed, author, evidence, created_at, " + - `updated_at) SELECT 'person', ?, 'organization', ?, ${linkKind("member-of")}, 'owner', 1, 'rule', ?, ?, ? ` + + "INSERT INTO links (from_type, from_id, to_type, to_id, kind, source, confirmed, author, evidence, metadata, " + + `created_at, updated_at) SELECT 'person', ?, 'organization', ?, ${linkKind("member-of")}, 'owner', 1, 'rule', ?, ` + + `'{"derived":"mail-domain"}', ?, ? ` + "WHERE NOT EXISTS (SELECT 1 FROM links WHERE from_type = 'person' AND from_id = ? AND to_type = 'organization' " + `AND to_id = ? AND kind = ${linkKind("member-of")})`, )