/** * The change log over Cotton MCP (src/changes.ts): * * - `undo { change_id }`: takes one change back, if its record was not * written since (else `changed_since`); the undo is a change of its own, * so undoing it does the change again. * - `restore_version { table, id, change_id }`: rewrites the record to how * that change left it. * - `list_changes { table?, id?, since?, limit? }`: the log, the latest first. */import { boundedLimit, fail, isoTimestamp, optionalString, typeData, typeToolContext } from"../../context.ts";import { afterOf, changeOf, restoreVersion, undo } from"../../../changes.ts";importtype { ChangeRow, Cond } from"../../../store.ts";import { TOKEN_TABLE } from"../../../tokens.ts";import { project, recordJson } from"./shape.ts";import { idArg, resolveTable, tableArg, visibleTables, typeTable } from"./table.ts";import { isSealedTable, openStored } from"../window.ts";import { isSealedRow } from"../../../seal.ts";import { refuse } from"../../../http.ts";importtype { TableKeys } from"../../../window.ts";/** Who wrote a change, in words: the token's name, the signed-in person's, or the owner's own hand. */function bylines(ctx: ToolContext): (actor: string | null) => string {const said = newMap<string, string>();return (actor) => {if (actor === null) return"the owner";let name = said.get(actor);if (name === undefined) {const token = ctx.store.get(TOKEN_TABLE, actor); name = typeof token?.data.name === "string" && token.data.name ? token.data.name : (ctx.store.person(actor)?.name ?? actor); said.set(actor, name); }return name; };}function changeView(t: Table, c: ChangeRow, byline: (actor: string | null) => string): Data {return { change_id: c.id, at: c.at, byline: byline(c.actor), via: c.via, table: c.table, record_id: c.record_id, kind: c.kind, before: c.before ? project(t, c.before) : null, after: c.after ? project(t, c.after) : null, undone_by: c.undone_by, };}/** The record as it now stands, or null when it is gone. */function standing(ctx: ToolContext, t: Table, id: string): Data | null {const row = ctx.store.any(t.id, id);return row && !row.deleted ? recordJson(t, row) : null;}exportasyncfunction undoTool(ctx: ToolContext, args: Data): Promise<Data> {if (args.change_id === undefined || args.change_id === null) fail("change_id is required: the change_id a write answered");const c = changeOf(ctx.store, args.change_id);const t = resolveTable(ctx, c.table); refuseSealKeyChange(c);// ADMIN KEYS 4: an undo writes the table its change touched, through the same guard as every write. ctx.writable(c.table); ctx.write((w) => undo(w.engine, w.journal, c, w.version, w.outcome));const done = ctx.store.change(c.id)!;return { undone: changeView(t, { ...done, after: afterOf(ctx.store, done) }, bylines(ctx)), record: standing(ctx, t, c.record_id) };}exportasyncfunction restoreVersionTool(ctx: ToolContext, args: Data): Promise<Data> {const t = resolveTable(ctx, tableArg(args), args.table);const id = idArg(args);if (args.change_id === undefined || args.change_id === null) fail("change_id is required: the change, from list_changes, whose version to put back");const c = changeOf(ctx.store, args.change_id);if (c.table !== t.id || c.record_id !== id) fail(`change ${c.id} is not of that record: it changed ${c.table} ${c.record_id}`); refuseSealKeyChange(c); ctx.writable(c.table); ctx.write((w) => restoreVersion(w.engine, w.journal, c, w.version, w.outcome));return { restored: changeView(t, { ...c, after: afterOf(ctx.store, c) }, bylines(ctx)), record: standing(ctx, t, id) };}/** * A seal key (the data key's wrap) is never rolled back by an assistant: its writes are the owner's devices', checked as * they are written, which undo would pass by. undo and restore_version are MCP tools alone, so every caller is an assistant. */function refuseSealKeyChange(c: ChangeRow): void {if (c.table === "seal_key") refuse(403, "owner_only", "only the owner's own devices write seal keys");// VAULT GUARD 2 item 4: a vault key row is never put back by undo or restore: the wrap it would bring back may be of// another key, and the identity the object keeps beside it (src/vault_identity.ts) would no longer be its own.if (c.table === "vault_key") refuse(403, "owner_only", "a vault key is changed only by the owner's own devices");}/** * A logged before or after as a window reads it: a sealed one opened with its * own version's key (the journal keeps ciphertext, so the change opens as the * row it was), or said parked by name. Outside a window a sealed one shows * only its clear columns. */asyncfunction openLogged(ctx: ToolContext, t: Table, keys: TableKeys | null, recordId: string, data: Data | null): Promise<Data | null> {if (!data || !keys || !isSealedRow(data)) return data;const { row, parked } = await openStored(ctx, t, keys, { table: t.id, id: recordId, data, version: 0, owner: null, deleted: false, created_at: "", updated_at: "" });return parked ? { ...data, sealed: parked } : row.data;}exportasyncfunction listChanges(ctx: ToolContext, args: Data): Promise<Data> {const limit = boundedLimit(args, 50, 200);const where: Cond[] = [];const tables = newMap(visibleTables(ctx).map((t) => [t.id, t]));if (args.table !== undefined && args.table !== null) {const t = resolveTable(ctx, tableArg(args), args.table); where.push({ sql: "table_id = ?", args: [t.id] }); } else where.push({ sql: "table_id IN (SELECT value FROM json_each(?))", args: [JSON.stringify([...tables.keys()])] });const id = optionalString(args, "id");if (id !== null) where.push({ sql: "record_id = ?", args: [id] });const asked = optionalString(args, "since");if (asked !== null) {const since = isoTimestamp(asked) ?? fail(`since is an instant (2026-10-25T09:00:00Z); ${JSON.stringify(asked)} is not one`); where.push({ sql: "at >= ?", args: [since] }); }const rows = ctx.store.changes(where, limit + 1);const byline = bylines(ctx);// A sealed table's changes open in this token's window, when one is open for it; none is asked for here.const keys = newMap<string, TableKeys | null>();const changes: Data[] = [];for (const c of rows.slice(0, limit)) {const t = tables.get(c.table)!;if (isSealedTable(t) && !keys.has(t.id)) keys.set(t.id, await ctx.window.keys(t.id));const k = keys.get(t.id) ?? null;// An entry keeps what a create or update wrote only by name: its values are worked back from the record (src/changes.ts).const before = await openLogged(ctx, t, k, c.record_id, c.before);const after = await openLogged(ctx, t, k, c.record_id, afterOf(ctx.store, c)); changes.push(changeView(t, { ...c, before, after }, byline)); }return { changes, more: rows.length > limit };}