/** * THE CALENDAR ENGINE IN THE OBJECT (owner, 29 Oct 2026): the typed columns * of an event the object fills itself — never a sentence. Its kind (`kind`, * filled by the object's classifier, src/classify.ts, from the kit's * exemplars on the column), and its people (`people`, the event's edges to * People). * * PEOPLE. Each of an event's attendees (`event_attendee`) is matched to a * person by the email or phone it names, through the handles People carry * (`person_handle`), as the message import matches a sender * (src/import/contacts.ts `peopleByHandle`: a number without its code read * in the owner's country, a handle two people claim is neither's). Each * person matched is added to the event's `people`; one already there stays, * and an attendee that matches nobody is no person made up. The owner (the * person the object links to the sign-in number, src/owner.ts) is linked to * an event with attendees when they organised it or are one of them. An * event is matched again when its attendees change, and every event again * when People's handles or the owner do. * * A KIND is the classifier's (src/classify.ts), with what is the calendar's * alone: a series carries its kind on its master (the row with the rule); * the phone draws each occurrence from its master's row, so a moved * occurrence (its own row, `series_id`) is never judged by its words — it * takes its master's kind while its own is empty, and follows it while * nobody has written it since. */import * as classify from"./classify.ts";import { peopleByHandle } from"./import/contacts.ts";import { handleKey, handlesFrom } from"./import/handles.ts";import { Reader } from"./import/reader.ts";import { linkedOwner } from"./owner.ts";importtype { Store } from"./store.ts";exportconst EVENT = "event";/** The column the classifier fills on an event. */exportconst KIND = "kind";/** How soon a pass that stopped at its bound carries on. */exportconst CARRY_ON_MS = 30 * 1000;/** Events matched to People in one pass. */exportconst PEOPLE_PER_PASS = 200;/** What the engine needs of the object: the classifier's host. */exporttypeCalendarHost = classify.ClassifyHost;/** The event's kind column as the classifier reads it, or null when it carries none to judge by. */exportfunction vocabulary(eventDefinition: Record<string, unknown> | undefined): classify.Vocabulary | null {return classify.vocabulary(eventDefinition, KIND);}/** * The calendar's own tables. The classifier's first home was here * (`kind_exemplars`, `kind_seen`); they went with it to src/classify.ts. */const SCHEMA = `CREATE TABLE IF NOT EXISTS people_seen (id TEXT PRIMARY KEY, version INTEGER NOT NULL, basis TEXT);DROP TABLE IF EXISTS kind_exemplars;DROP TABLE IF EXISTS kind_seen;`;function ready(host: CalendarHost): void { host.sql.exec(SCHEMA); classify.ready(host);}/** The row of `people_seen` that says what People and the owner stood at when the events were matched. */const PEOPLE_BASIS = "";const ATTENDEE = "event_attendee";/** The people job's mark among the changed rows (classify.changedAfter). */const PEOPLE_JOB = "event.people";/** The newest handle change the people job has matched against (its version only). */const PEOPLE_HANDLES = "event.people:handles";/** The inheriting job's mark among the changed rows (classify.changedAfter). */const INHERIT = "event.kind:inherit";/** A moved occurrence is its master's to kind, never judged by its words. */const LEAVE: classify.Leave = { leave: ["series_id"] };/** Whether anything since `version` touched an event: what makes a request start a pass. */exportfunction touched(store: Store, version: number): boolean {// Along rows_cursor: only the rows written since (a few). By the table's own index it read every row of the table, after every write (LIVE CPU 2, 23 Nov 2026: 50,000 events on an object of his shape).return store.query<{ n: number }>(`SELECT count(*) AS n FROM (SELECT 1 FROM rows INDEXED BY rows_cursor WHERE version > ? AND table_id IN ('${EVENT}', '${ATTENDEE}', 'person_handle') LIMIT 1)`, version)[0]!.n > 0;}/** Whether a pass has events to judge by their words. */exportfunction judging(host: CalendarHost, vocab: classify.Vocabulary | null): boolean { ready(host);return vocab !== null && classify.pending(host, vocab, LEAVE);}/** * Moved occurrences take their master's kind: one whose own is empty, and * one still holding the kind this engine gave it (nobody wrote it since) * when the master's has changed. A kind a person gave it stays. */exportfunction inherit(host: CalendarHost): number { ready(host);// AUDIT D: only the events written since this job's mark (it read every event a pass): an occurrence written since,// and the occurrences of a master written since (found by their series_id, along its lookup).const page = classify.changedAfter(host, classify.markOf(host, INHERIT));const changed = page.filter((r) => r.table_id === EVENT).map((r) => r.id);const ids = newSet<string>();if (changed.length) {for (const r of host.store.query<{ id: string; series: string | null; rule: string | null }>(`SELECT id, json_extract(data, '$.series_id') AS series, json_extract(data, '$.rrule') AS rule FROM rows WHERE table_id = '${EVENT}' AND deleted = 0 AND id IN (SELECT value FROM json_each(?))`, JSON.stringify(changed), )) {if (r.series) ids.add(r.id);elseif (r.rule) for (const o of host.store.list(EVENT, { column: "series_id", equals: r.id })) ids.add(o.id); } }const rows = ids.size ? host.store.query<{ id: string; master: string }>(`SELECT o.id AS id, json_extract(m.data, '$.kind') AS master FROM rows o JOIN rows m ON m.table_id = '${EVENT}' AND m.deleted = 0 AND m.id = json_extract(o.data, '$.series_id') LEFT JOIN classify_seen s ON s.table_id = '${EVENT}' AND s.column_key = '${KIND}' AND s.id = o.id WHERE o.table_id = '${EVENT}' AND o.deleted = 0 AND o.id IN (SELECT value FROM json_each(?)) AND COALESCE(json_extract(m.data, '$.kind'), '') != '' AND COALESCE(json_extract(o.data, '$.kind'), '') != json_extract(m.data, '$.kind') AND (COALESCE(json_extract(o.data, '$.kind'), '') = '' OR (s.wrote = json_extract(o.data, '$.kind') AND s.version = o.version))`, JSON.stringify([...ids]), ) : [];if (page.length) classify.setMark(host, INHERIT, page[page.length - 1]!);if (!rows.length) return0;return host.write((engine, version, outcome) => {let n = 0;for (const { id, master } of rows) {const row = engine.store.get(EVENT, id);if (!row) continue;const after = engine.update(row, { kind: master }, version, outcome); classify.seen(host, { table: EVENT, column: KIND }, id, after.version, master); n++; }return n; });}/** What one pass did. */exportinterfacePassAnswer {/** Events whose kind was written: by their words, or from their series' master. */ kinded: number; inherited: number;/** Events judged and left empty: nothing scored enough. */ unsure: number;/** The pass stopped at its bound with events still to judge. */ more: boolean;/** Why no event was judged, when one was due and none could be. */ failed?: string;}/** One pass of the kinds: the occurrences, the classifier's call, the occurrences again. Never throws. */exportasyncfunction passKinds(host: CalendarHost, vocab: classify.Vocabulary | null, embedder: classify.Embedder | null): Promise<PassAnswer> { ready(host);const answer: PassAnswer = { kinded: 0, inherited: inherit(host), unsure: 0, more: false };if (!vocab) return answer;const judged = await classify.classify(host, vocab, embedder, LEAVE); answer.kinded = judged.written; answer.unsure = judged.unsure; answer.more = judged.more;if (judged.failed) answer.failed = judged.failed; answer.inherited += inherit(host);return answer;}/** The ids a link value holds, one or a list, in order. */function linked(value: unknown): string[] {if (typeof value === "string" && value) return [value];returnArray.isArray(value) ? value.filter((v): v is string => typeof v === "string" && v !== "") : [];}/** Whether the owner organised an event: the column's own default (1) where the row says nothing. */function organisedByOwner(data: Record<string, unknown>): boolean {const said = data.organizer_is_self;return said === undefined || said === null || said === true || said === 1;}/** * The events whose attendees are People (see above), at most * PEOPLE_PER_PASS a pass. Answers how many events gained a person, and * whether events are left to match. */exportfunction linkPeople(host: CalendarHost): { linked: number; more: boolean } { ready(host);const { store } = host;const ownerPerson = linkedOwner(store);// What People stood at: who the owner is, and the newest handle change the walk below has met (AUDIT D: the newest// handle was found by reading every handle a pass). A handle written since starts the matching over.const start: classify.Mark = { version: -1, table_id: "", id: "" };const restart = (basis: string): void => { host.sql.exec("DELETE FROM people_seen"); host.sql.exec("INSERT INTO people_seen (id, version, basis) VALUES (?, 0, ?)", PEOPLE_BASIS, basis);// Every event matched again: the walk of changed rows starts over, a page a pass. classify.setMark(host, PEOPLE_JOB, start); };const basis = ownerPerson ?? "";const held = host.sql.exec<{ basis: string | null }>("SELECT basis FROM people_seen WHERE id = ?", PEOPLE_BASIS).toArray()[0]?.basis;if (held !== basis) restart(basis);// AUDIT D: the attendees written since this job's mark, a page at a time (it grouped every attendee row a pass).let page = classify.changedAfter(host, classify.markOf(host, PEOPLE_JOB));const handleSeen = classify.markOf(host, PEOPLE_HANDLES).version;const newestHandle = page.reduce((v, r) => (r.table_id === "person_handle" && r.version > v ? r.version : v), -1);if (newestHandle > handleSeen) { classify.setMark(host, PEOPLE_HANDLES, { version: newestHandle, table_id: "person_handle", id: "" }); restart(basis); page = classify.changedAfter(host, start); }const changed = page.filter((r) => r.table_id === ATTENDEE).map((r) => r.id);const byAttendee = newMap<string, { id: string; v: number }>();if (changed.length) {for (const a of store.query<{ aid: string; id: string; v: number }>(`SELECT a.id AS aid, json_extract(a.data, '$.event_id') AS id, a.version AS v FROM rows a WHERE a.table_id = '${ATTENDEE}' AND a.deleted = 0 AND a.id IN (SELECT value FROM json_each(?)) AND json_extract(a.data, '$.event_id') IS NOT NULL AND a.version > COALESCE((SELECT s.version FROM people_seen s WHERE s.id = json_extract(a.data, '$.event_id')), -1)`, JSON.stringify(changed), )) { byAttendee.set(a.aid, { id: a.id, v: a.v }); } }// The events in the order their attendees changed, at most PEOPLE_PER_PASS; the mark moves past what was taken.const due: { id: string; v: number }[] = [];const at = newMap<string, number>();let upTo = page.length - 1;for (let i = 0; i < page.length; i++) {const hit = page[i]!.table_id === ATTENDEE ? byAttendee.get(page[i]!.id) : undefined;if (!hit) continue;const known = at.get(hit.id);if (known !== undefined) { due[known]!.v = Math.max(due[known]!.v, hit.v);continue; }if (due.length === PEOPLE_PER_PASS) { upTo = i - 1;break; } at.set(hit.id, due.length); due.push({ ...hit }); }if (upTo >= 0) classify.setMark(host, PEOPLE_JOB, page[upTo]!);const more = upTo < page.length - 1 || page.length === classify.SCAN;if (!due.length) return { linked: 0, more };const reader = newReader(store, store.meta("owner_phone"));const people = peopleByHandle(reader);const region = reader.ownerRegion();const plans: { id: string; v: number; add: string[] }[] = [];for (const { id, v } of due.slice(0, PEOPLE_PER_PASS)) {const event = store.get(EVENT, id);if (!event) { plans.push({ id, v, add: [] });continue; }// Along the links index (event_id is a link): a JSON filter read every attendee of every event, per event.const attendees = store.list(ATTENDEE, { column: "event_id", equals: id }).slice(0, 1000);const matched: string[] = [];for (const a of attendees) {for (const handle of handlesFrom({ phone: a.data.phone as string | null, email: a.data.email as string | null }, region)) {const person = people.get(handleKey(handle));if (person && !matched.includes(person.id)) matched.push(person.id); } }if (ownerPerson && attendees.length && organisedByOwner(event.data) && !matched.includes(ownerPerson)) matched.push(ownerPerson);const have = linked(event.data.people); plans.push({ id, v, add: matched.filter((p) => !have.includes(p)) }); }const n = host.write((engine, version, outcome) => {let gained = 0;for (const plan of plans) { host.sql.exec("INSERT INTO people_seen (id, version) VALUES (?, ?) ON CONFLICT (id) DO UPDATE SET version = excluded.version", plan.id, plan.v);if (!plan.add.length) continue;const event = engine.store.get(EVENT, plan.id);if (!event) continue; engine.update(event, { people: [...linked(event.data.people), ...plan.add] }, version, outcome); gained++; }return gained; });return { linked: n, more };}/** One pass of the calendar engine: the people, then the kinds. Never throws. */exportasyncfunction pass(host: CalendarHost, vocab: classify.Vocabulary | null, embedder: classify.Embedder | null): Promise<PassAnswer & { linked: number }> {const people = linkPeople(host);const kinds = await passKinds(host, vocab, embedder);return { ...kinds, linked: people.linked, more: kinds.more || people.more };}