Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions changes/feat-organizations-from-domains.md
Original file line number Diff line number Diff line change
@@ -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.
11 changes: 11 additions & 0 deletions docs/dev/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/storage/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion scripts/schema/spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
],
Expand Down
176 changes: 176 additions & 0 deletions src/store/domain-organizations.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
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")
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)
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)
})
2 changes: 1 addition & 1 deletion src/store/people-list.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
})
})
Expand Down
Loading
Loading