/** * The bin, over the deletion mark delete_record sets: a record of a table * with a bin column (`trashed_at`, `deleted_at`) is binned by that column * holding the moment it went, and stays a live row until it is erased. * * - `list_bin { table?, limit? }`: binned records, the latest binned first. * - `restore_from_bin { table, id }`: clears the mark; the record is back in * every list, in one version. * - `empty_bin { table?, older_than? }`: erases binned records for good — * each leaves the tombstone a deleted row leaves, so a phone drops it too. * Never a table in NOT_EMPTIED_BY_AN_ASSISTANT (EMPTY BIN 1). */import { boundedLimit, fail, isoTimestamp, optionalString, typeData, typeToolContext } from"../../context.ts";import { col, typeOf, typeCond, typeStoredRow } from"../../../store.ts";import { changeJson, readData, recordJson } from"./shape.ts";import { idArg, lowerFirst, noLongerHere, resolveTable, tableArg, visibleTables, typeTable } from"./table.ts";import { joinMoment } from"./zone.ts";/** * EMPTY BIN 1 (coordinator, 27 Nov 2026): the tables whose Bin holds records the person did not bin, so an * assistant's empty_bin (every MCP tool call is a token's) never erases them, named or not, older_than or not; * only the owner's devices empty them (a phone's Bin, `/v1/act` delete with `erase`). What bins without the person: * - message: the WhatsApp timer bins what it ends (meta.cotton.timer_binned, inside the seal: the server cannot * tell which), and declining a group bins its messages (chat.group.decide); * - thread: declining a group bins the chat (chat.group.decide); * - photo: the photo prune bins the photos whose original never came up (src/photo_prune.ts), to be put back. */exportconst NOT_EMPTIED_BY_AN_ASSISTANT: ReadonlySet<string> = newSet(["message", "thread", "photo"]);/** How many binned records one empty_bin erases; past it the answer says `more`. */const EMPTY_MAX = 1000;function binnedSql(bin: string): Cond {return { sql: `${typeOf(bin)} = 'text' AND ${col(bin)} <> ''`, args: [] };}function noBin(t: Table): never { fail(`${t.plural} have no bin: a deleted ${lowerFirst(t.name)} is gone for good`);}/** The table named, or every table that keeps a bin. */function binTables(ctx: ToolContext, args: Data): { t: Table; bin: string }[] {if (args.table !== undefined && args.table !== null) {const t = resolveTable(ctx, tableArg(args), args.table);return [{ t, bin: t.binColumn ?? noBin(t) }]; }return visibleTables(ctx).flatMap((t) => (t.binColumn ? [{ t, bin: t.binColumn }] : []));}exportfunction listBin(ctx: ToolContext, args: Data): Data {const limit = boundedLimit(args, 25, 200);const found: { t: Table; row: StoredRow; at: string }[] = [];for (const { t, bin } of binTables(ctx, args)) {// Along a partial index of binned rows (READ COST): the page, never the table.const rows = ctx.store.binnedLatest(t.id, bin, limit + 1) ?? ctx.store.select(t.id, [binnedSql(bin)], `${col(bin)} DESC, id`, limit + 1);for (const row of rows) found.push({ t, row, at: String(row.data[bin]) }); } found.sort((a, b) => (a.at === b.at ? a.row.id.localeCompare(b.row.id) : a.at < b.at ? 1 : -1));return { records: found.slice(0, limit).map(({ t, row }) => recordJson(t, row)), more: found.length > limit };}exportfunction restoreFromBin(ctx: ToolContext, args: Data): Data {const t = resolveTable(ctx, tableArg(args), args.table);const bin = t.binColumn ?? noBin(t);const id = idArg(args);const row = ctx.get(t.id, id) ?? fail(noLongerHere(t));const day = t.binned(row);if (day === null) fail(`That ${lowerFirst(t.name)} is not in the bin`); ctx.write((w) => { w.journal.kind = "restore"; w.update(row, { [bin]: null }); });const after = ctx.get(t.id, id) ?? fail(noLongerHere(t));return { change: changeJson(ctx, t, "update", id, { [bin]: day, updated_at: row.updated_at }, { [bin]: null }, readData(t, after.data), "back"), record: recordJson(t, after) };}/** `older_than` as an instant: a day from its start in the owner's zone, or an instant with its offset. */function cutoff(ctx: ToolContext, args: Data): string | null {const asked = optionalString(args, "older_than");if (asked === null) returnnull;if (/^\d{4}-\d{2}-\d{2}$/.test(asked)) return joinMoment(asked, null, ctx.timezone);const at = /(Z|[+-]\d{2}:?\d{2})$/i.test(asked) ? isoTimestamp(asked) : null;return at ?? fail(`older_than is a day (YYYY-MM-DD, in the owner's zone) or an instant with its offset (2026-10-25T09:00:00Z); ${JSON.stringify(asked)} is not one`);}/** * AUDIT C 3: an assistant (every MCP call is a key's) erases only what has sat in the Bin this long, so whatever it * binned, or was made to bin, stays recoverable from the owner's devices for this many days. */exportconst ASSISTANT_BIN_DAYS = 30;exportfunction emptyBin(ctx: ToolContext, args: Data): Data {const asked = cutoff(ctx, args);const floor = newDate(Date.parse(ctx.now) - ASSISTANT_BIN_DAYS * 86_400_000).toISOString();const before = asked && Date.parse(asked) < Date.parse(floor) ? asked : floor;const all = binTables(ctx, args);const named = args.table !== undefined && args.table !== null;if (named && NOT_EMPTIED_BY_AN_ASSISTANT.has(all[0]!.t.id)) { fail(`${all[0]!.t.plural}' Bin is emptied only on the owner's devices: it holds ${lowerFirst(all[0]!.t.plural)} the owner did not bin (a chat's timer, a declined group, the photo prune), so an assistant never erases them`); }// What goes is read first: a bin with nothing to erase moves no version.const doomed: StoredRow[] = [];const erased: Record<string, number> = {};const kept = all.filter(({ t }) => NOT_EMPTIED_BY_AN_ASSISTANT.has(t.id)).map(({ t }) => t.id);let more = false;for (const { t, bin } of all.filter(({ t }) => !NOT_EMPTIED_BY_AN_ASSISTANT.has(t.id))) {const where = [binnedSql(bin), ...(before ? [{ sql: `julianday(${col(bin)}) < julianday(?)`, args: [before] }] : [])];const room = EMPTY_MAX - doomed.length;const rows = ctx.store.select(t.id, where, `${col(bin)}, id`, room + 1);const going = rows.slice(0, room); doomed.push(...going);if (going.length) erased[t.id] = going.length;if (rows.length > room) { more = true;break; } }if (doomed.length) ctx.write((w) => doomed.forEach((row) => w.delete(row)));return { erased: doomed.length, tables: erased, more, ...(kept.length ? { left_for_the_owner: kept } : {}) };}