Cotton code
248 lines · 15.2 KB · TypeScriptRaw
/** * The change log (owner, 26 Oct 2026): every row write an act or a Cotton MCP * tool makes is one row of the object's `change` table — who wrote it, through * what, the columns it changed as they were and as they became — so any one * of them can be taken back (`undo`) and a record put back the way one of its * changes left it (`restore_version`). * * The log is the object's own storage: no definition draws it and no phone * syncs it. It is kept to a window (the meta's `change_days`, default 90, * `change_rows`, default 100 000, and `change_bytes`, a size budget in * characters of before and after, none by default), trimmed on the object's * alarm a step at a time, the oldest first. Each is set per account * (`PUT /v1/admin/business`): nothing is trimmed harder than today until it is. * * What an entry keeps (coordinator, 22 Nov 2026: his log was 2.86 GB of a * 6.5 GB file, 28 KB an entry): a create keeps only the names of the columns * it wrote, an update the changed columns as they were and only the names of * what they became (`{ "$keys": [...] }`), a delete the whole record. What a * change left is worked back from the record as it stands through the later * changes (`stateAfter`), which is all undo and restore_version ever needed. A * write that says it is an import (`import: true` on create, update or delete) * keeps only that it happened (kind `import`): it cannot be undone, nor can a * record be restored across it. * * Who the log is for (owner, 23 Nov 2026): a PERSON taking back or restoring what a person or their assistant wrote. * A machine's write (MACHINE_WRITERS: imports, sync and seal bookkeeping, progress ticks, download and fetch state, * migrations, session and access logs, jobs, emptying the bin, whose undo is the bin) keeps only that it happened * (kind `machine`), as an import does: it cannot be undone, nor can a record be restored across it. A writer not * named there keeps its full undo, so a new tool is undoable until it is classified as a machine's. * * Undo is judged by the data, never the kind: a change with no `before` made * the record, so it goes; one with no `after` erased it, so it comes back * holding what it held; any other wrote columns, so they are written back. A * record written since the change (its version moved on) is refused: undoing * then would overwrite a later write. */import type { Engine, Outcome } from "./engine.ts";import { refuse } from "./http.ts";import { SEAL_FIELDS } from "./seal.ts";import type { ChangeKind, ChangeRow, Store, StoredRow } from "./store.ts";type Data = Record<string, unknown>;export const CHANGE_DAYS = 90;export const CHANGE_ROWS = 100_000;/** AUDIT C 3: the days the row cap never trims into, so a flood of cheap writes cannot flush recent undo. */export const CHANGE_FLOOR_DAYS = 7;/** What an entry's `after` keeps of a create or an update: the names of the columns written, never their values. */export const KEYS = "$keys";/** The column names a logged `after` holds only by name (a create or update logged since 22 Nov 2026), or null when it holds values. */export function keysOnly(after: Data | null): string[] | null {  const keys = after?.[KEYS];  return Array.isArray(keys) && Object.keys(after!).length === 1 ? keys.map(String) : null;}/** * The writers (a change's `via`) whose writes are a machine's, each with why: their entries keep only that they * happened. Everything else a person or an assistant writes by hand keeps its full undo. */export const MACHINE_WRITERS: Readonly<Record<string, string>> = {  // Seals and migrations  seal: "sealing a table's rows: a migration", seal_stage: "sealing a table's rows: a migration", seal_commit: "sealing a table's rows: a migration", seal_purge: "sealing a table's rows: a migration",  reshape_films: "a migration", story_move_old: "a migration",  owner: "linking the owner's own person, bookkeeping",  // Access, sessions and their logs  unlock_allow: "an assistant's window: access bookkeeping", unlock_decline: "an assistant's window: access bookkeeping", unlock_end: "an assistant's window: access bookkeeping", unlock: "an assistant's window: access bookkeeping",  assistant_allow: "an assistant's access: bookkeeping", assistant_add: "an assistant's access: bookkeeping", assistant_scope: "an assistant's access: bookkeeping", assistant_remove: "an assistant's access: bookkeeping",  set_role: "a member's role: access bookkeeping", mint_token: "a token: access bookkeeping", revoke_token: "a token: access bookkeeping", token_allow: "a token: access bookkeeping",  request_unlock: "an assistant's window: access bookkeeping", end_unlock: "an assistant's window: access bookkeeping",  log_session: "a session log", feedback: "a report from an app: bookkeeping",  // Imports and the services' sync  import_goodreads: "an import", export_open_bundle: "an export's bookkeeping", story_fountain_read: "an import of a screenplay file",  mail: "the Mac's mail: an import", google: "Google's calendar sync", calendar: "the calendar's sync", spotify: "Spotify's sync", send: "the outbox's sending state",  // Jobs that fill or fetch  alarm: "the object's own jobs", artwork: "a fetched picture", book_file: "a book's file landing",  film_converted: "a film's conversion",  meeting_claim: "a recording's transcription state", meeting_failed: "a recording's transcription state",  // Download and fetch state, and its progress ticks  fetch_add: "download and fetch state", fetch_cancel: "download and fetch state", fetch_retry: "download and fetch state", fetch_again: "download and fetch state",  fetch_claim: "download and fetch state", fetch_stage: "a progress tick", fetch_progress: "a progress tick", fetch_landed: "download and fetch state", fetch_failed: "download and fetch state",  // The bin is its own undo  empty_bin: "emptying the bin: the bin was its undo",};/** Whether a change through `via` is a machine's (MACHINE_WRITERS). */export const machineWrite = (via: string): boolean => Object.hasOwn(MACHINE_WRITERS, via);/** Where one write's row changes are logged: its actor, what it came through, and the kind it is said as (null: by the write each one made). */export class Journal {  readonly ids: number[] = [];  kind: ChangeKind | null;  private readonly store: Store;  private readonly actor: string | null;  private readonly via: string;  constructor(store: Store, actor: string | null, via: string, kind: ChangeKind | null = null) {    this.store = store;    this.actor = actor;    this.via = via;    // A machine's write keeps only that it happened, whatever it was asked as.    this.kind = kind === "import" || !machineWrite(via) ? kind : "machine";  }  record(op: "create" | "update" | "delete", table: string, recordId: string, before: Data | null, after: Data | null, version: number): void {    // An import keeps only that it happened; a create or update keeps what it wrote only by name (the record holds it).    if (this.kind === "import" || this.kind === "machine") [before, after] = [null, null];    else if (after !== null) after = { [KEYS]: Object.keys(after) };    this.ids.push(this.store.addChange({ actor: this.actor, via: this.via, table, record_id: recordId, kind: this.kind ?? op, before, after, version }));  }}/** The log's window as the meta sets it. */export function changeWindow(store: Store): { days: number; rows: number; bytes: number | null } {  const whole = (v: string | null, fallback: number): number => {    const n = v === null ? NaN : Number(v);    return Number.isInteger(n) && n > 0 ? n : fallback;  };  const budget = whole(store.meta("change_bytes"), 0);  return { days: whole(store.meta("change_days"), CHANGE_DAYS), rows: whole(store.meta("change_rows"), CHANGE_ROWS), bytes: budget > 0 ? budget : null };}/** * Trim the log toward its window, a bounded step at a time; answers how many changes went and whether more are left. * With a size budget the log's size is counted first (Store.countChanges, a step a call, newest first); until it is, * only the age and the count trim. */export function trimChanges(store: Store, now: Date, step: { most?: number; chars?: number } = {}): { trimmed: number; more: boolean } {  const { days, rows, bytes } = changeWindow(store);  if (bytes !== null && !store.changeSize().ready && store.countChanges(step.most)) return { trimmed: 0, more: true };  const floor = new Date(now.getTime() - Math.min(days, CHANGE_FLOOR_DAYS) * 86_400_000).toISOString();  return store.trimChanges(new Date(now.getTime() - days * 86_400_000).toISOString(), rows, bytes, step.most, step.chars, floor);}/** Trim the act log to the change log's window, a bounded step at a time (Store.trimActs). */export function trimActs(store: Store, now: Date, most?: number): { trimmed: number; more: boolean } {  const { days, rows } = changeWindow(store);  return store.trimActs(new Date(now.getTime() - days * 86_400_000).toISOString(), rows, most);}/** A change by its id, as a caller names it (a number, or its digits). */export function changeOf(store: Store, asked: unknown): ChangeRow {  const id = typeof asked === "number" ? asked : typeof asked === "string" && /^\d+$/.test(asked.trim()) ? Number(asked.trim()) : NaN;  if (!Number.isSafeInteger(id) || id < 1) refuse(400, "bad_change", "change_id is the number a write answered as its change_id");  return store.change(id) ?? refuse(404, "no_such_change", `there is no change ${id}: it was never made, or it is older than the log keeps`);}/** Take one change back, in the writer's version; answers the row as it now stands (a tombstone after a create is undone). */export function undo(engine: Engine, journal: Journal, c: ChangeRow, version: number, outcome: Outcome): StoredRow {  const store = engine.store;  if (c.kind === "import") refuse(409, "import_not_undone", `change ${c.id} was an import: the log keeps only that it happened, not what it wrote, so it cannot be undone`);  if (c.kind === "machine") refuse(409, "machine_not_undone", `change ${c.id} was a machine's write (${c.via}): the log keeps only that it happened, so it cannot be undone`);  if (c.undone_by !== null) refuse(409, "already_undone", `change ${c.id} was already undone by change ${c.undone_by}`);  // An erase (src/engine.ts `erased`) logs its delete holding nothing: there is nothing of the record to bring back.  if (c.kind === "delete" && c.before === null) refuse(409, "erased_not_undone", `change ${c.id} erased the record for good: the log keeps nothing it held, so it cannot be undone`);  const row = store.any(c.table, c.record_id);  const left = c.after === null ? row?.deleted === true : row?.deleted === false;  if (!row || !left || row.version !== c.version) refuse(409, "changed_since", `the record changed since change ${c.id}: undoing it would overwrite a later write`);  const first = journal.ids.length;  let now: StoredRow;  if (c.before === null) now = engine.delete(row, version, outcome);  else if (c.after === null) {    journal.kind = "restore";    now = engine.create(c.table, c.before, version, outcome, 0, { id: c.record_id, created_at: row.created_at });    journal.kind = null;  } else now = engine.update(row, sealTogether({ ...c.before }, row.data), version, outcome);  const by = journal.ids[first];  if (by !== undefined) store.markUndone(c.id, by);  return now;}/** * The record as change `c` left it, worked back from how it stands now * through every later change: null when that change left it erased. */export function stateAfter(store: Store, c: ChangeRow): Data | null {  if (c.kind === "import") refuse(409, "import_not_undone", `change ${c.id} was an import: the log keeps only that it happened, so what it left cannot be worked back`);  if (c.kind === "machine") refuse(409, "machine_not_undone", `change ${c.id} was a machine's write (${c.via}): the log keeps only that it happened, so what it left cannot be worked back`);  const row = store.any(c.table, c.record_id);  let state: Data | null = row && !row.deleted ? { ...row.data } : null;  for (const later of store.changesSince(c.table, c.record_id, c.id)) {    if (later.kind === "import") refuse(409, "import_since", `change ${later.id}, an import, wrote the record since change ${c.id}: what it was before cannot be worked back`);    if (later.kind === "machine") refuse(409, "machine_since", `change ${later.id}, a machine's write (${later.via}), wrote the record since change ${c.id}: what it was before cannot be worked back`);    if (later.before === null) state = null;    else if (later.after === null) state = { ...later.before };    else state = { ...(state ?? {}), ...later.before };  }  return state;}/** Rewrite a record to how change `c` left it, in the writer's version; refused when it already reads so. */export function restoreVersion(engine: Engine, journal: Journal, c: ChangeRow, version: number, outcome: Outcome): StoredRow {  const store = engine.store;  const wanted = stateAfter(store, c);  const row = store.any(c.table, c.record_id);  const t = engine.defs.table(c.table);  if (!t) refuse(404, "no_such_table", `no table ${c.table}`);  const same = `the record already reads as change ${c.id} left it`;  if (wanted === null) {    if (!row || row.deleted) refuse(409, "already_so", same);    return engine.delete(row, version, outcome);  }  if (!row || row.deleted) {    journal.kind = "restore";    const made = engine.create(c.table, wanted, version, outcome, 0, { id: c.record_id, ...(row ? { created_at: row.created_at } : {}) });    journal.kind = null;    return made;  }  const patch: Data = {};  for (const col of t.columns) {    if (col.computed) continue;    const is = row.data[col.key] ?? null;    const was = wanted[col.key] ?? null;    if (JSON.stringify(is) !== JSON.stringify(was)) patch[col.key] = was;  }  // A sealed record's blob, its key and its version go back as they were, together.  for (const k of SEAL_FIELDS) if (JSON.stringify(row.data[k] ?? null) !== JSON.stringify(wanted[k] ?? null)) patch[k] = wanted[k] ?? null;  sealTogether(patch, wanted);  if (!Object.keys(patch).length) refuse(409, "already_so", same);  return engine.update(row, patch, version, outcome);}/** * A write back that carries any of a sealed record's three seal fields carries all three: an entry keeps only the * columns that changed (since 22 Nov 2026), and a phone that seals a record again under the same key version changes * sealed_enc and dek_enc but not seal_v. The missing ones are taken from `from`, the record as the write leaves the * rest of it (undo: as it stands, which no later write has moved; restore: as the change left it). */function sealTogether(patch: Data, from: Data): Data {  if (SEAL_FIELDS.some((k) => k in patch)) for (const k of SEAL_FIELDS) if (!(k in patch)) patch[k] = from[k] ?? null;  return patch;}/** * What change `c` wrote, as values: its logged `after` when it holds them (an entry from before 22 Nov 2026), else * the columns it names, worked back from the record (`stateAfter`); null for a delete, an import, or one that can no * longer be worked back. */export function afterOf(store: Store, c: ChangeRow): Data | null {  const keys = keysOnly(c.after);  if (!keys) return c.after;  try {    const state = stateAfter(store, c);    return state === null ? null : Object.fromEntries(keys.map((k) => [k, state[k] ?? null]));  } catch {    return null;  }}