/**
* `create_record`, `update_record`, `delete_record` over a made table
* (tables/mod.rs `create_record_as`, `patch_record`, `delete_and_record`).
* Each write runs through the definitions engine in one transaction, so its
* automations run and a refusal anywhere rolls everything back; each answers
* `{ change, record }`.
*
* A record of a table with a bin column (`trashed_at`, `deleted_at`) waits in
* the bin when deleted, its day set there; any other is gone — the object
* keeps a tombstone so a phone drops it too. Either is taken back with undo
* while the change log holds the delete (src/changes.ts).
*
* A SEALED table is written inside the owner's window for this assistant
* (ruling R4 §5): the object seals the row with the window's table key at the
* table's current version, as a phone would, and keeps its blind tokens; the
* write is logged where the owner sees it. Outside a window a new record is
* sealed at arrival (e2e rulings R2, src/arrival.ts) to the person's arrival
* key, which the object holds and cannot open with: the assistant writes it
* and cannot read it back, and the owner's phone seals it again under the
* table's key. With no arrival key held yet, and for any edit (the object
* cannot read the row it would change), the write is refused by name,
* `window_needed`, and a request is filed.
*/
import { fail, type Data, type ToolContext } from "../../context.ts";
import { toolRules } from "../../../engine.ts";
import type { StoredRow } from "../../../store.ts";
import { PERSON_KEY_TABLE } from "../../../allowlist.ts";
import { RETIRED_TABLES, retiredRefusal } from "../../../protocol.ts";
import { WINDOW_TABLES } from "../../../window.ts";
import { isSealedRow, openRow, parseSeal, rowTokens, sealValues, SealError, SEAL_FIELDS, splitSealed } from "../../../seal.ts";
import type { TableKeys } from "../../../window.ts";
import { isSealedTable, openedJson, windowFor, windowNote } from "../window.ts";
import { ARRIVAL_ROW, keyFromText, sealAtArrival } from "../../../arrival.ts";
import * as tokenScopes from "../../../token_scopes.ts";
import { changeJson, readData, recordJson } from "./shape.ts";
import { idArg, noLongerHere, resolveTable, tableArg, type Table } from "./table.ts";
import { applyPicks, type Picks } from "./picks.ts";
import { PRODUCED_BY_THE_OBJECT, sameJson, validateCreate, validatePatch, withoutUnchangedReadonly } from "./values.ts";
/** A claim table a reservation rule owns is written by its own verbs (reservations.rs); an unlock table only by the unlock acts. */
function refuseReservation(ctx: ToolContext, t: Table): void {
if (t.id === PERSON_KEY_TABLE) fail("person_key is published by the owner's phone itself, never written over MCP");
// Token scopes on (src/token_scopes.ts, ROUTES-AUDIT finding 9): no token writes the account's keys and credentials.
if (tokenScopes.PROTECTED.has(t.id) && tokenScopes.readSwitch(ctx.store.meta(tokenScopes.META)) !== null) fail(`${t.id} holds the account's keys and credentials: a token never writes it`);
if (WINDOW_TABLES.has(t.id)) fail(`${t.id} is written only when the owner answers an unlock request on their phone: ask with request_unlock`);
const owned = ctx.store
.definitions("tool")
.map(toolRules)
.some((tool) => tool.reserve?.claim_table === t.id);
if (owned) fail(`${t.id} is a claim table its reservation owns: book with run_act { act: "book" } and cancel with run_act { act: "cancel" }`);
}
/** Every link names a live record of its table (`check_links`). */
function checkLinks(ctx: ToolContext, t: Table, values: Data): void {
for (const [key, value] of Object.entries(values)) {
const c = t.column(key);
if (!c || c.type !== "link" || !c.link_to || typeof value !== "string") continue;
const target = resolveTable(ctx, c.link_to);
const row = ctx.get(target.id, value);
if (!row || target.binned(row) !== null) fail(`${JSON.stringify(key)} links to ${c.link_to}, and there is no ${c.link_to} ${JSON.stringify(value)}`);
}
}
/** A row's stored values in the definition's order, nulls left out: what a change's before and after say. */
export function stored(t: Table, data: Data): Data {
const out: Data = {};
for (const c of t.columns) if (data[c.key] !== null && data[c.key] !== undefined) out[c.key] = data[c.key];
return out;
}
/** The table key a window seals a write with: the table's current seal version (its `seal_key` row `v:
`, 1 when none), which the window must hold. */
function sealingKey(ctx: ToolContext, t: Table, keys: TableKeys): { tk: Uint8Array; v: number } {
const said = ctx.sealRow(`v:${t.id}`)?.data.v;
const v = typeof said === "number" && Number.isInteger(said) && said >= 1 ? said : 1;
const tk = keys.tk.get(v) ?? fail(`${t.plural} moved to a newer key than this window holds: ask again with request_unlock`, { code: "seal_key_missing" });
return { tk, v };
}
/** The person's arrival key (seal_key row `arrival`, e2e rulings R2) when a device of theirs has handed it to the object. */
export function arrivalKey(ctx: ToolContext): Uint8Array | null {
return keyFromText(ctx.sealRow(ARRIVAL_ROW)?.data.pub);
}
/**
* A row a tool of the object's own makes (a document it stores, a bundle it
* zips): sealed at arrival to the person's key when its table is sealed
* (e2e rulings R2), as it is otherwise.
*/
export async function arriving(ctx: ToolContext, t: Table, id: string, data: Data): Promise {
if (!isSealedTable(t)) return data;
const arrival = arrivalKey(ctx) ?? fail(`${t.plural} are sealed, and no phone has handed the object its arrival key yet: open a Cotton app signed in on the phone that holds the key, then ask again`, { code: "no_arrival_key" });
const spec = parseSeal(t.def as unknown as Data) ?? fail(`${t.id} is not sealed`);
return sealAtArrival(arrival, ctx.database.id, t.id, id, spec, data);
}
/** A sealed write's values, sealed: the clear half as it is, the rest in the three seal fields; and the row's blind tokens. */
export async function sealedWrite(ctx: ToolContext, t: Table, keys: TableKeys, id: string, values: Data): Promise<{ data: Data; tokens: string[] }> {
const spec = parseSeal(t.def as unknown as Data) ?? fail(`${t.id} is not sealed`);
const { tk, v } = sealingKey(ctx, t, keys);
const { clear, sealed } = splitSealed(spec, values);
return { data: { ...clear, ...(await sealValues(tk, v, ctx.database.id, t.id, id, sealed)) }, tokens: await rowTokens(keys.bk, t.def as unknown as Data, spec, values) };
}
/** The writer a write validates as: the caller's token, or the object's own verb writing what it works out (`produced`). */
function writer(ctx: ToolContext, produced: boolean): string {
return produced ? PRODUCED_BY_THE_OBJECT : ctx.caller.tokenId;
}
export async function createRecord(ctx: ToolContext, args: Data, picks: Picks = new Map(), produced = false): Promise {
const t = resolveTable(ctx, tableArg(args), args.table);
refuseReservation(ctx, t);
if (RETIRED_TABLES.has(t.id)) fail(retiredRefusal(t.id));
if (args.data === undefined || args.data === null) fail("data is required: an object of column keys and values");
const sealedTable = isSealedTable(t);
const keys = sealedTable ? await ctx.window.keys(t.id) : null;
const arrival = sealedTable && !keys ? arrivalKey(ctx) : null;
if (sealedTable && !keys && !arrival) await windowFor(ctx, t, "create_record");
const clean = validateCreate(t, args.data, writer(ctx, produced));
applyPicks(t, clean, picks);
checkLinks(ctx, t, clean);
const id = crypto.randomUUID();
if (arrival) {
const spec = parseSeal(t.def as unknown as Data) ?? fail(`${t.id} is not sealed`);
const data = await sealAtArrival(arrival, ctx.database.id, t.id, id, spec, clean);
ctx.write((w) => w.create(t.id, data, { id }));
const row = ctx.get(t.id, id) ?? fail(noLongerHere(t));
// What the object can say of it: its clear columns. The rest it sealed and cannot read back.
const record = recordJson(t, row);
const said = (record.data ?? {}) as Data;
record.data = Object.fromEntries(Object.entries(said).filter(([key]) => key === "id" || spec.clear.includes(key)));
return { change: changeJson(ctx, t, "create", id, null, stored(t, clean), readData(t, clean)), record: { ...record, sealed: "sealed_at_arrival" }, sealed_at_arrival: `${t.plural} are sealed: this one was sealed as it arrived, to the owner's own key. Only their devices open it; reading it back needs a window (request_unlock).` };
}
if (keys) {
const { data, tokens } = await sealedWrite(ctx, t, keys, id, clean);
ctx.write((w) => {
w.create(t.id, data, { id });
ctx.store.setBlind(t.id, id, tokens);
});
const row = ctx.get(t.id, id) ?? fail(noLongerHere(t));
return { change: changeJson(ctx, t, "create", id, null, stored(t, clean), readData(t, clean)), record: await openedJson(ctx, t, keys, row), ...windowNote(keys) };
}
ctx.write((w) => w.create(t.id, clean, { id }));
const row = ctx.get(t.id, id) ?? fail(noLongerHere(t));
return { change: changeJson(ctx, t, "create", id, null, stored(t, row.data), readData(t, row.data)), record: recordJson(t, row) };
}
/** What Google Calendar holds of an event it sends: nothing writes to Google today, so a change here would be undone by the next pull (Cotton Days, 20 Nov 2026). */
const GOOGLE_HELD = ["title", "notes", "location", "starts_at", "ends_at", "all_day", "rrule", "exdates"];
export const GOOGLE_READ_ONLY = "This event is from Google Calendar. Change its time and title in Google.";
/** A Google event's time and title are refused, with the sentence a phone shows; the person's own mark, note (your_note), group and alert are theirs. */
export function refuseGoogleHeld(ctx: ToolContext, table: string, id: string, patch: unknown): void {
if (table !== "event" || typeof patch !== "object" || patch === null) return;
const held = ctx.get("event", id);
if (!held) return;
const master = typeof held.data.series_id === "string" ? ctx.get("event", held.data.series_id) : null;
const google = typeof held.data.gcal_id === "string" || typeof master?.data.gcal_id === "string";
if (google && Object.keys(patch).some((key) => GOOGLE_HELD.includes(key))) fail(GOOGLE_READ_ONLY);
}
export async function updateRecord(ctx: ToolContext, args: Data, picks: Picks = new Map(), produced = false): Promise {
const t = resolveTable(ctx, tableArg(args), args.table);
refuseReservation(ctx, t);
const id = idArg(args);
if (args.patch === undefined || args.patch === null) fail("patch is required: an object of column keys and values");
refuseGoogleHeld(ctx, t.id, id, args.patch);
if (isSealedTable(t)) return updateSealed(ctx, t, id, args.patch, picks, await windowFor(ctx, t, "update_record"), produced);
const held = ctx.get(t.id, id);
const asked = held ? withoutUnchangedReadonly(t, args.patch, held.data) : args.patch;
const patch = validatePatch(t, asked, writer(ctx, produced));
applyPicks(t, patch, picks);
checkLinks(ctx, t, patch);
const before = live(t, held);
const wanted: Data = { ...before.data };
for (const [k, v] of Object.entries(patch)) {
if (v === null) delete wanted[k];
else wanted[k] = v;
}
if (sameJson(stored(t, wanted), stored(t, before.data))) fail("the patch changes nothing");
// A cleared key is written as null so the engine sees it move.
const write: Data = {};
for (const [k, v] of Object.entries(patch)) if (!sameJson(v ?? null, before.data[k] ?? null)) write[k] = v;
ctx.write((w) => w.update(before, write));
const after = ctx.get(t.id, id) ?? fail(noLongerHere(t));
const was = stored(t, before.data);
const is = stored(t, after.data);
const b: Data = {};
const a: Data = {};
for (const c of t.columns) {
if (sameJson(was[c.key] ?? null, is[c.key] ?? null)) continue;
b[c.key] = was[c.key] ?? null;
a[c.key] = is[c.key] ?? null;
}
if (!Object.keys(a).length) fail("the patch changes nothing");
b.updated_at = before.updated_at;
return { change: changeJson(ctx, t, "update", id, b, a, readData(t, after.data)), record: recordJson(t, after) };
}
/** `update_record` on a sealed table, in a window: the row opened with its own version's key, the patch laid over it, and the whole sealed half sealed again at the current version with a fresh DEK. `update_todo` writes a sealed to-do through it too. */
export async function updateSealed(ctx: ToolContext, t: Table, id: string, rawPatch: unknown, picks: Picks, keys: TableKeys | null, produced = false, checked = false): Promise {
if (!keys) fail(`${t.plural} are sealed`);
const held = live(t, ctx.get(t.id, id));
let open: Data = held.data;
if (isSealedRow(held.data)) {
const v = held.data.seal_v;
try {
open = await openRow(typeof v === "number" ? (keys.tk.get(v) ?? null) : null, ctx.database.id, t.id, id, held.data);
} catch (error) {
if (error instanceof SealError) fail(`this ${t.name.toLowerCase()} does not open with this window's keys (${error.code}): it is not changed`, { code: error.code });
throw error;
}
}
const before: StoredRow = { ...held, data: open };
// `checked`: a patch its own tool has already made and checked (update_todo's due moments and completed_at), laid as it is.
const patch = checked ? { ...(rawPatch as Data) } : validatePatch(t, withoutUnchangedReadonly(t, rawPatch, open), writer(ctx, produced));
applyPicks(t, patch, picks);
checkLinks(ctx, t, patch);
const wanted: Data = {};
for (const [k, v] of Object.entries(open)) if (!(SEAL_FIELDS as readonly string[]).includes(k)) wanted[k] = v;
for (const [k, v] of Object.entries(patch)) {
if (v === null) delete wanted[k];
else wanted[k] = v;
}
if (sameJson(stored(t, wanted), stored(t, open))) fail("the patch changes nothing");
const { data, tokens } = await sealedWrite(ctx, t, keys, id, stored(t, wanted));
// A clear column the patch cleared is written as null so the engine sees it move.
for (const [k, v] of Object.entries(patch)) if (v === null && !(k in data)) data[k] = null;
ctx.write((w) => {
w.update(held, data);
ctx.store.setBlind(t.id, id, tokens);
});
const after = ctx.get(t.id, id) ?? fail(noLongerHere(t));
const was = stored(t, open);
const is = stored(t, wanted);
const b: Data = {};
const a: Data = {};
for (const c of t.columns) {
if (sameJson(was[c.key] ?? null, is[c.key] ?? null)) continue;
b[c.key] = was[c.key] ?? null;
a[c.key] = is[c.key] ?? null;
}
b.updated_at = before.updated_at;
return { change: changeJson(ctx, t, "update", id, b, a, readData(t, wanted)), record: await openedJson(ctx, t, keys, after), ...windowNote(keys) };
}
export function deleteRecord(ctx: ToolContext, args: Data): Data {
const t = resolveTable(ctx, tableArg(args), args.table);
refuseReservation(ctx, t);
const id = idArg(args);
const before = live(t, ctx.get(t.id, id));
const bin = t.binColumn;
const whole = { ...stored(t, before.data), updated_at: before.updated_at };
if (bin) {
ctx.write((w) => {
w.journal.kind = "delete";
w.update(before, { [bin]: ctx.now });
});
const now = ctx.get(t.id, id) ?? fail(noLongerHere(t));
return { change: changeJson(ctx, t, "delete", id, whole, null, null, "bin"), record: recordJson(t, now) };
}
const gone = ctx.write((w) => w.delete(before));
// The tombstone keeps no values; the answer says what the record held as it went.
const record = recordJson(t, { ...before, updated_at: gone.updated_at });
record.deleted_at = gone.updated_at;
return { change: changeJson(ctx, t, "delete", id, whole, null, null, "gone"), record };
}
function live(t: Table, row: StoredRow | null): StoredRow {
if (!row || t.binned(row) !== null) fail(noLongerHere(t));
return row;
}