Cotton code
152 lines · 10.3 KB · TypeScriptRaw
/** * The calendar engine's kinds (src/calendar_engine.ts, through the object's * classifier, src/classify.ts): an event's words against the kit's * exemplars, through an embedder that is a fake here (test/fake_embedder.ts) * — each exemplar phrase its kind's own axis, each event's words a vector set * at the score the case needs — so a case says exactly what the model would * have scored. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import type { Business } from "../src/business.ts";import { Store } from "../src/store.ts";import { Fake } from "./fake_embedder.ts";import { EVENTS_OPEN, http, personalObject, PERSONAL_TABLES, PEOPLE_OPEN } from "./personal.ts";const EVENT_DEF = PERSONAL_TABLES.find((t) => t.id === "event")!;const KIND = (EVENT_DEF.columns as Record<string, unknown>[]).find((c) => c.key === "kind")! as { choices: string[]; examples: Record<string, string[]>; families: Record<string, string> };const near = (kind: string, score: number) => Fake.near(KIND, kind, score);const fakeOf = (words: Record<string, number[]>) => new Fake(KIND, words);const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));async function pass(slug: string, fake: Fake) {  return runInDurableObject(stub(slug), (instance: Business) => instance.calendarPass(fake));}async function event(slug: string, id: string): Promise<Record<string, unknown>> {  return runInDurableObject(stub(slug), (_i, state) => new Store(state.storage.sql, () => new Date()).get("event", id)!.data);}async function write(slug: string, credential: string, act: "create" | "update", args: Record<string, unknown>): Promise<string> {  const res = await http<{ made?: { id: string } }>(slug, "POST", "/v1/act", { act, args }, { authorization: `Bearer ${credential}` });  expect(res.status, JSON.stringify(res.body)).toBe(200);  return res.body.made?.id ?? String(args.id);}const made = (slug: string, credential: string, data: Record<string, unknown>) => write(slug, credential, "create", { table: "event", data: { starts_at: "2026-11-02T07:00:00.000Z", ...data } });describe("the calendar engine's kinds", () => {  it("writes the nearest member, a family when only the family is sure, and leaves an event it is unsure of empty and unasked", async () => {    const { credential } = await personalObject("kinds-near", { open: [...EVENTS_OPEN.open, ...PEOPLE_OPEN.open] });    const gym = await made("kinds-near", credential, { title: "Gym at 7" });    const meal = await made("kinds-near", credential, { title: "Supper somewhere" });    const none = await made("kinds-near", credential, { title: "Project Aurora" });    const fake = fakeOf({ "Gym at 7": near("gym", 0.83), "Supper somewhere": near("dinner", 0.68), "Project Aurora": near("class", 0.55) });    const answer = await pass("kinds-near", fake);    expect(answer).toMatchObject({ kinded: 2, unsure: 1, more: false });    expect((await event("kinds-near", gym)).kind).toBe("gym");    expect((await event("kinds-near", meal)).kind).toBe("meal");    expect((await event("kinds-near", none)).kind).toBeUndefined();    const exemplars = fake.asked.length - 3;    expect(exemplars).toBe(Object.values(KIND.examples).flat().length);    // The next pass asks nothing: the exemplars are kept, and every event was judged as it stands.    const again = fakeOf(fake.words);    expect(await pass("kinds-near", again)).toMatchObject({ kinded: 0, unsure: 0 });    expect(again.asked).toEqual([]);  });  it("never writes over a kind a person gave, and fills one a person cleared", async () => {    const { credential } = await personalObject("kinds-person", { open: [...EVENTS_OPEN.open, ...PEOPLE_OPEN.open] });    const given = await made("kinds-person", credential, { title: "Gym at 7", kind: "dinner" });    const fake = fakeOf({ "Gym at 7": near("gym", 0.9) });    await pass("kinds-person", fake);    expect((await event("kinds-person", given)).kind).toBe("dinner");    expect(fake.asked.filter((t) => t === "Gym at 7")).toEqual([]);    // The engine's own kind, changed by the person: the next pass leaves the person's.    const judged = await made("kinds-person", credential, { title: "Gym at 7" });    await pass("kinds-person", fake);    expect((await event("kinds-person", judged)).kind).toBe("gym");    await write("kinds-person", credential, "update", { table: "event", id: judged, data: { kind: "dinner" } });    await pass("kinds-person", fake);    expect((await event("kinds-person", judged)).kind).toBe("dinner");    // Cleared, it is judged again.    await write("kinds-person", credential, "update", { table: "event", id: judged, data: { kind: null } });    await pass("kinds-person", fake);    expect((await event("kinds-person", judged)).kind).toBe("gym");  });  it("judges a series by its master alone, and its moved occurrence takes the master's kind and follows it until a person writes its own", async () => {    const { credential } = await personalObject("kinds-series", { open: [...EVENTS_OPEN.open, ...PEOPLE_OPEN.open] });    const master = await made("kinds-series", credential, { title: "Leg day weekly", rrule: "FREQ=WEEKLY" });    const moved = await made("kinds-series", credential, { title: "Leg day weekly (moved)", series_id: master, original_starts_at: "2026-11-09T07:00:00.000Z" });    const fake = fakeOf({ "Leg day weekly": near("gym", 0.8), "Leg day weekly (moved)": near("dinner", 0.95) });    await pass("kinds-series", fake);    expect(fake.asked).not.toContain("Leg day weekly (moved)");    expect((await event("kinds-series", master)).kind).toBe("gym");    expect((await event("kinds-series", moved)).kind).toBe("gym");    // The master's kind changed by a person: the occurrence the engine filled follows it.    await write("kinds-series", credential, "update", { table: "event", id: master, data: { kind: "yoga" } });    await pass("kinds-series", fake);    expect((await event("kinds-series", moved)).kind).toBe("yoga");    // An occurrence a person gave a kind of its own keeps it.    await write("kinds-series", credential, "update", { table: "event", id: moved, data: { kind: "swim" } });    await write("kinds-series", credential, "update", { table: "event", id: master, data: { kind: "run" } });    await pass("kinds-series", fake);    expect((await event("kinds-series", moved)).kind).toBe("swim");  });  it("leaves every kind as it was when the embedding fails, and fills them at the next pass", async () => {    const { credential } = await personalObject("kinds-fail", { open: [...EVENTS_OPEN.open, ...PEOPLE_OPEN.open] });    const gym = await made("kinds-fail", credential, { title: "Gym at 7" });    const fake = fakeOf({ "Gym at 7": near("gym", 0.83) });    fake.fail = true;    const answer = await pass("kinds-fail", fake);    expect(answer?.failed).toMatch(/down/);    expect(answer?.kinded).toBe(0);    expect((await event("kinds-fail", gym)).kind).toBeUndefined();    fake.fail = false;    expect(await pass("kinds-fail", fake)).toMatchObject({ kinded: 1 });    expect((await event("kinds-fail", gym)).kind).toBe("gym");  });});describe("the calendar engine's people", () => {  async function person(slug: string, credential: string, name: string, handle: { kind: "email" | "phone"; value: string; normalised: string }): Promise<string> {    const id = await write(slug, credential, "create", { table: "person", data: { full_name: name } });    await write(slug, credential, "create", { table: "person_handle", data: { person_id: id, ...handle, source: "manual", position: 0 } });    return id;  }  const attendee = (slug: string, credential: string, event: string, data: Record<string, unknown>) =>    write(slug, credential, "create", { table: "event_attendee", data: { event_id: event, response: "needs_action", ...data } });  it("links an attendee a person's handle names, and makes nobody up for one that names nobody", async () => {    const { credential } = await personalObject("people-two", { open: [...EVENTS_OPEN.open, ...PEOPLE_OPEN.open] });    const asha = await person("people-two", credential, "Invented Asha", { kind: "email", value: "Asha@Example.test", normalised: "asha@example.test" });    const dinner = await made("people-two", credential, { title: "Dinner with friends", organizer_is_self: false });    await attendee("people-two", credential, dinner, { email: "ASHA@example.test", display_name: "Asha" });    await attendee("people-two", credential, dinner, { email: "stranger@example.test", display_name: "Invented Stranger" });    await pass("people-two", fakeOf({}));    expect((await event("people-two", dinner)).people).toEqual([asha]);    const people = await runInDurableObject(stub("people-two"), (_i, state) => [...new Store(state.storage.sql, () => new Date()).scan("person")].map((p) => p.data.full_name));    expect(people).not.toContain("Invented Stranger");  });  it("links the owner to an event with guests they organised, keeps a person already there, and matches again when People gains the handle", async () => {    const { credential } = await personalObject("people-owner", { open: [...EVENTS_OPEN.open, ...PEOPLE_OPEN.open] });    const owner = await runInDurableObject(stub("people-owner"), (_i, state) => new Store(state.storage.sql, () => new Date()).meta("owner_person_id"));    expect(owner).toBeTruthy();    const kept = await person("people-owner", credential, "Invented Kept", { kind: "email", value: "kept@example.test", normalised: "kept@example.test" });    const lunch = await made("people-owner", credential, { title: "Team lunch", people: kept });    await attendee("people-owner", credential, lunch, { phone: "98450 12345", display_name: "Invented Ravi" });    const solo = await made("people-owner", credential, { title: "Gym at 7" });    await pass("people-owner", fakeOf({}));    expect((await event("people-owner", lunch)).people).toEqual([kept, owner]);    expect((await event("people-owner", solo)).people, "an event with no guests names nobody").toBeUndefined();    // Ravi's number joins People: the attendee's code-less number is read in the owner's country.    const ravi = await person("people-owner", credential, "Invented Ravi", { kind: "phone", value: "+919845012345", normalised: "919845012345" });    await pass("people-owner", fakeOf({}));    expect((await event("people-owner", lunch)).people).toEqual([kept, owner, ravi]);  });});