Cotton code
420 lines · 21.9 KB · TypeScriptRaw
/** * `create_todo`, `list_todos`, `update_todo` over the personal package's * `todo` table (crates/cotton-tools/src/mcp/handlers/records_1/todos.rs, its * validators in records_1/validate.rs). A due is two spellings of one fact — * an instant (`dueAt`) or a day with an optional clock (`dueDate`/`dueTime`) * — joined in the call's zone or the database's, never UTC. * * A repeating todo is a `todo_recurrence` series and its occurrences * (src/recurrence.ts): `rrule` on create_todo makes the series and its first * occurrence at the due; on update_todo it reshapes the todo's series, makes * a plain todo repeat, or (null) stops the series keeping this todo. * * A todo's projects are `project_link` rows (record_kind "todo"); a todo on a * list such as Agents is a `group_member` of that `record_group`, read with * `list_records { table: "todo", where: { group } }` as in Rust. */import { boundedLimit, fail, isoTimestamp, optionalString, type Data, type ToolContext } from "../../context.ts";import { col, typeOf, type Cond, type StoredRow } from "../../../store.ts";import { equalSql } from "./where.ts";import { isDate, isTime } from "./values.ts";import { isKnownZone, joinMoment, nextMoment, splitMoment, type Part } from "./zone.ts";import { resolveProject } from "./list.ts";import { createRepeating, makeRecurring, SERIES, stopRecurrence, updateRecurrence } from "../../../recurrence.ts";import { isSealedTable, windowFor } from "../window.ts";import { isSealedRow, openRow, SealError } from "../../../seal.ts";import type { TableKeys } from "../../../window.ts";import { resolveTable } from "./table.ts";import { createRecord, updateSealed } from "./write.ts";import marksFile from "../../../../../../crates/cotton-rules/src/days/marks.json";/** Cotton Days' marks catalogue: a `mark` names one of these ids (crates/cotton-rules/src/days/marks.json). */export const MARK_IDS: ReadonlySet<string> = new Set((marksFile as { marks: { id: string }[] }).marks.map((m) => m.id));/** `mark`: absent, null (no mark), or an id of the catalogue. */export function markArg(args: Data): { kind: "unchanged" } | { kind: "set"; value: string | null } {  if (!("mark" in args) || args.mark === undefined) return { kind: "unchanged" };  if (args.mark === null) return { kind: "set", value: null };  if (typeof args.mark === "string" && MARK_IDS.has(args.mark)) return { kind: "set", value: args.mark };  return fail(`mark must be one of the marks (${[...MARK_IDS].join(", ")}), or null for none`);}const TODO = "todo";const LIST_STATUSES = ["open", "done", "dropped", "missed", "all"];const SET_STATUSES = ["open", "done", "dropped"];const PRIORITIES = ["high", "none"];const LABEL_GONE =  'Todos have no label any more; groups do that job. Put the todo in a group instead: create_record { table: "record_group", data: { table_id: "todo", name } }, then create_record { table: "group_member", data: { group, record_id, place } } for each todo.';const NO_ZONE = "Cotton does not know which timezone this database lives in, so a day cannot be placed — pass timezone (an IANA zone like Asia/Kolkata), or pass dueAt as an exact instant.";function isUuid(v: string): boolean {  return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(v);}function requireUuid(args: Data, key: string): string {  const v = optionalString(args, key);  if (!v || !isUuid(v)) fail(`${key} must be a uuid`);  return v;}function optionalEnum(args: Data, key: string, allowed: string[]): string | null {  const v = optionalString(args, key);  if (v === null) return null;  if (!allowed.includes(v)) fail(`${key} must be one of: ${allowed.join(", ")}`);  return v;}/** `optional_zone`: the zone a call named, asked of the runtime. */function optionalZone(args: Data): string | null {  const zone = optionalString(args, "timezone");  if (zone === null) return null;  if (!isKnownZone(zone)) fail(`unknown timezone ${JSON.stringify(zone)}`);  return zone;}/** The database's own zone; the personal object always knows it, but the refusal stands for one that does not. */function workspaceZone(ctx: ToolContext): string {  return ctx.timezone && isKnownZone(ctx.timezone) ? ctx.timezone : fail(NO_ZONE);}type Clear = { kind: "unchanged" } | { kind: "cleared" } | { kind: "set"; value: string };const UNCHANGED: Clear = { kind: "unchanged" };function clearableTimestamp(args: Data, key: string): Clear {  const v = args[key];  if (v === undefined) return UNCHANGED;  if (v === null) return { kind: "cleared" };  if (typeof v !== "string") return UNCHANGED;  const at = isoTimestamp(v);  if (at === null) fail(`${key} must be an ISO 8601 timestamp, or null to clear it`);  return { kind: "set", value: at };}function clearableDate(args: Data, key: string): Clear {  const v = args[key];  if (v === undefined) return UNCHANGED;  if (v === null) return { kind: "cleared" };  if (typeof v !== "string") return UNCHANGED;  if (!isDate(v)) fail(`${key} must be YYYY-MM-DD, or null to clear it`);  return { kind: "set", value: v };}/** `clearable_string`: a blank string is the same instruction as null. */function clearableString(args: Data, key: string): Clear {  const v = args[key];  if (v === undefined) return UNCHANGED;  if (v === null) return { kind: "cleared" };  if (typeof v !== "string") return UNCHANGED;  return v.trim() ? { kind: "set", value: v.trim() } : { kind: "cleared" };}interface Due {  dueAt: Clear;  dueDate: Clear;  dueTime: Clear;  timezone: string | null;}function dueChange(args: Data): Due {  const dueAt = clearableTimestamp(args, "dueAt");  const dueDate = clearableDate(args, "dueDate");  let dueTime: Clear = UNCHANGED;  const raw = args.dueTime;  if (raw === null) dueTime = { kind: "cleared" };  else if (typeof raw === "string") {    if (!isTime(raw.trim())) fail("dueTime must be HH:mm (24-hour), or null to drop the time");    dueTime = { kind: "set", value: raw.trim() };  }  const timezone = optionalZone(args);  if (dueAt.kind !== "unchanged" && (dueDate.kind !== "unchanged" || dueTime.kind !== "unchanged")) fail("pass dueAt OR dueDate/dueTime, not both — they name the same moment");  return { dueAt, dueDate, dueTime, timezone };}function refuseLabel(args: Data): void {  if ("label" in args) fail(LABEL_GONE);}/** The day and clock a due reads as in a zone (`todo_due_fields`). */function dueFields(out: Data, dueAt: string | null, zone: string | null): void {  if (!dueAt || !zone) return;  let split: { date: string; time: string | null };  try {    split = splitMoment(dueAt, zone);  } catch {    return;  }  out.dueDate = split.date;  out.dueTime = split.time;}const text = (row: StoredRow, key: string): string | null => {  const v = row.data[key];  return typeof v === "string" && v !== "" ? v : v === null || v === undefined ? null : String(v);};function liveTodo(ctx: ToolContext, id: string): StoredRow | null {  const row = ctx.get(TODO, id);  return row && !text(row, "trashed_at") ? row : null;}// ── create_todo ───────────────────────────────────────────────────────────export async function createTodo(ctx: ToolContext, args: Data): Promise<Data> {  const title = optionalString(args, "title") ?? fail("title is required");  const notes = optionalString(args, "notes");  refuseLabel(args);  const rrule = optionalString(args, "rrule");  const mark = markArg(args);  const due = dueChange(args);  if (due.dueAt.kind === "cleared" || due.dueDate.kind === "cleared") fail("omit the due to create an undated todo — null clears nothing here");  if (due.dueTime.kind === "cleared") fail("omit dueTime for a date-only todo — null drops nothing here");  if (due.dueTime.kind === "set" && due.dueDate.kind !== "set") fail("dueTime needs dueDate — a time is a time on a day");  if (rrule !== null && due.dueAt.kind !== "set" && due.dueDate.kind !== "set") fail("a repeating todo needs a due — it anchors the series' first occurrence");  let dueAt: string | null = due.dueAt.kind === "set" ? due.dueAt.value : null;  if (due.dueDate.kind === "set") {    const zone = due.timezone ?? workspaceZone(ctx);    dueAt = joinMoment(due.dueDate.value, due.dueTime.kind === "set" ? due.dueTime.value : null, zone);  }  // AUDIT C 2-2: todos are sealed (the seal rule). A new todo is sealed as create_record seals one (in the caller's  // window, or at arrival to the owner's key), never written in the clear: on the dev Worker a key's create_todo put  // its title in the clear in a table every phone keeps sealed.  const t = resolveTable(ctx, TODO);  ctx.writable(TODO);  const sealed = isSealedTable(t);  if (rrule !== null) {    if (sealed) fail("Todos are sealed, and a repeating todo is not sealed here yet: make the todo without rrule, and the owner makes it repeat on the phone");    const { series, first } = ctx.write((w) => {      const made = createRepeating(w.engine, { title, notes, priority: 0 }, rrule, dueAt!, w.now, w.version, w.outcome);      if (mark.kind === "set" && mark.value !== null) w.engine.update(made.first, { mark: mark.value }, w.version, w.outcome);      return made;    });    const out: Data = { id: first.id, title, due_at: dueAt, status: "open", recurrenceId: series.id, rrule };    if (mark.kind === "set") out.mark = mark.value;    dueFields(out, dueAt, due.timezone ?? ctx.timezone);    return out;  }  const id = crypto.randomUUID();  const data: Data = { title };  if (dueAt !== null) data.due_at = dueAt;  if (notes !== null) data.notes = notes;  if (mark.kind === "set" && mark.value !== null) data.mark = mark.value;  let made = id;  if (sealed) {    const answer = await createRecord(ctx, { table: TODO, data });    made = String(((answer.record as Data | undefined)?.id ?? (answer.change as Data | undefined)?.id) ?? fail("the todo was not made"));  } else ctx.write((w) => w.create(TODO, data, { id }));  const out: Data = { id: made, title, due_at: dueAt, status: "open" };  if (mark.kind === "set") out.mark = mark.value;  dueFields(out, dueAt, due.timezone ?? ctx.timezone);  return out;}// ── list_todos ────────────────────────────────────────────────────────────type Cursor = { phase: "dated"; key: string; id: string } | { phase: "undated"; key: string; id: string };function b64url(text: string): string {  const bytes = new TextEncoder().encode(text);  let s = "";  for (const b of bytes) s += String.fromCharCode(b);  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}function unb64url(text: string): string | null {  if (!/^[A-Za-z0-9_-]*$/.test(text)) return null;  try {    const bin = atob(text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4));    return new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)));  } catch {    return null;  }}function encodeCursor(c: Cursor): string {  return b64url(JSON.stringify({ v: 1, phase: c.phase, key: c.key, id: c.id }));}function decodeCursor(raw: string): Cursor | null {  const text = unb64url(raw);  if (text === null) return null;  try {    const p = JSON.parse(text) as Data;    if (p.v !== 1 || typeof p.key !== "string" || typeof p.id !== "string") return null;    if (p.phase !== "dated" && p.phase !== "undated") return null;    return { phase: p.phase, key: p.key, id: p.id };  } catch {    return null;  }}export async function listTodos(ctx: ToolContext, args: Data): Promise<Data> {  const status = optionalEnum(args, "status", LIST_STATUSES) ?? "open";  const windowEnd = (key: string): string | null => {    const raw = optionalString(args, key);    return raw === null ? null : (isoTimestamp(raw) ?? fail(`${key} must be an ISO 8601 timestamp`));  };  const after = windowEnd("dueAfter");  const before = windowEnd("dueBefore");  if (after && before && after >= before) fail("dueAfter must be before dueBefore");  const includeUndated = typeof args.includeUndated === "boolean" ? args.includeUndated : after === null && before === null;  const project = optionalString(args, "project");  const unfiled = args.unfiled === true;  if (unfiled && project !== null && project !== "none") fail(`unfiled asks for the todos in no project and project ${JSON.stringify(project)} asks for one project's — pass one of them, not both`);  const rawCursor = optionalString(args, "cursor");  const cursor = rawCursor === null ? null : (decodeCursor(rawCursor) ?? fail("cursor is not one list_todos handed out — pass nextCursor from the previous page exactly as it came, or drop it to start the list again"));  const limit = boundedLimit(args, 50, 5000);  const zone = ctx.timezone && isKnownZone(ctx.timezone) ? ctx.timezone : null;  // Which projects each todo is filed under, read once.  const wanted = unfiled || project === "none" ? "none" : project === null ? null : resolveProject(ctx, project);  const projects = ctx.defs().table("project") ? [...ctx.scan("project")] : [];  const slugOf = new Map(projects.map((p) => [p.id, typeof p.data.slug === "string" ? p.data.slug : ""]));  const slugs = new Map<string, string[]>();  const filed = new Set<string>();  const under = new Set<string>();  const links = ctx.defs().table("project_link") ? ctx.where("project_link", "record_kind", "todo") : [];  for (const link of links) {    const projectId = text(link, "project");    const recordId = text(link, "record_id");    if (!projectId || !recordId) continue;    filed.add(recordId);    if (wanted !== null && wanted !== "none" && projectId === wanted) under.add(recordId);    const slug = slugOf.get(projectId);    if (slug) slugs.set(recordId, [...new Set([...(slugs.get(recordId) ?? []), slug])].sort());  }  // The list pages in SQL: the todo table is read a page at a time, never whole.  const due = `CAST(${col("due_at")} AS TEXT)`;  const base: Cond[] = [{ sql: `COALESCE(CAST(${col("trashed_at")} AS TEXT), '') = ''`, args: [] }];  if (status !== "all") base.push(equalSql("status", status));  if (wanted === "none") base.push({ sql: "id NOT IN (SELECT value FROM json_each(?))", args: [JSON.stringify([...filed])] });  else if (wanted !== null) base.push({ sql: "id IN (SELECT value FROM json_each(?))", args: [JSON.stringify([...under])] });  let all: StoredRow[] = [];  if (cursor?.phase !== "undated") {    const dated: Cond[] = [...base, { sql: `${typeOf("due_at")} <> 'null'`, args: [] }];    if (after !== null) dated.push({ sql: `${due} >= ?`, args: [after] });    if (before !== null) dated.push({ sql: `${due} < ?`, args: [before] });    if (cursor?.phase === "dated") dated.push({ sql: `(${due}, id) > (?, ?)`, args: [cursor.key, cursor.id] });    all = ctx.store.select(TODO, dated, `${due}, id`, limit + 1);  }  if (includeUndated && all.length <= limit) {    const undated: Cond[] = [...base, { sql: `${typeOf("due_at")} = 'null'`, args: [] }];    if (cursor?.phase === "undated") undated.push({ sql: "(created_at, id) < (?, ?)", args: [cursor.key, cursor.id] });    all = all.concat(ctx.store.select(TODO, undated, "created_at DESC, id DESC", limit + 1 - all.length));  }  const more = all.length > limit;  const out: Data = { more };  if (zone !== null) out.timezone = zone;  const page = all.slice(0, limit);  const last = page.at(-1);  if (more && last) {    const due = text(last, "due_at");    out.nextCursor = encodeCursor(due !== null ? { phase: "dated", key: due, id: last.id } : { phase: "undated", key: last.created_at, id: last.id });  }  // Todos are sealed (the seal rule): in the caller's window each sealed row on the page is opened, so its title and  // notes are read; a page holding a sealed row asks for a window outside one. A row still in the clear (made over  // MCP, not yet sealed by a phone) reads as it did.  const t = resolveTable(ctx, TODO);  const keys = isSealedTable(t) && page.some((row) => isSealedRow(row.data)) ? await windowFor(ctx, t, "list_todos") : null;  const shown = keys ? await Promise.all(page.map((row) => openTodo(ctx, keys, row))) : page;  out.todos = shown.map((row) => {    const due = text(row, "due_at");    const item: Data = { id: row.id, title: text(row, "title"), status: text(row, "status"), dueAt: due };    dueFields(item, due, zone);    const notes = text(row, "notes");    if (notes !== null) item.notes = notes;    if (typeof row.data.priority === "number" && row.data.priority > 0) item.priority = "high";    const snoozed = text(row, "snoozed_until");    if (snoozed !== null) item.snoozedUntil = snoozed;    const completed = text(row, "completed_at");    if (completed !== null) item.completedAt = completed;    if (text(row, "recurrence_id") !== null) item.repeating = true;    item.projects = slugs.get(row.id) ?? [];    return item;  });  return out;}/** A sealed to-do opened with the window's key for its own version, its clear columns kept beside. */async function openTodo(ctx: ToolContext, keys: TableKeys, row: StoredRow): Promise<StoredRow> {  if (!isSealedRow(row.data)) return row;  const v = row.data.seal_v;  try {    return { ...row, data: await openRow(typeof v === "number" ? (keys.tk.get(v) ?? null) : null, ctx.database.id, TODO, row.id, row.data) };  } catch (error) {    if (error instanceof SealError) fail(`a to-do does not open with this window's keys (${error.code})`, { code: error.code });    throw error;  }}// ── update_todo ───────────────────────────────────────────────────────────const UPDATE_COLUMNS = ["title", "notes", "status", "due_at", "snoozed_until", "priority", "completed_at"];function asPart(c: Clear): Part {  return c.kind === "set" ? { kind: "set", value: c.value } : c;}export async function updateTodo(ctx: ToolContext, args: Data): Promise<Data> {  const id = requireUuid(args, "id");  const title = optionalString(args, "title");  const notes = clearableString(args, "notes");  refuseLabel(args);  const due = dueChange(args);  const priority = optionalEnum(args, "priority", PRIORITIES);  const snoozed = clearableTimestamp(args, "snoozedUntil");  const status = optionalEnum(args, "status", SET_STATUSES);  const mark = markArg(args);  const rrule = args.rrule === undefined ? undefined : args.rrule === null ? null : (optionalString(args, "rrule") ?? fail("rrule is an iCal rule such as FREQ=WEEKLY;BYDAY=MO, or null to stop the repeat"));  const changesDue = due.dueAt.kind !== "unchanged" || due.dueDate.kind !== "unchanged" || due.dueTime.kind !== "unchanged";  if (title === null && notes.kind === "unchanged" && !changesDue && priority === null && snoozed.kind === "unchanged" && status === null && rrule === undefined && mark.kind === "unchanged") fail("nothing to change — pass a field to change");  const needsZone = due.dueAt.kind === "unchanged" && (due.dueDate.kind !== "unchanged" || due.dueTime.kind !== "unchanged");  const zone = needsZone ? (due.timezone ?? workspaceZone(ctx)) : null;  const current = liveTodo(ctx, id) ?? fail(`no todo with id ${id}`);  const patch: Data = {};  if (title !== null) patch.title = title;  if (notes.kind !== "unchanged") patch.notes = notes.kind === "set" ? notes.value : null;  if (changesDue) {    if (due.dueAt.kind !== "unchanged") patch.due_at = due.dueAt.kind === "set" ? due.dueAt.value : null;    else if (zone === null) fail("a day needs a zone to be placed in");    else patch.due_at = nextMoment(text(current, "due_at"), asPart(due.dueDate), asPart(due.dueTime), zone);  }  if (priority !== null) patch.priority = priority === "high" ? 1 : 0;  if (mark.kind === "set") patch.mark = mark.value;  if (snoozed.kind !== "unchanged") patch.snoozed_until = snoozed.kind === "set" ? snoozed.value : null;  if (status !== null) {    patch.status = status;    // `completed_at` is what done means: completing stamps it, reopening or dropping clears it.    patch.completed_at = status === "done" ? ctx.now : null;  }  const seriesId = text(current, "recurrence_id");  const series = seriesId !== null && ctx.get(SERIES, seriesId) && !text(ctx.get(SERIES, seriesId)!, "trashed_at") ? seriesId : null;  if (rrule === null && series === null) fail("that todo does not repeat — there is no series to stop");  // Todos are sealed (the seal rule): a change to a sealed column is made in the caller's window, the row opened,  // the change laid over it and sealed again, as update_record does. Written in the clear it was refused  // sealed_in_clear on every to-do a phone had sealed (the emulator, 22 Nov 2026).  const t = resolveTable(ctx, TODO);  const sealed = isSealedTable(t) && isSealedRow(current.data);  let opened: Data | null = null;  if (sealed && Object.keys(patch).length) {    const answer = await updateSealed(ctx, t, id, patch, new Map(), await windowFor(ctx, t, "update_todo"), true, true);    opened = ((answer.record as { data?: Data } | undefined)?.data ?? null) as Data | null;  }  ctx.write((w) => {    const row = Object.keys(patch).length && !sealed ? w.update(current, patch) : (liveTodo(ctx, id) ?? current);    if (rrule === null) stopRecurrence(w.engine, { recurrence: series, keep: id }, w.now, w.version, w.outcome);    else if (rrule !== undefined && series !== null) updateRecurrence(w.engine, { recurrence: series, rrule }, w.now, w.version, w.outcome);    else if (rrule !== undefined) makeRecurring(w.engine, { todo: row.id, rrule }, w.now, w.version, w.outcome);  });  const after = liveTodo(ctx, id) ?? fail(`no todo with id ${id}`);  const shown: Data = { ...after.data, ...(opened ?? {}) };  const out: Data = { id: after.id };  for (const key of UPDATE_COLUMNS) out[key] = shown[key] ?? null;  if (mark.kind === "set") out.mark = shown.mark ?? null;  const repeats = text(after, "recurrence_id");  if (repeats !== null) out.recurrenceId = repeats;  dueFields(out, text(after, "due_at"), zone ?? (ctx.timezone && isKnownZone(ctx.timezone) ? ctx.timezone : null));  return out;}