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
4 changes: 4 additions & 0 deletions THIRD_PARTY_NOTICES
Original file line number Diff line number Diff line change
Expand Up @@ -802,3 +802,7 @@ SPDX-License-Identifier: Unicode-3.0

EmbeddingGemma (Google) is used under the Gemma Terms of Use, https://ai.google.dev/gemma/terms, including its use
restrictions (https://ai.google.dev/gemma/prohibited_use_policy).

The domain-to-sector table (src/domain/organization-sectors.generated.ts) is built from Wikidata
(https://www.wikidata.org), whose structured data is available under CC0 1.0
(https://creativecommons.org/publicdomain/zero/1.0/). The export date is in the file's header.
2 changes: 1 addition & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,7 @@
}
},
{
"includes": ["src/domain/phone-plans.generated.ts"],
"includes": ["src/domain/phone-plans.generated.ts", "src/domain/organization-sectors.generated.ts"],
"linter": {
"rules": {
"security": {
Expand Down
8 changes: 8 additions & 0 deletions changes/feat-organization-categories.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
### Added

- **An organization says what it does: `Organization.sector`.** An organization holding a company mail domain gets
`bank`, `airline`, `shop`, `news`, `government`, `telecom`, `social`, `delivery` or `financial` from a table of
domains built into the package from Wikidata (CC0), so no sender is looked up online. It is stored in the
organization's `metadata.sector`; free mail and sending platforms never give one. The first list after the
upgrade sets it for the organizations already stored
([ARCHITECTURE](../docs/dev/ARCHITECTURE.md#entities-and-source-records)).
7 changes: 6 additions & 1 deletion docs/dev/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -715,7 +715,12 @@ proposes them instead. A no-reply address (`isNoReplyAddress`) is no one's: it n
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;
ungrouped. Each organization holding a company domain takes that domain's `metadata.sector` (`Organization.sector`:
`airline`, `bank`, `financial`, `telecom`, `social`, `shop`, `delivery`, `news`, `government`; the first in that
order when its domains differ), from `src/domain/organization-sectors.generated.ts`. That table is built into the
package at release by `scripts/organization-sectors.ts` from the official websites (P856) of Wikidata items (CC0),
so nothing is looked up per sender. A sector is what an organization does; `Category` (client, supplier, …) is what
it is to the owner. 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;
Expand Down
2 changes: 1 addition & 1 deletion docs/storage/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ CREATE VIRTUAL TABLE identities_fts USING fts5(name, username, content='identiti

### `organizations`

A company, team, family or community the owner deals with. Projects, work accounts and people's identities belong to one.
A company, team, family or community the owner deals with. Projects, work accounts and people's identities belong to one. `metadata.sector` says what it does (`bank`, `airline`, `shop`, …), set from the company domains it holds and the Wikidata list built into the package.

| Column | Type | Constraints | References | Meaning |
|---|---|---|---|---|
Expand Down
173 changes: 173 additions & 0 deletions scripts/organization-sectors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
// Writes src/domain/organization-sectors.generated.ts: registrable domain → sector, from the official websites (P856)
// of Wikidata items (CC0). Run at release, never at run time: a lookup per sender would tell a third party who writes
// to the owner. The query sends only class ids.
// Run: node --experimental-strip-types scripts/organization-sectors.ts && pnpm exec biome check --write src/domain/organization-sectors.generated.ts
import { writeFileSync } from "node:fs"
import { parse } from "tldts"

const ENDPOINT = "https://query.wikidata.org/sparql"
const OUT = new URL("../src/domain/organization-sectors.generated.ts", import.meta.url)
const USER_AGENT = "WireCat-build/1.0 (https://github.com/WireCatLabs/cli-core)"

// Most specific first: a domain several sectors claim takes the first. `tree`: the class with its subclasses;
// `direct`: its own instances only, since government agency's subclasses take in about 50,000 towns. `notable`: the
// fewest Wikipedia and sister-site pages an item needs, which keeps the long tail of local papers and agencies out of
// the package (all three together were about 90,000 domains, 1.6 MB, on 2026-11-25).
const CLASSES: Record<string, { tree: string[]; direct?: string[]; notable?: number }> = {
airline: { tree: ["Q46970"] },
bank: { tree: ["Q22687"] },
financial: { tree: ["Q2143354", "Q1956140", "Q25401607", "Q11691", "Q650241"] },
telecom: { tree: ["Q2401749", "Q1941618", "Q11371"] },
social: { tree: ["Q3220391"] },
shop: { tree: ["Q4382945", "Q3390477", "Q507619", "Q18043413", "Q216107"], notable: 2 },
delivery: { tree: ["Q1529128"] },
news: { tree: ["Q1193236", "Q11032", "Q192283", "Q17232649", "Q1153191", "Q15265344", "Q2001305"], notable: 3 },
government: { tree: ["Q192350", "Q573607"], direct: ["Q327333"], notable: 2 },
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

class TooBig extends Error {}

interface Row {
item: string
url: string
links: number
}

const sparql = async (query: string): Promise<Record<string, { value: string }>[]> => {
for (let attempt = 1; ; attempt++) {
const response = await fetch(ENDPOINT, {
method: "POST",
headers: {
"User-Agent": USER_AGENT,
Accept: "application/sparql-results+json",
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({ query }),
signal: AbortSignal.timeout(90_000),
}).catch((error: unknown) => {
if (error instanceof Error && error.name === "TimeoutError") throw new TooBig()
throw error
})
if (response.status === 429 && attempt < 6) {
await sleep(Number(response.headers.get("retry-after") ?? 60) * 1000)
continue
}
const text = await response.text()
// The service cuts a query at 60 s; it answers 500 with a Java TimeoutException, or a broken JSON body.
if (response.status === 500 && text.includes("TimeoutException")) throw new TooBig()
// A gateway error is a query the proxy gave up on, or a busy server: try again, then split.
if ([502, 503, 504].includes(response.status)) {
if (attempt >= 3) throw new TooBig()
await sleep(10_000 * attempt)
continue
}
if (!response.ok) throw new Error(`Wikidata answered ${response.status}`)
try {
return (JSON.parse(text) as { results: { bindings: Record<string, { value: string }>[] } }).results.bindings
} catch {
throw new TooBig()
}
}
}

// The best-ranked website (preferred if any, else normal), no end date, of an item not dissolved. Only preferred
// statements would keep 227 of about 3,800 banks (2026-11-25).
const websites = (match: string, notable: number) =>
`SELECT ?item ?url ?links WHERE { ${match} ?item wikibase:sitelinks ?links . FILTER(?links >= ${notable}) ` +
"?item p:P856 ?st . ?st ps:P856 ?url ; a wikibase:BestRank . " +
"FILTER NOT EXISTS { ?st pq:P582 [] } FILTER NOT EXISTS { ?item wdt:P576 [] } }"

const subclassesOf = async (id: string) =>
(await sparql(`SELECT ?sub WHERE { ?sub wdt:P279 wd:${id} }`)).map(
(row) => (row.sub?.value ?? "").split("/").pop() ?? "",
)

const rowOf = (row: Record<string, { value: string }>): Row => ({
item: row.item?.value ?? "",
url: row.url?.value ?? "",
links: Number(row.links?.value ?? 0),
})

const seen = new Set<string>()
/** Instances of `id` and its subclasses; a query too big for the 60 s limit is split into each direct subclass. */
const instancesOf = async (id: string, notable: number): Promise<Row[]> => {
if (seen.has(id)) return []
await sleep(1000)
try {
const rows = await sparql(websites(`?item wdt:P31/wdt:P279* wd:${id} .`, notable))
seen.add(id)
return rows.map(rowOf)
} catch (error) {
if (!(error instanceof TooBig)) throw error
console.error(`${id}: too big, split by subclass`)
seen.add(id)
const direct = await sparql(websites(`?item wdt:P31 wd:${id} .`, notable))
const found = direct.map(rowOf)
for (const sub of await subclassesOf(id)) found.push(...(await instancesOf(sub, notable)))
return found
}
}

// A home page, or one in a language folder (`/en`, `/es-es/`), on the domain itself or `www`. A deeper path is a page
// on someone else's site: a bank's Facebook page would make facebook.com a bank.
const HOME = /^\/?([a-z]{2}([-_][a-z]{2})?\/?)?(index\.html?)?$/iu

/** The registrable domain as `registrableOf` reads mail (ICANN suffixes only); none under a shared host. */
const domainOf = (url: string): string | undefined => {
let path: string
try {
path = new URL(url).pathname
} catch {
return undefined
}
if (!HOME.test(path)) return undefined
const icann = parse(url)
if (icann.isIp || icann.domain === null) return undefined
// tv.youtube.com, apps.microsoft.com, a blog on wordpress.com: a product or a tenant of a bigger site, not its owner.
if (icann.subdomain !== "" && icann.subdomain !== "www") return undefined
// blogspot.com, github.io, …: the private part of the Public Suffix List; the domain is the host's, not the owner's.
if (parse(url, { allowPrivateDomains: true }).domain !== icann.domain) return undefined
return icann.domain.toLowerCase()
}

const claims = new Map<string, Set<string>>()
const counts: Record<string, number> = {}
for (const [sector, { tree, direct = [], notable = 0 }] of Object.entries(CLASSES)) {
seen.clear()
const rows: Row[] = []
for (const id of tree) rows.push(...(await instancesOf(id, notable)))
for (const id of direct) {
await sleep(1000)
rows.push(...(await sparql(websites(`?item wdt:P31 wd:${id} .`, notable))).map(rowOf))
}
const items = new Set(rows.map(({ item }) => item))
for (const { url } of rows) {
const domain = domainOf(url)
if (domain !== undefined) claims.set(domain, (claims.get(domain) ?? new Set()).add(sector))
}
counts[sector] = items.size
console.error(`${sector}: ${items.size} items`)
}

const order = Object.keys(CLASSES)
const table = new Map(order.map((sector) => [sector, [] as string[]]))
for (const [domain, sectors] of claims) {
// Three sectors on one domain is a group or a host, not a sector.
if (sectors.size >= 3) continue
const sector = order.find((one) => sectors.has(one))
if (sector !== undefined) table.get(sector)?.push(domain)
}

const date = new Date().toISOString().slice(0, 10)
writeFileSync(
OUT,
`// Generated by scripts/organization-sectors.ts from Wikidata on ${date}; do not edit by hand.\n` +
"// Wikidata data is CC0 1.0 (https://creativecommons.org/publicdomain/zero/1.0/): official websites (P856).\n" +
"// Each value is the registrable domains of that sector, sorted, one space between.\n" +
"export const SECTOR_DOMAINS = {\n" +
[...table].map(([sector, domains]) => ` ${sector}: "${domains.sort().join(" ")}",\n`).join("") +
"} as const\n",
)
for (const [sector, domains] of table)
console.error(`${sector}: ${domains.length} domains from ${counts[sector]} items`)
2 changes: 1 addition & 1 deletion scripts/schema/spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ const NEW = {
actors: [
{
name: "organizations",
doc: "A company, team, family or community the owner deals with. Projects, work accounts and people's identities belong to one.",
doc: "A company, team, family or community the owner deals with. Projects, work accounts and people's identities belong to one. `metadata.sector` says what it does (`bank`, `airline`, `shop`, …), set from the company domains it holds and the Wikidata list built into the package.",
cols: [
id(),
c("kind", "text", { notnull: true, note: "company, team, family, community" }),
Expand Down
20 changes: 20 additions & 0 deletions src/domain/organization-sectors.generated.ts

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions src/domain/organization-sectors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { getDomain } from "tldts"
import { expect, it } from "vitest"
import { SECTOR_DOMAINS } from "./organization-sectors.generated.js"
import { SECTORS } from "./organization-sectors.js"

const all = SECTORS.flatMap((sector) => SECTOR_DOMAINS[sector].split(" "))

it("holds each registrable domain once, in lower case, as mail is read", () => {
expect(new Set(all).size).toBe(all.length)
expect(all.filter((domain) => getDomain(domain) !== domain || domain !== domain.toLowerCase())).toEqual([])
})
19 changes: 19 additions & 0 deletions src/domain/organization-sectors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { SECTOR_DOMAINS } from "./organization-sectors.generated.js"

/**
* What an organization does (a bank, an airline, a shop), from the websites Wikidata lists, built into the package by
* `scripts/organization-sectors.ts`. Apart from `Category`, which says what an organization is to the owner.
*/
export type Sector = keyof typeof SECTOR_DOMAINS
/** Most specific first: an organization holding domains of two sectors takes the first. */
export const SECTORS = Object.keys(SECTOR_DOMAINS) as Sector[]

let sectors: Map<string, Sector> | undefined

/** The sector of a registrable domain, lower case as `registrableOf` gives it. */
export const sectorOfDomain = (domain: string): Sector | undefined => {
sectors ??= new Map(
SECTORS.flatMap((sector) => SECTOR_DOMAINS[sector].split(" ").map((one): [string, Sector] => [one, sector])),
)
return sectors.get(domain)
}
11 changes: 10 additions & 1 deletion src/entities/entities.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,15 @@ const samples: Record<EntityName, unknown> = {
since: null,
},
stage: { ...stageSample, pipeline: "pipeline:2", pipeline_name: "Sales", kind: "deal" },
organization: { id: "1", ref: "organization:1", kind: "company", name: "Sample", scope: "work", created_at: at },
organization: {
id: "1",
ref: "organization:1",
kind: "company",
name: "Sample",
scope: "work",
sector: "bank",
created_at: at,
},
project: {
id: "1",
ref: "project:1",
Expand Down Expand Up @@ -355,6 +363,7 @@ const samples: Record<EntityName, unknown> = {
kind: "company",
name: "Sample LLC",
scope: "work",
sector: null,
created_at: at,
own: false,
},
Expand Down
2 changes: 2 additions & 0 deletions src/entities/knowledge-lists.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as v from "valibot"
import { SECTORS } from "../domain/organization-sectors.js"
import { id, reference, text, time } from "./fields.js"

/** @experimental */
Expand All @@ -8,6 +9,7 @@ export const organization = v.strictObject({
kind: v.picklist(["company", "team", "family", "community"]),
name: text,
scope: v.picklist(["personal", "work"]),
sector: v.nullable(v.picklist(SECTORS)),
created_at: time,
})
/** @experimental */
Expand Down
28 changes: 28 additions & 0 deletions src/store/domain-organizations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,31 @@ it("changes nothing when it runs again", async () => {
expect(rows()).toEqual(before)
expect(db.prepare("SELECT count(*) AS n FROM persons WHERE kind IS NULL").get()?.n).toBe(0)
})

it("gives an organization the sector of its domain from the Wikidata list, and none for free mail", async () => {
const { store, db } = await opened()
await store.people.savePeople(MAIL, [
{ id: "noreply@mail.hsbc.com", name: "HSBC" },
{ id: "info@studio.ru", name: "Studio" },
{ id: "boss@mail.ru", name: "Boss" },
])
await sorted(store)
const club = await store.knowledge.addOrganization({ kind: "company", name: "Club" })
const freeMail = db.prepare("SELECT id FROM identities WHERE external_id = 'boss@mail.ru'").get()?.id
db.prepare(
"INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
"VALUES (?, ?, 'owner', 'owner', 0, 0)",
).run(Number(freeMail), Number(club.id))

await resort(store, db)

const sectors = (await store.knowledge.organizations()).map(({ name, sector }) => ({ name, sector }))
expect(sectors).toEqual([
{ name: "Club", sector: null },
{ name: "HSBC", sector: "bank" },
{ name: "Studio", sector: null },
])
const before = db.prepare("SELECT * FROM organizations").all()
await resort(store, db)
expect(db.prepare("SELECT * FROM organizations").all()).toEqual(before)
})
20 changes: 20 additions & 0 deletions src/store/sqlite/domain-organizations.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getDomainWithoutSuffix } from "tldts"
import { isReadable } from "../../domain/display-names.js"
import { SECTORS, sectorOfDomain } from "../../domain/organization-sectors.js"
import { isCompanyName } from "../../domain/person-kinds.js"
import { FREE_MAIL, isDisposableDomain, registrableOf } from "../../mail/score.js"
import type { CacheDatabase } from "../driver.js"
Expand Down Expand Up @@ -152,6 +153,7 @@ const othersAt = (database: CacheDatabase, domains: ReadonlySet<string>, seen: R
/**
* 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.
* An organization holding a domain of the built-in Wikidata list gets its `metadata.sector`.
* 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.
*/
Expand Down Expand Up @@ -216,6 +218,24 @@ export const groupByDomain = (database: CacheDatabase, people: readonly Sorted[]
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)
setSectors(database, byDomain, at)
}

/** Each organization holding a company domain takes that domain's sector, the first in `SECTORS` order if several. */
const setSectors = (database: CacheDatabase, byDomain: ReadonlyMap<string, ReadonlySet<number>>, at: number) => {
const found = new Map<number, number>()
for (const [domain, organizations] of byDomain) {
const sector = sectorOfDomain(domain)
if (sector === undefined) continue
const rank = SECTORS.indexOf(sector)
for (const organization of organizations)
if (rank < (found.get(organization) ?? SECTORS.length)) found.set(organization, rank)
}
const set = database.prepare(
"UPDATE organizations SET metadata = json_set(coalesce(metadata, '{}'), '$.sector', ?), updated_at = ? " +
"WHERE id = ? AND deleted_at IS NULL AND json_extract(metadata, '$.sector') IS NOT ?",
)
for (const [organization, rank] of found) set.run(SECTORS[rank] ?? null, at, organization, SECTORS[rank] ?? null)
}

/** The owner erased an organization: no rule makes one for the company domains it held again. */
Expand Down
11 changes: 2 additions & 9 deletions src/store/sqlite/knowledge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { idsOf } from "./merged-persons.js"
import { holdingText } from "./note-index.js"
import { hasBothEnds, insertLink, type Link, linkOf } from "./notes.js"
import type { StoreContext } from "./open.js"
import { type OrganizationsStore, organizationOf, organizationsStoreOver } from "./organizations.js"
import { type Organization, type OrganizationsStore, organizationOf, organizationsStoreOver } from "./organizations.js"
import type { ProposedAction } from "./proposed-actions.js"
import { type ColumnMap, queryFilter } from "./query-filter.js"
import {
Expand Down Expand Up @@ -97,14 +97,7 @@ export const ORGANIZATION_KINDS = ["company", "team", "family", "community"] as
export const PROJECT_TYPES = ["work", "client", "personal", "oss", "other"] as const
export const SCOPES = ["personal", "work"] as const

export interface Organization {
id: string
ref: string
kind: (typeof ORGANIZATION_KINDS)[number]
name: string
scope: (typeof SCOPES)[number]
createdAt: string
}
export type { Organization } from "./organizations.js"

export interface Project {
id: string
Expand Down
Loading
Loading