Cotton code
988 lines · 51.1 KB · TypeScriptRaw
/** * The business subset of the definitions engine, over the object's row store: * computed columns of ONE record on demand, the rule expressions, the * automations a write sets off, the record acts, and the reservation rule. * * The package JSON is the program; nothing here knows yoga or kitchens. The * semantics follow the Rust engine the phone runs * (crates/cotton-core/src/definitions/{computed,automations,acts,reserve}.rs, * crates/cotton-tools/src/mcp/handlers/tables/{automations,acts,reservations}.rs): * * - an automation fires when the write touched `when.column` and the record's *   value is `when.to` (or `to` is "any") and the guard holds; it runs `set`, *   `create` and `ledger` actions and cascades, bounded; * - the ledger picks the earliest-expiring purchase of the account that covers *   the day and still has credit (a purchase whose limit column is null is *   unlimited); none and no override is a refusal that rolls the write back; * - a reservation refuses when the slot's capacity is spent; * - a record act is a create (with bindings and picks), a set, or a cancel. */import type { ColumnDef, Definitions, TableDef } from "./definitions.ts";import { missingRequired, storable, withDefaults } from "./definitions.ts";import { BOOK, withBookFormat } from "./books.ts";import { withAppReports } from "./device_reports.ts";import { FETCH, withFetchDefaults } from "./fetch.ts";import { refuse } from "./http.ts";import { rule } from "./rules/index.ts";import { filmFolder } from "./media.ts";/** A film's tables, any of which may name one film folder (films.ts FAMILY's; kept here, as films.ts imports this). */const FILM_FAMILY = ["film", "film_season", "film_episode"] as const;import type { Journal } from "./changes.ts";import { col, type Stamps, type Store, type StoredRow } from "./store.ts";import { ARRIVAL_PATCHES, type ArrivalSeam } from "./arrival_seam.ts";import { checkSealFields, clearSealed, isSealedColumn, isSealedRow, KEEP_OPEN, SEAL_FIELDS, sealedColumns, seals } from "./seal.ts";/** A chat's messages and its threads: an erased message takes its words out of its chat's logged list lines. */const MESSAGES = "message";const THREADS = "thread";type Data = Record<string, unknown>;export interface Clock {  now: string;  today: string;}export interface ToolRules {  id: string;  tables: string[];  automations: Automation[];  reserve: Reservation | null;  order: OrderRule | null;}/** A tool that prices its claims: an order on a menu slot is quoted from the slot's item and written with one line beside it. */export interface OrderRule {  line_table: string;  order_link: string;  item_table: string;  item_link: string;  slot_item_link: string;  quantity: string;  price: string;  currency: string;  line_total: string;  order_total: string;  order_date: string;  slot_date: string;  plan?: string;}export interface Automation {  id: string;  name: string;  when: { table: string; column: string; to: unknown; guard?: unknown };  then: Action[];}export type Action =  | { set: { column: string; value: unknown } }  | { create: { table: string; values: Data } }  | { notify: { text: string } }  | { ledger: Ledger };export interface Ledger {  table: string;  account: string;  on: string;  purchase: string;  override_column: string;  purchase_account: string;  remaining: string;  expires: string;  starts: string;  refusal: string;  history?: string;  limit?: string;}export interface Reservation {  slot_table: string;  capacity_column: string;  claim_table: string;  slot_column: string;  quantity_column?: string;}export interface RecordAct {  id: string;  label: string;  kind: "create" | "update" | "delete";  verb: "create" | "reserve_record" | "set" | "cancel_reservation";  data?: Data;  bindings?: Record<string, string>;  when?: Data;  pick?: Pick;  picks?: Pick[];  confirm?: string;}export interface Pick {  argument: string;  kind: "record" | "number" | "text" | "datetime";  table?: string;  label?: string;  min?: number;  max?: number;  default?: unknown;  optional?: boolean;  /** A record pick's filter: each column holds the value, or one of a list; `$id` is the acted-on record's own id. */  where?: Data;}export function toolRules(tool: Record<string, unknown>): ToolRules {  const automations = Array.isArray(tool.automations) ? (tool.automations as Automation[]) : [];  return {    id: String(tool.id ?? ""),    tables: Array.isArray(tool.tables) ? (tool.tables as string[]) : [],    automations,    reserve: (tool.reserve as Reservation | undefined) ?? null,    order: (tool.order as OrderRule | undefined) ?? null,  };}export function recordActs(t: TableDef): RecordAct[] {  return Array.isArray(t.raw.acts) ? (t.raw.acts as RecordAct[]) : [];}const MAX_DEPTH = 6;/** How deep a chain of lookups may run before it is cut; cycles are handled before this, so only a pathological definition reaches it. */const MAX_RESOLVE_DEPTH = 12;const NONE: ReadonlySet<string> = new Set();const MAX_WRITE_ACTIONS = 64;/** What one act or write changed, in the order it happened. */export interface Outcome {  changed: StoredRow[];  made?: StoredRow;  notices: string[];  /** What an act says beside the rows it wrote (a statement's sums, what to read next). */  reply?: Data;  /** The columns each write set, by `wroteKey(table, id)`: a made row every column it holds, an erased one none. What a rule judging a write by what it changed reads (src/accounts.ts). */  wrote?: Map<string, Set<string>>;  /** A device's write said a column in the clear that an earlier clear list kept clear and the table now seals: the answer tells it its definitions are old (src/seal_wide.ts). */  stale?: boolean;}/** The key a row's written columns are kept under in `Outcome.wrote`. */export function wroteKey(table: string, id: string): string {  return `${table}\u0000${id}`;}function noteWrite(outcome: Outcome, table: string, id: string, keys: readonly string[]): void {  const wrote = (outcome.wrote ??= new Map());  const key = wroteKey(table, id);  const held = wrote.get(key) ?? new Set<string>();  for (const k of keys) held.add(k);  wrote.set(key, held);}/** Each row an outcome touched once, as it ended up: a cascade writes a row several times and the wire carries only the last. */export function settled(outcome: Outcome): StoredRow[] {  const last = new Map<string, StoredRow>();  for (const r of outcome.changed) last.set(`${r.table}\u0000${r.id}`, r);  return [...last.values()];}export class Engine {  readonly defs: Definitions;  readonly tools: ToolRules[];  readonly store: Store;  readonly clock: Clock;  /** Where this engine's row writes are logged (src/changes.ts): set for an act's and a Cotton MCP tool's writes; null writes unlogged (an import, a sync's own bookkeeping). */  journal: Journal | null = null;  /** Set while an act's own writes are sealed at arrival (src/arrival_seam.ts): a row it makes in a sealed table with sealed columns in the clear goes through it. */  arrival: ArrivalSeam | null = null;  /** While set, a change to a sealed row's sealed columns is a fill patch: the device fills only what the row leaves empty (a lookup's details). */  fillOnly = false;  /**   * The sealed columns, by table, a device's write in this act may say in the clear beside its seal: ones an earlier   * clear list kept clear, said by a phone still holding it (src/seal_wide.ts). Set by the act before it writes.   */  private readonly wide = new Map<string, Set<string>>();  /** Let this act's sealed writes to `table` hold `columns` in the clear (src/seal_wide.ts `admit` chose them). */  admitWide(table: string, columns: readonly string[]): void {    if (!columns.length) return;    const held = this.wide.get(table) ?? new Set<string>();    for (const k of columns) held.add(k);    this.wide.set(table, held);  }  /** The sealed columns `data` says in the clear that no device of this act was let say. */  private clearRefused(t: TableDef, data: Data): string[] {    const let_ = this.wide.get(t.id);    return clearSealed(t, data).filter((k) => !let_?.has(k));  }  /** Mark a sealed row by the sealed columns it holds in the clear beside its seal, or clear its mark (src/seal_wide.ts). */  private markWide(t: TableDef, row: StoredRow): void {    if (!t.seal || !isSealedRow(row.data)) return;    this.store.markWide(t.id, row.id, sealedColumns(t).filter((k) => k in row.data && row.data[k] !== null), this.clock.now);  }  private readonly cache = new Map<string, Data>();  private readonly inProgress = new Set<string>();  /** Set while computing a column when a value it needed could not be known. */  private unknown = false;  /** The computed columns of the record `resolved` last answered that could not be known; empty when the record is exact. */  private lastUnknown: ReadonlySet<string> = NONE;  constructor(defs: Definitions, tools: ToolRules[], store: Store, clock: Clock) {    this.defs = defs;    this.tools = tools;    this.store = store;    this.clock = clock;  }  // ── computed columns of one record ──────────────────────────────────────  /** The record with every column present and every computed column worked out. */  /**   * The record with its computed columns filled. Lookups and rollups read other   * rows and are computed once each; formulas read this record and settle   * after. Resolved records are cached until the next write, since a cascade   * reads the same records many times over.   *   * Definitions link in cycles (a session's `present` sums its bookings'   * `present`; a booking's `photo` looks up its session's), so a record being   * resolved answers a lookup from inside its own resolution with its stored   * columns only. A computed column read that way is unknown; the columns   * built on it are unknown too, exact for this call but not kept, while the   * rest of the record is exact and a caller reading only those is unharmed.   */  resolved(t: TableDef, row: StoredRow, depth = 0): Data {    const key = `${t.id}/${row.id}`;    const cached = this.cache.get(key);    if (cached) {      this.lastUnknown = NONE;      return cached;    }    const out: Data = { ...row.data, id: row.id };    for (const c of t.columns) if (!(c.key in out)) out[c.key] = null;    const computed = t.columns.filter((c) => c.computed);    if (this.inProgress.has(key) || depth > MAX_RESOLVE_DEPTH) {      this.lastUnknown = new Set(computed.map((c) => c.key));      this.unknown = true;      return out;    }    const formulas = computed.filter((c) => (c.computed as Record<string, unknown>).formula !== undefined);    const unknownKeys = new Set<string>();    const outerUnknown = this.unknown;    this.inProgress.add(key);    try {      for (const c of computed) {        if (formulas.includes(c)) continue;        this.unknown = false;        out[c.key] = this.computed(t, c, out, row, depth);        if (this.unknown) unknownKeys.add(c.key);      }    } finally {      this.inProgress.delete(key);    }    for (let pass = 0; pass < 4 && formulas.length; pass++) {      let settled = true;      for (const c of formulas) {        const value = this.computed(t, c, out, row, depth);        if (!looseEqual(value, out[c.key])) settled = false;        out[c.key] = value;        const of = ((c.computed as { formula: { of?: string[] } }).formula.of ?? []);        if (of.some((k) => unknownKeys.has(k))) unknownKeys.add(c.key);      }      if (settled) break;    }    // The caller's flag is its own: it is set by the column it reads, below.    this.unknown = outerUnknown;    if (!unknownKeys.size) this.cache.set(key, out);    this.lastUnknown = unknownKeys;    return out;  }  /** One column of a linked record. A record read from inside its own resolution answers its stored columns only; a computed column read that way, or one the linked record could not know, is unknown. */  private linkedValue(linkedDef: TableDef, linked: StoredRow, column: string, depth: number): unknown {    if (this.inProgress.has(`${linkedDef.id}/${linked.id}`)) {      if (linkedDef.columns.find((c) => c.key === column)?.computed) {        this.unknown = true;        return null;      }      return column === "id" ? linked.id : linked.data[column] ?? null;    }    const record = this.resolved(linkedDef, linked, depth + 1);    if (this.lastUnknown.has(column)) this.unknown = true;    return record[column] ?? null;  }  /** A computed column that reads another table's sealed column: unknown here (not kept), since only a device opens it. */  private sealedRead(): null {    this.unknown = true;    return null;  }  /** Forget every resolved record: a row changed, so rollups and lookups through it may have. */  private forget(): void {    this.cache.clear();  }  private computed(t: TableDef, c: ColumnDef, record: Data, row: StoredRow, depth: number): unknown {    const spec = c.computed as Record<string, unknown>;    if (spec.lookup) {      const l = spec.lookup as { through: string; column: string };      const target = record[l.through];      const through = t.columns.find((x) => x.key === l.through);      if (typeof target !== "string" || !through?.link_to) return null;      const linkedDef = this.defs.table(through.link_to);      // A sealed column is the device's to read (e2e rulings R3): the phone's derive works it out; here it is unknown, never a guess.      if (linkedDef && isSealedColumn(linkedDef, l.column)) return this.sealedRead();      const linked = this.store.get(through.link_to, target);      if (!linkedDef || !linked) return null;      return this.linkedValue(linkedDef, linked, l.column, depth);    }    if (spec.rollup) {      const r = spec.rollup as { table: string; link: string; op: string; column?: string; where?: { column: string; values: unknown[] } };      const sourceDef = this.defs.table(r.table);      if (!sourceDef) return null;      if ([r.link, r.column, r.where?.column].some((k) => typeof k === "string" && isSealedColumn(sourceDef, k))) return this.sealedRead();      let rows = this.store.list(r.table, { column: r.link, equals: row.id });      if (r.where) rows = rows.filter((x) => r.where!.values.includes(x.data[r.where!.column] ?? null));      const values = r.column        ? rows.map((x) => {            const needs = sourceDef.columns.find((col) => col.key === r.column)?.computed;            return needs ? this.linkedValue(sourceDef, x, r.column!, depth) : x.data[r.column!];          })        : [];      return rollupValue(r.op, rows.length, values);    }    if (spec.formula) {      const f = spec.formula as { op: string; of: string[]; separator?: string; flip_when?: { column: string; values: unknown[] } };      const flip = f.flip_when !== undefined && wordsOf(record[f.flip_when.column]) !== null && f.flip_when.values.includes(wordsOf(record[f.flip_when.column]));      return formulaValue(f.op, f.of.map((k) => record[k] ?? null), flip, f.separator);    }    return null;  }  // ── expressions ────────────────────────────────────────────────────────  /** A rule expression over the record: the phone's own evaluator (cotton-rules expressions.rs, as WASM). */  evaluate(value: unknown, record: Data): unknown {    return rule("expression.evaluate", { expression: value ?? null, record, now: this.clock.now, today: this.clock.today }, "rule_error");  }  // ── writes with their automations ──────────────────────────────────────  /** Create a row, run the automations it sets off, answer everything changed. `keep` carries an imported row's own id and times. */  create(table: string, data: Data, version: number, outcome: Outcome, depth = 0, keep: Stamps & { id?: string } = {}): StoredRow {    const t = this.defs.table(table);    if (!t) refuse(404, "no_such_table", `no table ${table}`);    if (t.raw.face_choices === true) data = this.faceChoice(t, data);    if (t.id === BOOK) data = withBookFormat(data);    if (t.id === FETCH) data = withFetchDefaults(data, this.clock.now);    const rowKey = t.raw.row_key;    if (typeof rowKey === "string") {      const id = data[rowKey];      if (typeof id !== "string" || !id.trim()) refuse(400, "bad_row_key", `${table} needs its ${rowKey} key`);      if (keep.id !== undefined && keep.id !== id) refuse(400, "bad_row_key", `${table} uses its ${rowKey} as its id`);      const held = this.store.get(table, id);      if (held) return this.update(held, data, version, outcome, depth);      keep = { ...keep, id };    }    let clean = withDefaults(t, storable(t, data));    if (checkSealFields(t, clean)) refuseClearSealed(t, this.clearRefused(t, clean));    const missing = missingRequired(t, clean);    if (missing.length) refuse(400, "missing_required", `${table} needs ${missing.join(", ")}`);    this.checkLinks(t, clean);    let id = keep.id ?? this.arrival?.freshId() ?? crypto.randomUUID();    // An act's own row in a sealed table is held sealed at arrival, never in the clear (R2).    if (this.arrival && t.seal && !isSealedRow(clean) && clearSealed(t, clean).length) ({ id, data: clean } = this.arrival.made(t, id, keep.id !== undefined, clean));    const owner = this.store.ownerOf(this.defs, t, clean);    const row = this.store.insert(table, id, clean, owner, version, keep);    this.markWide(t, row);    this.journal?.record("create", table, row.id, null, clean, version);    if (this.journal) this.store.witnessLogged(table, row.id, null, row.data);    this.forget();    outcome.changed.push(row);    const changed = Object.keys(clean);    for (const c of t.columns) if (!c.computed && !changed.includes(c.key)) changed.push(c.key);    noteWrite(outcome, table, row.id, changed);    return this.cascade(t, row, changed, version, outcome, depth);  }  /**   * A row of a table of face choices (`face_choices`, the definition says   * what the table is): its key names the table, `face` one its card offers,   * and the object owns the identity, the check and the accepted time.   *   * A key that names no table names a screen of the shell's own (the book   * reader's row, `reader`): its faces are the shell's to know, so its face   * is kept as said, and its other columns are that screen's settings (type   * size, margins, layout), kept as written where a table's row keeps none.   */  private faceChoice(t: TableDef, data: Data): Data {    const key = String(t.raw.row_key);    const chosen = data[key];    if (typeof chosen === "string" && chosen.trim() && !this.defs.table(chosen)) {      if (typeof data.face !== "string" || !data.face.trim()) refuse(400, "bad_face_choice", "choose a face for the screen");      return { ...storable(t, data), [key]: chosen, face: data.face, chosen_at: this.clock.now };    }    const card = this.defs.table(String(chosen))?.raw.card as { face?: string; offers?: string[] } | undefined;    const offers = card?.offers?.length ? card.offers : card?.face ? [card.face] : [];    if (typeof chosen !== "string" || typeof data.face !== "string" || !offers.includes(data.face)) {      refuse(400, "bad_face_choice", "choose a face the table offers");    }    return { [key]: chosen, face: data.face, chosen_at: this.clock.now };  }  /** Patch a row, run the automations it sets off. */  update(row: StoredRow, patch: Data, version: number, outcome: Outcome, depth = 0, stamps: Stamps = {}): StoredRow {    const t = this.defs.table(row.table);    if (!t) refuse(404, "no_such_table", `no table ${row.table}`);    if (t.raw.face_choices === true) {      // A write that seals carries the sealed half in its blob: the held row's clear copies stay out of what the choice is      // read from, and a seal that changes neither the key nor the face changes no choice (it is not chosen again).      const key = String(t.raw.row_key);      const moved = (k: string): boolean => k in patch && patch[k] !== row.data[k];      if (!isSealedRow(patch)) patch = this.faceChoice(t, { ...row.data, ...patch });      else if (moved(key) || moved("face")) {        const held = Object.fromEntries(Object.entries(row.data).filter(([k]) => !isSealedColumn(t, k)));        const seal = Object.fromEntries(SEAL_FIELDS.filter((k) => k in patch).map((k) => [k, patch[k]]));        patch = { ...seal, ...this.faceChoice(t, { ...held, ...patch }) };      }    }    if (t.id === BOOK) patch = withBookFormat(patch, row.data);    // Apps sharing one device credential each keep their own report on the row (src/device_reports.ts).    patch = withAppReports(t.id, patch, row.data, new Date(Date.parse(this.clock.now) || Date.now()));    let clean = storable(t, patch);    // A row of a sealed table that holds nothing sealed yet (made with clear columns alone) and that an act now gives sealed    // columns is sealed whole at arrival, never given them in the clear (R2).    if (this.arrival && t.seal && !isSealedRow(row.data) && !clearSealed(t, row.data).length && !isSealedRow(clean) && clearSealed(t, clean).length) clean = this.arrival.made(t, row.id, true, { ...row.data, ...clean }).data;    // A write that seals carries the whole sealed half in its blob: the row's clear copies of sealed columns (an open row's) go.    const sealing = checkSealFields(t, clean);    // The object's own change to sealed columns of a sealed row is kept beside it as an arrival patch (src/arrival_seam.ts).    let patched: unknown[] | null = null;    if (!sealing && this.arrival && t.seal && isSealedRow(row.data)) {      const said = clearSealed(t, clean);      if (said.length) {        const part: Data = {};        for (const k of said) {          part[k] = clean[k];          delete clean[k];        }        patched = [...heldPatches(row.data), this.arrival.patched(t, row.id, part, this.fillOnly)];      }    }    if (sealing || isSealedRow(row.data)) refuseClearSealed(t, this.clearRefused(t, clean));    // A device's seal folds the patches in: they go with the open copies. So does every other key the row holds that the    // table's clear list does not keep (one a definition has since dropped, LOCK TABLES 2 M1): the device sealed it    // into the blob (cotton-client seal::migrate clear_left), and a copy left beside it would fail every open. A sealed    // column this write says in the clear (one an earlier list kept clear, src/seal_wide.ts) is the write's own.    const dropped = sealing ? Object.keys(row.data).filter((k) => !(k in clean) && heldSealed(t, k)) : [];    if (patched) clean[ARRIVAL_PATCHES] = patched;    const changed = Object.keys(clean).filter((k) => !looseEqual(clean[k], row.data[k] ?? null));    if (!changed.length && !dropped.length) return row;    const data = { ...row.data, ...clean };    for (const k of dropped) delete data[k];    const rowKey = t.raw.row_key;    if (typeof rowKey === "string" && data[rowKey] !== row.id) refuse(400, "bad_row_key", `${row.table} keeps its ${rowKey} key`);    const missing = missingRequired(t, data);    if (missing.length) refuse(400, "missing_required", `${row.table} needs ${missing.join(", ")}`);    // A link the write leaves as the row holds it is no new claim: a row whose film has since gone still takes its other changes (and its seal).    this.checkLinks(t, Object.fromEntries(Object.entries(clean).filter(([k, v]) => JSON.stringify(v) !== JSON.stringify(row.data[k]))));    const owner = this.store.ownerOf(this.defs, t, data);    const next = this.store.update(row, data, owner, version, stamps);    if (sealing) this.markWide(t, next);    if (this.journal) {      const before: Data = {};      const after: Data = {};      for (const k of changed) {        before[k] = row.data[k] ?? null;        after[k] = clean[k] ?? null;      }      this.journal.record("update", row.table, row.id, before, after, version);      this.store.witnessLogged(row.table, row.id, row.data, next.data);    }    // The open row's plaintext goes from the log too: its earlier changes keep no sealed column (sealing plan §7 step 3).    if (dropped.length) this.store.scrubChanges(row.table, row.id, [...new Set([...sealedColumns(t), ...dropped])]);    this.forget();    outcome.changed.push(next);    const touched = [...changed, ...dropped.filter((k) => !changed.includes(k))];    noteWrite(outcome, row.table, row.id, touched);    return this.cascade(t, next, touched, version, outcome, depth);  }  /**   * `erase` (a phone's erase receipt says why: `disappeared`, `revoked`, `bin`) ends the row for good here too: the   * log keeps no earlier change of it and no `before`, and an erased message takes its words out of its chat's   * logged list lines (CONTRACT.md "WhatsApp through the Mac").   */  delete(row: StoredRow, version: number, outcome: Outcome, erase: string | null = null): StoredRow {    const t = this.defs.table(row.table);    // `delete: false` hides a page's own Delete. On a table a phone keeps    // under an engine (the personal package's), that engine removes its rows    // as it decides and the object cannot tell its removal from any other, so    // it is refused only on a table with none.    if (t?.raw.delete === false && !t.raw.engine) refuse(400, "no_delete", `${row.table} rows are not deleted directly`);    // A film's folder goes only when the row ends for good: an erase (a phone's emptied Bin says `bin`), or a delete    // on a table that keeps its own Bin (`deleted_at`), where the delete IS the emptying. A plain delete of a table    // without one is how a phone sends a row it has put in ITS Bin, and Undo there brings the row back: its files    // stay (Cinemas lead, 26 Nov 2026: Bin then Undo on a film had lost its stream, upload and original).    const final = erase !== null || Boolean(t?.columns.some((c) => c.key === "deleted_at"));    if (t && final) this.dropPlayedMedia(t, row);    // Not final, the tombstone keeps the keys of the files the row named and nothing else, so the phone's later erase    // (its emptied Bin, sent at this tombstone) still knows which folder to drop (CINEMAS DEV PROOF, 26 Nov 2026).    const kept = t && !final ? this.mediaKeys(t, row) : {};    const gone = erase ? this.erased(row, version, erase) : this.tombstone(row, version, kept);    this.forget();    outcome.changed.push(gone);    noteWrite(outcome, row.table, row.id, []);    return gone;  }  /**   * A record erased for good that plays a film (its table's slip names a   * `player` column holding `<database id>/films/<id>/master.m3u8`) takes the   * film's folder with it: the object deletes it from R2 once the write   * commits (src/business.ts `dropMedia`). So does each other file column   * holding a key in a film's folder (Cinemas, 5 Nov 2026: a film waiting   * for the Mac holds its upload in `source_file`, possibly in a folder of   * its own). A folder another live record of the table still holds a file   * of, in that column, stays.   */  private dropPlayedMedia(t: TableDef, row: StoredRow): void {    const slip = t.raw.slip as { player?: unknown } | null | undefined;    const player = typeof slip?.player === "string" ? slip.player : null;    const columns = new Set([...(player ? [player] : []), ...t.columns.filter((c) => c.type === "file" && !c.computed).map((c) => c.key)]);    const dropped = new Set<string>();    // Who else may name the folder: every file column of this table and, for a film's tables, of each of them (a    // film moved under a series is a film_episode naming the film's folder; Cinemas lead, 26 Nov 2026).    const family: readonly string[] = (FILM_FAMILY as readonly string[]).includes(t.id) ? FILM_FAMILY : [t.id];    const holders = family.flatMap((id) => {      const def = this.defs.table(id);      if (!def) return [];      const its = def.raw.slip as { player?: unknown } | null | undefined;      const keys = new Set([...(typeof its?.player === "string" ? [its.player] : []), ...def.columns.filter((c) => c.type === "file" && !c.computed).map((c) => c.key)]);      return [...keys].map((key) => ({ table: id, column: key }));    });    for (const column of columns) {      const key = row.data[column];      const folder = typeof key === "string" ? filmFolder(key) : null;      if (!folder || dropped.has(folder)) continue;      const sharing = holders.some(({ table, column: other }) => this.store.select(table, [{ sql: `substr(CAST(${col(other)} AS TEXT), 1, ?) = ? AND id <> ?`, args: [folder.length, folder, row.id] }], "id", 1).length > 0);      if (sharing) continue;      this.store.dropMediaLater(folder);      dropped.add(folder);    }  }  /** The row's columns that name a key in a film's folder (the player column and each file column), as the row holds them. */  private mediaKeys(t: TableDef, row: StoredRow): Record<string, string> {    const slip = t.raw.slip as { player?: unknown } | null | undefined;    const columns = new Set([...(typeof slip?.player === "string" ? [slip.player] : []), ...t.columns.filter((c) => c.type === "file" && !c.computed).map((c) => c.key)]);    const kept: Record<string, string> = {};    for (const column of columns) {      const key = row.data[column];      if (typeof key === "string" && filmFolder(key)) kept[column] = key;    }    return kept;  }  /**   * A row ERASED: a tombstone whose log entry holds nothing it held, its earlier entries gone, and, for a message,   * every copy of its chat's list line (`last_message_preview`, and the sealed blob a sealed thread's entries keep)   * taken out of that chat's entries.   */  private erased(row: StoredRow, version: number, erase: string): StoredRow {    const gone = this.store.tombstone(row, version, erase);    this.store.forgetChanges(row.table, row.id);    this.journal?.record("delete", row.table, row.id, null, null, version);    if (this.journal) this.store.witnessLogged(row.table, row.id, row.data, gone.data);    const thread = row.table === MESSAGES ? row.data.thread_id : null;    const threads = this.defs.table(THREADS);    if (typeof thread === "string" && thread && threads) this.store.scrubChanges(THREADS, thread, [...new Set([...sealedColumns(threads), ...SEAL_FIELDS, "last_message_preview"])]);    return gone;  }  /** A row goes as a tombstone, logged with everything it held. */  private tombstone(row: StoredRow, version: number, kept: Record<string, unknown> = {}): StoredRow {    const gone = this.store.tombstone(row, version, null, kept);    this.journal?.record("delete", row.table, row.id, row.data, null, version);    if (this.journal) this.store.witnessLogged(row.table, row.id, row.data, gone.data);    return gone;  }  private checkLinks(t: TableDef, data: Data): void {    for (const c of t.columns) {      if (c.type !== "link" || !c.link_to || c.computed) continue;      const v = data[c.key];      if (v === undefined || v === null || v === "") continue;      // A link of several records (an event's people) holds a list of ids, or one.      const ids = c.multiple && Array.isArray(v) ? v : [v];      for (const id of ids) {        if (typeof id !== "string" || id === "") refuse(400, "bad_link", `${t.id}.${c.key} must be ${c.multiple ? "record ids" : "a record id"}`);        if (c.link_to === "person" || c.link_to === "photo") continue;        if (!this.defs.table(c.link_to)) continue;        if (!this.store.get(c.link_to, id)) refuse(400, "bad_link", `${t.id}.${c.key} names no ${c.link_to}`);      }    }  }  private cascade(t: TableDef, row: StoredRow, changed: string[], version: number, outcome: Outcome, depth: number): StoredRow {    if (depth >= MAX_DEPTH) return row;    let current = row;    for (const tool of this.tools) {      for (const a of tool.automations) {        if (a.when.table !== t.id || !changed.includes(a.when.column)) continue;        const record = this.resolved(t, current);        if (a.when.to !== "any" && !looseEqual(record[a.when.column] ?? null, a.when.to)) continue;        if (a.when.guard !== undefined && this.evaluate(a.when.guard, record) !== true) continue;        for (const action of a.then) {          if (outcome.changed.length > MAX_WRITE_ACTIONS) refuse(400, "too_many_writes", "this write set off too many rules");          if ("set" in action) {            const value = this.evaluate(action.set.value, record);            if (!looseEqual(value, current.data[action.set.column] ?? null)) {              current = this.update(current, { [action.set.column]: value }, version, outcome, depth + 1);            }          } else if ("create" in action) {            const values: Data = {};            for (const [k, v] of Object.entries(action.create.values)) values[k] = this.evaluate(v, record);            this.create(action.create.table, values, version, outcome, depth + 1);          } else if ("ledger" in action) {            const purchase = this.ledgerPurchase(action.ledger, record);            if (purchase !== null) current = this.update(current, { [action.ledger.purchase]: purchase }, version, outcome, depth + 1);          } else if ("notify" in action) {            outcome.notices.push(action.notify.text.replace(/\$record\.(\w+)/g, (_, k: string) => String(record[k] ?? "")));          }        }      }    }    return current;  }  /** The earliest expiring purchase that covers the movement, or null when an override or history leaves it unassigned. */  private ledgerPurchase(rule: Ledger, movement: Data): string | null {    const historical = !!rule.history && typeof movement[rule.history] === "string" && movement[rule.history] !== "";    const override = movement[rule.override_column] === true;    const account = movement[rule.account];    const on = movement[rule.on];    if (typeof account !== "string" || typeof on !== "string") refuse(400, "ledger_refused", rule.refusal);    const held = typeof movement[rule.purchase] === "string" ? (movement[rule.purchase] as string) : null;    const purchaseDef = this.defs.table(rule.table);    if (!purchaseDef) refuse(400, "ledger_refused", rule.refusal);    const eligible: [string, string][] = [];    for (const p of this.store.list(rule.table, { column: rule.purchase_account, equals: account })) {      if (held && held !== p.id) continue;      const data = this.resolved(purchaseDef, p);      if (historical && !(rule.history && typeof data[rule.history] === "string" && data[rule.history] !== "")) continue;      const starts = typeof data[rule.starts] === "string" ? (data[rule.starts] as string) : null;      const expires = typeof data[rule.expires] === "string" ? (data[rule.expires] as string) : null;      const unlimited = !!rule.limit && (data[rule.limit] === null || data[rule.limit] === undefined);      const left = typeof data[rule.remaining] === "number" ? (data[rule.remaining] as number) : null;      const hasCredit = historical || unlimited || (left !== null && (held === p.id ? left >= 0 : left >= 1));      if ((starts === null || starts <= on) && (expires === null || on <= expires) && hasCredit) eligible.push([expires ?? "9999-12-31", p.id]);    }    eligible.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : 1));    const first = eligible[0];    if (first) return held === first[1] ? null : first[1];    if ((historical || override) && !held) return null;    refuse(409, "ledger_refused", rule.refusal);  }  // ── reservations ───────────────────────────────────────────────────────  reservationOf(claimTable: string): { tool: ToolRules; rule: Reservation } | null {    for (const tool of this.tools) if (tool.reserve && tool.reserve.claim_table === claimTable) return { tool, rule: tool.reserve };    return null;  }  /** Places left on a slot. */  remaining(rule: Reservation, slotId: string): number {    const slotDef = this.defs.table(rule.slot_table);    const slot = this.store.get(rule.slot_table, slotId);    if (!slotDef || !slot) refuse(404, "no_such_slot", `no ${rule.slot_table} ${slotId}`);    const capacity = this.resolved(slotDef, slot)[rule.capacity_column];    const cap = typeof capacity === "number" ? capacity : 0;    let taken = 0;    for (const claim of this.store.list(rule.claim_table, { column: rule.slot_column, equals: slotId })) {      const q = rule.quantity_column ? claim.data[rule.quantity_column] : 1;      taken += typeof q === "number" ? q : 1;    }    return cap - taken;  }  /** Take a claim on a slot: refused when the places are spent; priced and lined when the tool orders. */  reserve(tool: ToolRules, slotId: string, data: Data, version: number, outcome: Outcome): StoredRow {    const rule = tool.reserve;    if (!rule) refuse(400, "rule_error", `${tool.id} reserves nothing`);    const quantity = rule.quantity_column ? data[rule.quantity_column] ?? 1 : 1;    if (typeof quantity !== "number" || !Number.isInteger(quantity) || quantity <= 0) refuse(400, "bad_quantity", "quantity must be a positive whole number");    const left = this.remaining(rule, slotId);    if (quantity > left) refuse(409, "full", left <= 0 ? "this session is full" : `only ${left} place${left === 1 ? "" : "s"} left`);    const claim: Data = { ...data, [rule.slot_column]: slotId };    if (rule.quantity_column) claim[rule.quantity_column] = quantity;    const quote = tool.order ? this.quote(tool.order, rule, slotId, quantity, claim) : null;    const made = this.create(rule.claim_table, claim, version, outcome);    if (quote) this.writeLine(tool.order!, rule, made, quote, version, outcome);    outcome.made = made;    return made;  }  /**   * Price the order on `slot` from the slot's item (nothing when it is on a   * plan), and put its quantity, currency and day into the order: a value   * already there must agree. Answers the line to write beside the order.   */  private quote(spec: OrderRule, rule: Reservation, slotId: string, quantity: number, data: Data): Data {    const slotDef = this.defs.table(rule.slot_table);    const slot = this.store.get(rule.slot_table, slotId);    if (!slotDef || !slot) refuse(404, "no_such_slot", `no ${rule.slot_table} ${slotId}`);    if (rule.quantity_column !== spec.quantity) refuse(400, "rule_error", "reserve must bind the order quantity column");    const itemId = slot.data[spec.slot_item_link];    if (typeof itemId !== "string") refuse(400, "rule_error", "menu slot has no item");    const itemDef = this.defs.table(spec.item_table);    const item = this.store.get(spec.item_table, itemId);    if (!itemDef || !item) refuse(400, "rule_error", "menu slot names no item");    const listed = item.data[spec.price];    if (typeof listed !== "number" || !Number.isInteger(listed) || listed < 0) refuse(400, "rule_error", "menu item needs a price in whole minor units");    const onPlan = !!spec.plan && data[spec.plan] !== undefined && data[spec.plan] !== null && data[spec.plan] !== "";    const price = onPlan ? 0 : listed;    const currency = item.data[spec.currency];    if (typeof currency !== "string" || currency === "") refuse(400, "rule_error", "menu item needs a currency");    const date = slot.data[spec.slot_date];    if (date === undefined || date === null) refuse(400, "rule_error", "menu slot needs its date");    for (const [key, value] of [[spec.quantity, quantity], [spec.currency, currency], [spec.order_date, date]] as [string, unknown][]) {      const old = data[key];      if (old !== undefined && old !== null && !looseEqual(old, value)) refuse(400, "bad_request", "order currency and date come from the selected menu slot");      data[key] = value;    }    const line: Data = { [spec.item_link]: itemId, [spec.quantity]: quantity, [spec.price]: price, [spec.currency]: currency, [spec.line_total]: price * quantity };    const title = typeof itemDef.raw.title === "string" ? itemDef.raw.title : "name";    const lineDef = this.defs.table(spec.line_table);    if (!lineDef) refuse(400, "rule_error", `no table ${spec.line_table}`);    const lineTitle = typeof lineDef.raw.title === "string" ? lineDef.raw.title : "name";    if (item.data[title] !== undefined && item.data[title] !== null) line[lineTitle] = item.data[title];    return line;  }  /** The order's line, beside the order just taken: each link the line shares with the order (its customer) holds the order's own value. */  private writeLine(spec: OrderRule, rule: Reservation, order: StoredRow, line: Data, version: number, outcome: Outcome): void {    const claims = this.defs.table(rule.claim_table)!;    const lines = this.defs.table(spec.line_table)!;    for (const c of lines.columns) {      if (c.type !== "link" || c.key === spec.order_link || c.key === spec.item_link) continue;      const shared = claims.columns.find((x) => x.key === c.key && x.type === "link" && x.link_to === c.link_to);      const value = order.data[c.key];      if (shared && value !== undefined && value !== null) line[c.key] = value;    }    line[spec.order_link] = order.id;    this.create(spec.line_table, line, version, outcome);  }  // ── record acts ────────────────────────────────────────────────────────  /** Run a record act as the package defines it; `picked` is the ordered list of pick values. */  /**   * The tables `act` on a row of `t` writes (ADMIN KEYS 4: a key's record_act is checked against these, not only the   * table it names): `set` and `cancel_reservation` its own row's table (and a cancelled order's lines), `create` the   * table its data names, `reserve_record` the reservation's claim table (and the slot's).   */  actTables(t: TableDef, act: RecordAct): string[] {    switch (act.verb) {      case "set":        return [t.id];      case "cancel_reservation": {        const order = this.reservationOf(t.id)?.tool.order;        return order ? [t.id, order.line_table] : [t.id];      }      case "create":        return [String((act.data ?? {}).table)];      case "reserve_record": {        const picks = act.picks ?? (act.pick ? [act.pick] : []);        const slot = picks.find((pick) => pick.argument === "slot" && pick.kind === "record")?.table ?? t.id;        const r = this.reservationOf(this.reservationClaimFor(slot));        return r ? [this.reservationClaimFor(slot), slot] : [t.id];      }      default:        return [t.id];    }  }  runAct(t: TableDef, row: StoredRow, act: RecordAct, picked: unknown[], version: number, outcome: Outcome): StoredRow | null {    const record = this.resolved(t, row);    if (act.when) {      for (const [k, v] of Object.entries(act.when)) {        if (!whenMatches(record[k], v)) refuse(409, "act_not_available", `${act.label} is not available for this ${t.id}`);      }    }    const picks = act.picks ?? (act.pick ? [act.pick] : []);    if (picked.length !== picks.length) refuse(400, "bad_request", `${act.label} needs ${picks.length} picked value${picks.length === 1 ? "" : "s"}`);    switch (act.verb) {      case "set": {        const d = act.data ?? {};        const column = String(d.column);        const value = this.evaluate(d.value, record);        return this.update(row, { [column]: value }, version, outcome);      }      case "cancel_reservation": {        return this.cancel(row, version, outcome);      }      case "create":      case "reserve_record": {        const d = act.data ?? {};        // The act's `data` is the write's shape: `{ table, data: { preset columns } }`; bindings and picks address into it ("data.member").        const bound: Data = { data: { ...(typeof d.data === "object" && d.data ? (d.data as Data) : {}) } };        const table = act.verb === "create" ? String(d.table) : null;        for (const [argument, column] of Object.entries(act.bindings ?? {})) {          const value = column === "$id" ? row.id : record[column];          if (value === undefined) refuse(400, "rule_error", `act binding names an absent column ${column}`);          putPath(bound, argument, value);        }        picks.forEach((pick, i) => {          let value = picked[i];          if (pick.kind === "number") {            if (value === undefined || value === null || value === "") value = pick.default;            if (typeof value !== "number" || !Number.isFinite(value)) refuse(400, "bad_pick", `${pick.label ?? pick.argument} must be a number`);            if (pick.min !== undefined && value < pick.min) refuse(400, "bad_pick", `${pick.label ?? pick.argument} must be at least ${pick.min}`);            if (pick.max !== undefined && value > pick.max) refuse(400, "bad_pick", `${pick.label ?? pick.argument} must be at most ${pick.max}`);          } else {            if ((value === undefined || value === null || value === "") && pick.optional) value = "";            if (typeof value !== "string") refuse(400, "bad_pick", `${pick.label ?? pick.argument} is required`);            if (pick.kind === "record" && value !== "" && pick.table) {              const chosen = this.store.get(pick.table, value);              if (!chosen || !pickAccepts(pick, chosen.data, row.id)) refuse(400, "bad_pick", `that ${pick.table} is no longer a choice`);            }          }          putPath(bound, pick.argument, value);        });        const data = (bound.data as Data | undefined) ?? {};        if (act.verb === "reserve_record") {          // Taken on the slot itself, or on the slot's item with the slot          // picked among that item's (a dish's Order picks one of its days).          const slotPick = picks.find((pick) => pick.argument === "slot" && pick.kind === "record");          const r = this.reservationOf(this.reservationClaimFor(slotPick?.table ?? t.id));          if (!r) refuse(400, "rule_error", `${t.id} has no reservation rule`);          return this.reserve(r.tool, slotPick ? String(bound.slot) : row.id, data, version, outcome);        }        const made = this.create(table!, data, version, outcome);        outcome.made = made;        return made;      }    }    refuse(400, "rule_error", `unknown act verb ${String(act.verb)}`);  }  private reservationClaimFor(slotTable: string): string {    for (const tool of this.tools) if (tool.reserve && tool.reserve.slot_table === slotTable) return tool.reserve.claim_table;    refuse(400, "rule_error", `${slotTable} is not a slot table`);  }  /** Cancel a claim: the row goes (as a tombstone), the places return; an order's lines go with it. */  cancel(claim: StoredRow, version: number, outcome: Outcome): StoredRow {    const gone = this.tombstone(claim, version);    this.forget();    outcome.changed.push(gone);    const order = this.reservationOf(claim.table)?.tool.order;    if (order) {      for (const line of this.store.list(order.line_table, { column: order.order_link, equals: claim.id })) {        outcome.changed.push(this.tombstone(line, version));      }      this.forget();    }    return gone;  }}// ── helpers ─────────────────────────────────────────────────────────────────/** Whether a picked record still satisfies its pick's `where`, as the list that offered it did (`accepts_on` in the core). *//** `fn` with the engine's changes to sealed rows made as fill patches (src/arrival_seam.ts). */export function filling<T>(engine: Engine, fn: () => T): T {  const was = engine.fillOnly;  engine.fillOnly = true;  try {    return fn();  } finally {    engine.fillOnly = was;  }}/** The arrival patches a sealed row holds, in order. */function heldPatches(data: Data): unknown[] {  const held = data[ARRIVAL_PATCHES];  return Array.isArray(held) ? held : [];}/** * A key a sealed row holds that a device's seal carries in its blob: the object's arrival patches, and any key the * table's clear list does not keep (`seals`) but the seal's own fields, the id and the keep-open mark. The same set as * cotton-client seal::migrate `clear_left`, so what the reseal seals is what the commit drops. */function heldSealed(t: TableDef, k: string): boolean {  if (k === ARRIVAL_PATCHES) return true;  if (!t.seal || k === KEEP_OPEN || (SEAL_FIELDS as readonly string[]).includes(k)) return false;  return seals(t.seal, k);}/** A sealed row never holds a sealed column in the clear: refused by name, naming the columns. */function refuseClearSealed(t: TableDef, clear: string[]): void {  if (clear.length) refuse(400, "sealed_in_clear", `${t.id} keeps ${clear.join(", ")} sealed: a sealed row carries them only inside sealed_enc`);}function pickAccepts(pick: Pick, data: Data, on: string): boolean {  const at = (value: unknown): unknown => (value === "$id" ? on : value);  return Object.entries(pick.where ?? {}).every(([column, wanted]) => {    const held = data[column] ?? null;    return Array.isArray(wanted) ? wanted.some((one) => looseEqual(held, at(one))) : looseEqual(held, at(wanted));  });}/** An act's `when` as the phone reads it: equal, one of a list asked for, or among a list held; an absent value reads as `false`. */function whenMatches(value: unknown, wanted: unknown): boolean {  const held = value === undefined || value === null ? false : value;  if (looseEqual(held, wanted)) return true;  if (Array.isArray(wanted)) return wanted.some((one) => whenMatches(held, one));  return Array.isArray(held) && held.some((one) => looseEqual(one, wanted));}function looseEqual(a: unknown, b: unknown): boolean {  const na = a === undefined ? null : a;  const nb = b === undefined ? null : b;  if (typeof na === "number" && typeof nb === "number") return na === nb;  return JSON.stringify(na) === JSON.stringify(nb);}function putPath(target: Data, path: string, value: unknown): void {  const keys = path.split(".");  let at = target;  for (let i = 0; i < keys.length - 1; i++) {    const k = keys[i]!;    const next = at[k];    if (next === null || typeof next !== "object" || Array.isArray(next)) at[k] = {};    at = at[k] as Data;  }  at[keys[keys.length - 1]!] = value;}// ── computed columns' arithmetic ──────────────────────────────────────────// The phone's own (cotton-rules computed.rs, run as WASM), vectors in// crates/cotton-rules/vectors/computed.json./** A value as the words a join joins and a where compares. */export function wordsOf(value: unknown): string | null {  if (typeof value === "string") return value;  if (typeof value === "number" || typeof value === "boolean") return String(value);  return null;}/** A formula over the values its `of` names, in order; `flip` is whether the record's flip_when holds (signed only). */export function formulaValue(op: string, values: unknown[], flip: boolean, separator?: string): unknown {  return rule("computed.formula", { op, values, flip, ...(separator !== undefined ? { separator } : {}) });}/** A number as a reading writes it: half-up to `decimals` places (absent: at most 2), trailing zeros dropped; the stored value is never rounded. */export function readingFigure(value: number, decimals?: number): string {  return rule<string>("computed.figure", { value, ...(decimals !== undefined ? { decimals } : {}) });}/** A rollup over `count` gathered records whose rolled-up values are `values`, in gathered order. */export function rollupValue(op: string, count: number, values: unknown[]): unknown {  return rule("computed.rollup", { op, count, values });}