Cotton code
294 lines · 15.5 KB · TypeScriptRaw
/** * Repeating todos on the object (owner, 26 Oct 2026). A repeating todo is a * series — a `todo_recurrence` row: title, notes, priority, rrule, dtstart * (the first occurrence's instant), paused — and its occurrences, `todo` rows * carrying `recurrence_id` and `occurrence_at`. * * One occurrence is current: the series' latest, its one live copy (Days, * 20 Nov 2026: a repeat never stacks). When it is finished (done, dropped, * missed, or binned) the object makes the next one the rule names after now, * on the write that finished it. An occurrence left open past its moment * stays open and is still the one copy: nothing is made beside it. A stack * the old rule left (one late open copy per day) collapses on the series' * next pass: the newest open one stays, the earlier open ones are missed * (cotton-rules todo_recurrence.rs collapse_stack). Completing an occurrence * writes only occurrences, never the series; done also marks the series' * earlier open occurrences missed. * * The rule is read and expanded by the phone's own rules (cotton-rules * rrule.rs and todo_recurrence.rs, as WASM), in the database's own zone. * * SEALED TODOS ARE THE DEVICE'S (e2e rulings R3, 15 Nov 2026): once the * `todo` table is sealed the object cannot read a series' title, notes or * priority to copy into an occurrence, so it makes none. The person's * devices make them (cotton-tools recurrence.rs `materialize_todo_recurrences`, * run at every foreground, with ids derived from the series and the moment, * so two devices that overlap make one). */import type { Engine, Outcome } from "./engine.ts";import { refuse } from "./http.ts";import { rule } from "./rules/index.ts";import type { StoredRow } from "./store.ts";type Data = Record<string, unknown>;export const SERIES = "todo_recurrence";const TODO = "todo";const FINISHED = new Set(["done", "dropped", "missed"]);/** What a series pass needs besides the engine: the moment and the database's zone. */export interface Now {  at: string;  zone: string;}function str(row: StoredRow, key: string): string | null {  const v = row.data[key];  return typeof v === "string" && v !== "" ? v : null;}/** Whether the person's devices make this database's occurrences: its todos are sealed, so the object cannot read the words it would copy. */export function devicesRepeat(engine: Engine): boolean {  return !!engine.defs.table(TODO)?.seal;}function keeps(engine: Engine): void {  if (!engine.defs.table(SERIES) || !engine.defs.table(TODO)) refuse(404, "no_repeating_todos", "this database keeps no repeating todos");}function liveSeries(engine: Engine, id: string): StoredRow {  keeps(engine);  const row = engine.store.get(SERIES, id);  if (!row || str(row, "trashed_at")) refuse(404, "no_such_series", `no repeating todo with id ${id}`);  return row;}function liveTodo(engine: Engine, id: string): StoredRow {  const row = engine.store.get(TODO, id);  if (!row || str(row, "trashed_at")) refuse(404, "no_such_todo", `no todo with id ${id}`);  return row;}function instant(value: unknown, what: string): string {  const t = typeof value === "string" ? Date.parse(value) : NaN;  if (Number.isNaN(t)) refuse(400, "bad_request", `${what} is an ISO-8601 instant`);  return new Date(t).toISOString();}/** A series' occurrences that are not in the bin, by their moment. */function occurrencesOf(engine: Engine, seriesId: string): StoredRow[] {  return engine.store    .list(TODO, { column: "recurrence_id", equals: seriesId })    .filter((r) => !str(r, "trashed_at") && str(r, "occurrence_at") !== null)    .sort((a, b) => str(a, "occurrence_at")!.localeCompare(str(b, "occurrence_at")!));}/** One occurrence of a series at a moment, in its words. */function makeOccurrence(engine: Engine, series: StoredRow, at: string, version: number, outcome: Outcome): StoredRow {  const data: Data = { title: series.data.title ?? "", status: "open", recurrence_id: series.id, occurrence_at: at, due_at: at };  if (str(series, "notes")) data.notes = series.data.notes;  if (typeof series.data.priority === "number") data.priority = series.data.priority;  // The person's mark goes on with the series: the next copy wears the last one's (Cotton Days).  const marked = occurrencesOf(engine, series.id).filter((r) => str(r, "mark")).at(-1);  if (marked) data.mark = marked.data.mark;  return engine.create(TODO, data, version, outcome);}/** What the planner reads of a series. */export interface PlanInput {  rrule: string;  dtstart: string;  zone: string;  /** The series' latest occurrence not in the bin. */  latest: { at: string; finished: boolean } | null;  /** The newest occurrence the series ever made. */  mark: string | null;  paused: boolean;}/** A repeating todo's rule, read strictly (cotton-rules parse_todo_rule): refused as `bad_rrule` in its words. */export function readRule(rrule: string): { freq: string; interval: number; count: number | null; until: string | null; byday: string[] } {  return rule("todo.rule", { rrule }, "bad_rrule");}/** * The occurrences a series is owed at `now`, ascending: the phone's planner * (cotton-rules todo_recurrence.rs, as WASM), vectors in * crates/cotton-rules/vectors/todo_recurrence.json. */export function planOwed(input: PlanInput, now: string): string[] {  return rule("todo.plan", { ...input, now }, "bad_rrule");}/** * Give a series what it is owed (planOwed); answers the last occurrence made, * or null when none is owed * (the current one is still ahead, the series is paused or binned, or the rule * has ended). */export function advance(engine: Engine, series: StoredRow, now: Now, version: number, outcome: Outcome): StoredRow | null {  if (series.deleted || str(series, "trashed_at") || series.data.paused === true) return null;  const rrule = str(series, "rrule");  const dtstart = str(series, "dtstart");  if (!rrule || !dtstart || Number.isNaN(Date.parse(dtstart))) return null;  const all = occurrencesOf(engine, series.id);  const open = all.filter((r) => String(r.data.status ?? "open") === "open" && str(r, "occurrence_at") !== null);  const newest = open.at(-1);  for (const r of open) if (r.id !== newest!.id) engine.update(r, { status: "missed" }, version, outcome);  const latest = all.at(-1);  const owed = planOwed(    {      rrule,      dtstart,      zone: now.zone,      latest: latest ? { at: str(latest, "occurrence_at")!, finished: FINISHED.has(String(latest.data.status ?? "open")) } : null,      mark: str(series, "materialized_until"),      paused: false,    },    now.at,  );  // The series is never written by its occurrences (owner, 26 Oct 2026): its own mark is only an imported one.  let made: StoredRow | null = null;  for (const at of owed) if (!all.some((r) => str(r, "occurrence_at") === at)) made = makeOccurrence(engine, series, at, version, outcome);  return made;}/** * After a write: each series one of its occurrences was finished in gets its * next, and done marks the series' earlier open occurrences missed. Only the * rows the write itself changed are read. */export function afterWrites(engine: Engine, now: Now, version: number, outcome: Outcome): void {  if (!engine.defs.table(SERIES) || devicesRepeat(engine)) return;  const finished = new Map<string, StoredRow>();  for (const row of outcome.changed) {    if (row.table !== TODO || row.deleted) continue;    const series = str(row, "recurrence_id");    if (series && (FINISHED.has(String(row.data.status ?? "")) || str(row, "trashed_at"))) finished.set(series, row);  }  for (const [seriesId, done] of finished) {    const series = engine.store.get(SERIES, seriesId);    if (!series) continue;    if (done.data.status === "done") {      const at = str(done, "occurrence_at");      for (const earlier of occurrencesOf(engine, seriesId)) {        if (at === null || earlier.id === done.id || String(earlier.data.status ?? "open") !== "open") continue;        if (str(earlier, "occurrence_at")! < at) engine.update(earlier, { status: "missed" }, version, outcome);      }    }    advance(engine, series, now, version, outcome);  }}/** The alarm's pass: every series whose current occurrence passed gets its next. Answers how many were made. */export function advanceAll(engine: Engine, now: Now, version: number, outcome: Outcome): number {  if (!engine.defs.table(SERIES) || devicesRepeat(engine)) return 0;  let made = 0;  for (const series of engine.store.scan(SERIES)) if (advance(engine, series, now, version, outcome)) made += 1;  return made;}/** A series' template as an answer says it. */export function seriesJson(row: StoredRow): Data {  const d = row.data;  return {    id: row.id,    title: d.title ?? "",    notes: d.notes ?? null,    priority: d.priority ?? 0,    rrule: d.rrule ?? "",    dtstart: d.dtstart ?? "",    paused: d.paused === true,    stopped: typeof d.trashed_at === "string" && d.trashed_at !== "",  };}/** * A new repeating todo: the series and its first occurrence at `dtstart` * (with any next one already owed). Answers the series and that occurrence. */export function createRepeating(engine: Engine, data: { title: string; notes: string | null; priority: number }, rrule: string, dtstart: string, now: Now, version: number, outcome: Outcome): { series: StoredRow; first: StoredRow } {  keeps(engine);  readRule(rrule);  const at = instant(dtstart, "dtstart");  const series = engine.create(SERIES, { title: data.title, ...(data.notes ? { notes: data.notes } : {}), priority: data.priority, rrule, dtstart: at, paused: false }, version, outcome);  advance(engine, engine.store.get(SERIES, series.id)!, now, version, outcome);  const first = occurrencesOf(engine, series.id).find((r) => str(r, "occurrence_at") === at)!;  return { series: engine.store.get(SERIES, series.id)!, first };}/** `make_todo_recurring { todo, rrule, dtstart? }`: an existing todo becomes a series' first occurrence, anchored at `dtstart` or its own due. */export function makeRecurring(engine: Engine, args: Data, now: Now, version: number, outcome: Outcome): StoredRow {  keeps(engine);  // The rule is read before anything else: a rule nothing can expand is a series that mints nothing.  const rrule = typeof args.rrule === "string" && args.rrule.trim() ? args.rrule.trim() : refuse(400, "bad_request", "rrule is required: an iCal rule such as FREQ=WEEKLY;BYDAY=MO");  readRule(rrule);  const todo = liveTodo(engine, typeof args.todo === "string" ? args.todo : refuse(400, "bad_request", "todo is the todo's id"));  if (str(todo, "recurrence_id") && engine.store.get(SERIES, str(todo, "recurrence_id")!)) refuse(409, "already_repeats", "That todo already repeats");  const at = args.dtstart !== undefined && args.dtstart !== null ? instant(args.dtstart, "dtstart") : str(todo, "due_at") ? instant(todo.data.due_at, "the todo's due") : refuse(400, "bad_request", "a repeating todo needs a due — it anchors the series' first occurrence: give the todo a due, or pass dtstart");  const priority = typeof todo.data.priority === "number" ? todo.data.priority : 0;  const series = engine.create(SERIES, { title: todo.data.title ?? "", ...(str(todo, "notes") ? { notes: todo.data.notes } : {}), priority, rrule, dtstart: at, paused: false }, version, outcome);  engine.update(todo, { recurrence_id: series.id, occurrence_at: at, due_at: at }, version, outcome);  advance(engine, engine.store.get(SERIES, series.id)!, now, version, outcome);  outcome.made = series;  return series;}/** * `update_todo_recurrence { recurrence, rrule?, dtstart?, title?, notes?, priority?, paused? }`: * the series takes what is given. Its open occurrences still ahead follow: a * new title, notes or priority is written on them; a new rule, anchor or a * pause bins them, and the next occurrence the series now owes is made. * Overdue and finished occurrences are never touched. */export function updateRecurrence(engine: Engine, args: Data, now: Now, version: number, outcome: Outcome): StoredRow {  const series = liveSeries(engine, typeof args.recurrence === "string" ? args.recurrence : refuse(400, "bad_request", "recurrence is the repeating todo's id"));  const patch: Data = {};  if (args.rrule !== undefined) {    const rrule = typeof args.rrule === "string" && args.rrule.trim() ? args.rrule.trim() : refuse(400, "bad_request", "rrule is an iCal rule; stop a repeating todo with stop_todo_recurrence");    readRule(rrule);    patch.rrule = rrule;  }  if (args.dtstart !== undefined) patch.dtstart = instant(args.dtstart, "dtstart");  if (args.title !== undefined) patch.title = typeof args.title === "string" && args.title.trim() ? args.title.trim() : refuse(400, "bad_request", "title is text");  if (args.notes !== undefined) patch.notes = typeof args.notes === "string" && args.notes.trim() ? args.notes : null;  if (args.priority !== undefined) patch.priority = typeof args.priority === "number" && Number.isInteger(args.priority) ? args.priority : refuse(400, "bad_request", "priority is a whole number");  if (args.paused !== undefined) patch.paused = typeof args.paused === "boolean" ? args.paused : refuse(400, "bad_request", "paused is true or false");  const changed = Object.keys(patch).filter((k) => JSON.stringify(patch[k] ?? null) !== JSON.stringify(series.data[k] ?? null));  if (!changed.length) refuse(409, "nothing_to_change", "the repeating todo already reads so");  const reshaped = changed.some((k) => k === "rrule" || k === "dtstart" || k === "paused");  // A reshaped series projects afresh from now: its old mark no longer stands.  const next = engine.update(series, { ...patch, ...(reshaped ? { materialized_until: null } : {}) }, version, outcome);  const nowMs = Date.parse(now.at);  for (const occurrence of occurrencesOf(engine, series.id)) {    if (String(occurrence.data.status ?? "open") !== "open" || Date.parse(str(occurrence, "occurrence_at")!) <= nowMs) continue;    if (reshaped) engine.update(occurrence, { trashed_at: now.at }, version, outcome);    else engine.update(occurrence, { title: next.data.title, notes: next.data.notes ?? null, priority: next.data.priority ?? 0 }, version, outcome);  }  advance(engine, engine.store.get(SERIES, series.id)!, now, version, outcome);  return engine.store.get(SERIES, series.id)!;}/** * `stop_todo_recurrence { recurrence, keep? }`: the series goes to the bin. * Its open occurrences still ahead go with it, except `keep`; every open one * that stays (kept, or overdue) becomes a plain todo. Finished occurrences * stay as they are: they are what happened. Answers how many went. */export function stopRecurrence(engine: Engine, args: Data, now: Now, version: number, outcome: Outcome): number {  const series = liveSeries(engine, typeof args.recurrence === "string" ? args.recurrence : refuse(400, "bad_request", "recurrence is the repeating todo's id"));  const keep = args.keep === undefined || args.keep === null ? null : typeof args.keep === "string" ? args.keep : refuse(400, "bad_request", "keep is an occurrence's todo id");  const all = occurrencesOf(engine, series.id);  if (keep !== null && !all.some((r) => r.id === keep)) refuse(404, "no_such_todo", `todo ${keep} is no occurrence of that repeating todo`);  const nowMs = Date.parse(now.at);  let dropped = 0;  for (const occurrence of all) {    if (String(occurrence.data.status ?? "open") !== "open") continue;    if (occurrence.id !== keep && Date.parse(str(occurrence, "occurrence_at")!) > nowMs) {      engine.update(occurrence, { trashed_at: now.at }, version, outcome);      dropped += 1;    } else engine.update(occurrence, { recurrence_id: null, occurrence_at: null }, version, outcome);  }  engine.update(series, { trashed_at: now.at }, version, outcome);  return dropped;}