Cotton code
181 lines · 12.5 KB · TypeScriptRaw
import { env, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { answer, personalObject, put, refusal, TODOS_OPEN } from "./personal.ts";import planVectors from "../../../crates/cotton-rules/vectors/todo_recurrence.json";import { planOwed, readRule } from "../src/recurrence.ts";import ruleVectors from "../../../crates/cotton-rules/vectors/todo_rule.json";interface Rec {  id: string;  data: Record<string, unknown>;  updated_at: string;  deleted_at: string | null;}const DAY = 86_400_000;/** A day from today, as YYYY-MM-DD in the database's zone (Asia/Kolkata). */const day = (offset: number) => new Date(Date.now() + offset * DAY + 5.5 * 3_600_000).toISOString().slice(0, 10);/** RULE (owner, 26 Oct 2026; Days, 20 Nov 2026): a repeating todo is a series and its occurrences; the next comes when one is finished, and the series is never touched by an occurrence. */describe("repeating todos", () => {  const slug = "repeating";  let owner = "";  async function occurrences(series: string): Promise<Rec[]> {    const all = await answer<{ records: Rec[] }>(slug, owner, "list_records", { table: "todo", limit: 500 });    return all.records.filter((r) => r.data.recurrence_id === series).sort((a, b) => String(a.data.occurrence_at).localeCompare(String(b.data.occurrence_at)));  }  it("makes the series and its first occurrence from create_todo's rrule, and the next when it is done, the series untouched", async () => {    ({ owner } = await personalObject(slug, { open: TODOS_OPEN }));    const made = await answer<{ id: string; recurrenceId: string; dueDate: string; change_id: number }>(slug, owner, "create_todo", { title: "Water the plants", dueDate: day(1), dueTime: "09:00", rrule: "FREQ=DAILY" });    expect(made).toMatchObject({ dueDate: day(1), rrule: "FREQ=DAILY", change_id: expect.any(Number) });    const series = await answer<Rec>(slug, owner, "get_record_by_table", { table: "todo_recurrence", id: made.recurrenceId });    expect(series.data).toMatchObject({ title: "Water the plants", rrule: "FREQ=DAILY", paused: false });    expect((await occurrences(made.recurrenceId)).map((o) => o.id)).toEqual([made.id]);    await answer(slug, owner, "update_todo", { id: made.id, status: "done" });    const after = await occurrences(made.recurrenceId);    expect(after.map((o) => [o.data.status, o.data.due_at])).toEqual([      ["done", after[0]!.data.occurrence_at],      ["open", new Date(Date.parse(String(after[0]!.data.occurrence_at)) + DAY).toISOString()],    ]);    expect(after[1]!.data).toMatchObject({ title: "Water the plants", recurrence_id: made.recurrenceId });    const unchanged = await answer<Rec>(slug, owner, "get_record_by_table", { table: "todo_recurrence", id: made.recurrenceId });    expect(unchanged).toEqual(series);  });  /** RULE (Days, 20 Nov 2026): a repeat never stacks: an occurrence left open past its moment stays the one live copy and the alarm makes nothing beside it; done (even late) makes the next after now. */  it("keeps an overdue occurrence as the one live copy on the alarm, and makes the next after now once it is done", async () => {    const past = new Date(Date.now() - 3 * DAY).toISOString();    const ids = await put(slug, [      { ref: "series", table: "todo_recurrence", data: { title: "Stretch", rrule: "FREQ=DAILY", dtstart: past, paused: false } },      { ref: "first", table: "todo", data: { title: "Stretch", status: "open", recurrence_id: "@series", occurrence_at: past, due_at: past } },    ]);    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));    await runDurableObjectAlarm(stub);    const all = await occurrences(ids.series!);    expect(all.map((o) => [o.data.status, o.data.occurrence_at])).toEqual([["open", past]]);    await answer(slug, owner, "update_todo", { id: all[0]!.id, status: "done" });    const after = await occurrences(ids.series!);    expect(after.map((o) => o.data.status)).toEqual(["done", "open"]);    expect(Date.parse(String(after[1]!.data.occurrence_at))).toBeGreaterThan(Date.now());    expect(Date.parse(String(after[1]!.data.occurrence_at)) - Date.now()).toBeLessThanOrEqual(DAY);  });  /** RULE (Days, 20 Nov 2026): a stack the old rule left collapses on the series' next pass: the newest open occurrence stays, the earlier open ones are missed, none is deleted. */  it("collapses a stack of late open copies to its newest", async () => {    const at = (days: number) => new Date(Date.now() - days * DAY).toISOString();    const ids = await put(slug, [      { ref: "series", table: "todo_recurrence", data: { title: "Walk", rrule: "FREQ=DAILY", dtstart: at(3), paused: false, materialized_until: at(1) } },      { ref: "a", table: "todo", data: { title: "Walk", status: "open", recurrence_id: "@series", occurrence_at: at(3), due_at: at(3) } },      { ref: "b", table: "todo", data: { title: "Walk", status: "open", recurrence_id: "@series", occurrence_at: at(2), due_at: at(2) } },      { ref: "c", table: "todo", data: { title: "Walk", status: "open", recurrence_id: "@series", occurrence_at: at(1), due_at: at(1) } },    ]);    await runDurableObjectAlarm(env.BUSINESS.get(env.BUSINESS.idFromName(slug)));    const all = await occurrences(ids.series!);    expect(all.map((o) => [o.id, o.data.status])).toEqual([[ids.a, "missed"], [ids.b, "missed"], [ids.c, "open"]]);  });  it("makes a todo repeat, reshapes the series and stops it through run_act", async () => {    const plain = await answer<{ id: string }>(slug, owner, "create_todo", { title: "Pay rent", dueDate: day(5) });    const made = await answer<{ made: { table: string; id: string } }>(slug, owner, "run_act", { act: "make_todo_recurring", args: { todo: plain.id, rrule: "FREQ=MONTHLY" } });    expect(made.made.table).toBe("todo_recurrence");    const series = made.made.id;    expect((await occurrences(series)).map((o) => o.id)).toEqual([plain.id]);    expect(await refusal(slug, owner, "run_act", { act: "make_todo_recurring", args: { todo: plain.id, rrule: "FREQ=MONTHLY" } })).toBe("That todo already repeats");    expect(await refusal(slug, owner, "run_act", { act: "make_todo_recurring", args: { todo: plain.id, rrule: "FREQ=HOURLY" } })).toBe('Unsupported RRULE FREQ: "HOURLY". Allowed: DAILY, WEEKLY, MONTHLY, YEARLY');    await answer(slug, owner, "run_act", { act: "update_todo_recurrence", args: { recurrence: series, title: "Pay the rent" } });    expect((await occurrences(series))[0]!.data.title).toBe("Pay the rent");    await answer(slug, owner, "run_act", { act: "update_todo_recurrence", args: { recurrence: series, rrule: "FREQ=WEEKLY" } });    const reshaped = await occurrences(series);    expect(reshaped).toHaveLength(1);    expect(reshaped[0]!.id).not.toBe(plain.id);    expect(Date.parse(String(reshaped[0]!.data.occurrence_at)) - Date.now()).toBeLessThanOrEqual(7 * DAY);    const stopped = await answer<{ changed: { table: string; id: string; data: Record<string, unknown> }[] }>(slug, owner, "run_act", { act: "stop_todo_recurrence", args: { recurrence: series, keep: reshaped[0]!.id } });    expect(stopped.changed.find((r) => r.table === "todo_recurrence")!.data.trashed_at).toEqual(expect.any(String));    const kept = await answer<Rec>(slug, owner, "get_record_by_table", { table: "todo", id: reshaped[0]!.id });    expect(kept.data.recurrence_id).toBeUndefined();    expect(kept.deleted_at).toBeNull();  });  it("takes rrule on update_todo: a plain todo starts repeating, null stops it", async () => {    const plain = await answer<{ id: string }>(slug, owner, "create_todo", { title: "Call home", dueDate: day(2), dueTime: "19:00" });    const repeating = await answer<{ recurrenceId: string }>(slug, owner, "update_todo", { id: plain.id, rrule: "FREQ=WEEKLY;BYDAY=SU" });    expect(repeating.recurrenceId).toEqual(expect.any(String));    const stopped = await answer<{ recurrenceId?: string }>(slug, owner, "update_todo", { id: plain.id, rrule: null });    expect(stopped.recurrenceId).toBeUndefined();    expect(await refusal(slug, owner, "update_todo", { id: plain.id, rrule: null })).toBe("that todo does not repeat — there is no series to stop");  });});/** e2e rulings R3 (15 Nov 2026): once todos are sealed the object cannot read a series' words, so the person's devices make its occurrences (cotton-tools recurrence.rs). */describe("repeating todos, sealed", () => {  it("the object makes no occurrence of a sealed series on the alarm, though its rule reads", async () => {    const slug = "repeating-sealed";    await personalObject(slug);    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));    const past = new Date(Date.now() - 3 * DAY).toISOString();    const sealed = { sealed_enc: "s1:synthetic", dek_enc: "d1:synthetic", seal_v: 1 };    const count = () => runInDurableObject(stub, (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE table_id = 'todo'").toArray()[0]!.n);    await runInDurableObject(stub, (_i, state) => {      const at = new Date().toISOString();      state.storage.sql.exec("INSERT INTO rows (table_id, id, data, version, created_at, updated_at) VALUES ('todo_recurrence', 'series-sealed', ?, 1, ?, ?)", JSON.stringify({ rrule: "FREQ=DAILY", dtstart: past, paused: false, ...sealed }), at, at);      state.storage.sql.exec("INSERT INTO rows (table_id, id, data, version, created_at, updated_at) VALUES ('todo', 'first-sealed', ?, 1, ?, ?)", JSON.stringify({ recurrence_id: "series-sealed", occurrence_at: past, due_at: past, ...sealed }), at, at);    });    await runDurableObjectAlarm(stub);    expect(await count()).toBe(1);  });});describe("the rule", () => {  const zone = "Asia/Kolkata";  // The next occurrence after `from`, as a series whose latest finished there is owed it.  const after = (rule: string, dtstart: string, from: string, at = zone) => planOwed({ rrule: rule, dtstart, zone: at, latest: { at: from, finished: true }, mark: null, paused: false }, from)[0] ?? null;  it("walks weekly days, an interval, a count and an until", () => {    // Monday 2 Nov 2026, 09:00 in Kolkata.    const anchor = "2026-11-02T03:30:00.000Z";    expect(after("FREQ=WEEKLY;BYDAY=MO,TH", anchor, anchor)).toBe("2026-11-05T03:30:00.000Z");    expect(after("FREQ=WEEKLY;BYDAY=MO,TH", anchor, "2026-11-05T03:30:00.000Z")).toBe("2026-11-09T03:30:00.000Z");    expect(after("FREQ=WEEKLY;INTERVAL=2", anchor, anchor)).toBe("2026-11-16T03:30:00.000Z");    expect(after("FREQ=DAILY;COUNT=2", anchor, "2026-11-03T03:30:00.000Z")).toBeNull();    expect(after("FREQ=DAILY;UNTIL=20261103T235959Z", anchor, "2026-11-02T04:00:00.000Z")).toBe("2026-11-03T03:30:00.000Z");  });  it("skips a month without the anchor's day, and keeps the wall clock", () => {    expect(after("FREQ=MONTHLY", "2026-01-31T03:30:00.000Z", "2026-01-31T03:30:00.000Z")).toBe("2026-03-31T03:30:00.000Z");    expect(after("FREQ=YEARLY", "2024-02-29T00:00:00.000Z", "2024-03-01T00:00:00.000Z")).toBe("2028-02-29T00:00:00.000Z");    expect(after("FREQ=DAILY", "2026-03-07T14:00:00.000Z", "2026-03-07T15:00:00.000Z", "America/New_York")).toBe("2026-03-08T13:00:00.000Z");  });  it("refuses what it does not keep", () => {    expect(() => readRule("FREQ=MONTHLY;BYMONTHDAY=2")).toThrow("RRULE BYMONTHDAY is not kept");    expect(() => readRule("FREQ=MONTHLY;BYDAY=MO")).toThrow("RRULE BYDAY is kept on a weekly rule only");    expect(() => readRule("FREQ=WEEKLY;BYDAY=2MO")).toThrow('Invalid RRULE BYDAY token: "2MO"');  });  // RULE (decision 7): a todo rule reads as the phone reads it — the shared vectors.  for (const c of ruleVectors.cases as { rule: string; want?: unknown; refused?: string }[]) {    it(`reads ${JSON.stringify(c.rule)} as the phone does`, () => {      if (c.refused) expect(() => readRule(c.rule)).toThrow(c.refused);      else expect(readRule(c.rule)).toEqual(c.want);    });  }});// RULE: a series owes what the shared vectors say — the phone's planner reads// the same file (crates/cotton-rules/vectors/todo_recurrence.json).describe("the repeating-todo planner, by the shared vectors", () => {  type Case = { name: string; rrule: string; dtstart: string; zone: string; now: string; latest: { at: string; finished: boolean } | null; mark: string | null; paused: boolean; want?: string[]; refused?: boolean };  for (const c of planVectors.cases as Case[]) {    it(c.name, () => {      const plan = () => planOwed({ rrule: c.rrule, dtstart: c.dtstart, zone: c.zone, latest: c.latest, mark: c.mark, paused: c.paused }, c.now);      if (c.refused) expect(plan).toThrow();      else expect(plan()).toEqual(c.want);    });  }});