Cotton code
232 lines · 10.5 KB · TypeScriptRaw
/** * OPEN TABLES (owner, 24 Nov 2026; assets/design/shared/OPEN-TABLES.md §2): the session tools and the project writes * over tables that may be sealed (project, session, session_task, prompt, session_message), one call at a time. * * While a table is open (no `seal` block in the object's own view, which the lock keeps open until every grant holds * the table's key) everything here passes rows and writes through unchanged, so nothing moves on deploy. * * Sealed, a READ opens only the rows a tool asks for, each once per call, with the window's keys (Your Claude's * standing grant): a list of 50 sessions opens 50 rows, never the 3,257 the owner holds; a prompt search opens only its * blind-token matches. A row that does not open is left out and counted (`parked`), never answered blank. With no key * and a sealed row held, `need` answers `window_needed` (window.ts), as a sealed read does everywhere. * * A WRITE is sealed before it is stored: with the window's key when the call holds one (its blind tokens beside it), or * sealed on arrival to the owner's key when it does not (R2, records/write.ts `arriving`), so a hook with no grant still * logs its session. A change of clear columns alone goes as it is; any other is laid over the opened row and its whole * sealed half is sealed again. * * SYNCHRONOUS PASSES. A tool that must read, decide and write with nothing in between (log_session) cannot await * inside its pass: an await lets another call onto the object's thread. So `read` and `prepare` answer from what this * call has already opened and sealed, and note what they lacked (`lacking`); the tool's pass then writes nothing, the * tool awaits `fill`, and runs the pass again. The pass that writes saw every row it writes over, opened, and holds every * value it writes, sealed. An open table never lacks anything, so it never costs a second pass. */import { fail, type Data, type ToolContext, type Writer } from "../context.ts";import type { StoredRow } from "../../store.ts";import { parseSeal, SEAL_FIELDS, type SealSpec } from "../../seal.ts";import type { TableKeys } from "../../window.ts";import { arriving, sealedWrite, stored as storedValues } from "./records/write.ts";import { resolveTable, type Table } from "./records/table.ts";import { holdsSealed, isSealedTable, needWindow, openStored, READ_REASON } from "./window.ts";/** A row's values as they are to be stored, and its blind tokens when it was sealed with a window's key. */export interface Prepared {  data: Data;  tokens: string[] | null;}interface One {  table: Table;  spec: SealSpec | null;  keys: TableKeys | null;  /** Sealed rows are held and this call has no key: a read of them asks for a window. */  holds: boolean;  /** Opened rows by `id@version`; null for a row that did not open. */  opened: Map<string, StoredRow | null>;}type Want = { kind: "open"; table: string; row: StoredRow } | { kind: "seal"; key: string; table: string; id: string; values: Data; patch: Data | null };export class SealedRows {  /** Rows a read left out because they did not open. */  parked = 0;  private readonly ctx: ToolContext;  private readonly tables: Map<string, One>;  private readonly prepared = new Map<string, Prepared>();  private wants: Want[] = [];  private constructor(ctx: ToolContext, tables: Map<string, One>) {    this.ctx = ctx;    this.tables = tables;  }  /** The tables `ids` names that the database defines, each with this call's keys when sealed. */  static async of(ctx: ToolContext, ids: readonly string[]): Promise<SealedRows> {    const tables = new Map<string, One>();    for (const id of ids) {      if (!ctx.defs().table(id)) continue;      const table = resolveTable(ctx, id);      const spec = isSealedTable(table) ? parseSeal(table.def as unknown as Data) : null;      const keys = spec ? await ctx.window.keys(table.id) : null;      tables.set(id, { table, spec, keys, holds: !!spec && !keys && holdsSealed(ctx, table), opened: new Map() });    }    return new SealedRows(ctx, tables);  }  /** Is the table sealed in the object's own view? */  sealed(table: string): boolean {    return !!this.tables.get(table)?.spec;  }  /** The window's keys of a sealed table, when this call holds them. */  keys(table: string): TableKeys | null {    return this.tables.get(table)?.keys ?? null;  }  /** Asks for a window (throws `window_needed`) when a read of these tables would meet a sealed row it cannot open. */  async need(tables: readonly string[]): Promise<void> {    const lacking = tables.map((t) => this.tables.get(t)).filter((t): t is One => !!t && t.holds);    if (lacking.length) await needWindow(this.ctx, lacking.map((t) => t.table), READ_REASON);  }  /** Did a `read` or `prepare` since the last `fill` lack something? */  lacking(): boolean {    return this.wants.length > 0;  }  /** Opens and seals what the last pass lacked. */  async fill(): Promise<void> {    const wants = this.wants;    this.wants = [];    for (const want of wants) {      const t = this.tables.get(want.table)!;      if (want.kind === "open") {        const said = await openStored(this.ctx, t.table, t.keys, want.row);        t.opened.set(rowKey(want.row), said.parked ? null : said.row);        if (said.parked) this.parked++;      } else if (!this.prepared.has(want.key)) {        this.prepared.set(want.key, await this.sealNow(t, want.id, want.values, want.patch));      }    }  }  /** The rows as this pass reads them: opened when sealed, the ones that do not open left out; any not opened yet noted. */  read(table: string, rows: Iterable<StoredRow>): StoredRow[] {    const t = this.tables.get(table);    const list = [...rows];    if (!t?.spec || !t.keys) return list;    const out: StoredRow[] = [];    for (const row of list) {      if (row.data.sealed_enc == null) {        out.push(row);        continue;      }      const open = t.opened.get(rowKey(row));      if (open === undefined) this.wants.push({ kind: "open", table, row });      else if (open) out.push(open);    }    return out;  }  /** Opens the rows now (for a tool with no synchronous pass). */  async open(table: string, rows: Iterable<StoredRow>): Promise<StoredRow[]> {    const list = [...rows];    this.read(table, list);    await this.fill();    return this.read(table, list);  }  /** One row opened now, or null when it is not held or does not open. */  async get(table: string, id: string): Promise<StoredRow | null> {    const row = this.ctx.get(table, id);    return row ? ((await this.open(table, [row]))[0] ?? null) : null;  }  /** A new row's values as stored (sealed when the table is), or null when this pass must `fill` first. */  create(table: string, id: string, data: Data): Prepared | null {    const t = this.tables.get(table);    if (!t?.spec) return { data, tokens: null };    return this.held(table, id, data, null);  }  /**   * A change to a held row as stored: clear columns alone as they are; any other the whole row sealed again, laid over   * the row opened. Null when this pass must `fill` first.   */  patch(table: string, held: StoredRow, patch: Data): Prepared | null {    const t = this.tables.get(table);    if (!t?.spec || Object.keys(patch).every((k) => t.spec!.clear.includes(k))) return { data: patch, tokens: null };    let base: Data;    if (held.data.sealed_enc == null) base = held.data;    else {      if (!t.keys) fail(`this ${t.table.id} is sealed and this call holds no window to change it: ask the owner to allow Your Claude on the phone`, { code: "window_needed" });      const open = t.opened.get(rowKey(held));      if (open === undefined) {        this.wants.push({ kind: "open", table, row: held });        return null;      }      if (open === null) fail(`${t.table.id} ${held.id} does not open with this window's keys: it is not changed`, { code: "parked" });      base = open.data;    }    const wanted: Data = {};    for (const [k, v] of Object.entries(base)) 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;    }    return this.held(table, held.id, wanted, patch);  }  /** `create`, filled now (for a tool with no synchronous pass). */  async createNow(table: string, id: string, data: Data): Promise<Prepared> {    const ready = this.create(table, id, data);    if (ready) return ready;    await this.fill();    return this.create(table, id, data) ?? fail(`${table} ${id} could not be sealed`);  }  /** `patch`, filled now (for a tool with no synchronous pass). */  async patchNow(table: string, held: StoredRow, patch: Data): Promise<Prepared> {    for (let i = 0; i < 3; i++) {      const ready = this.patch(table, held, patch);      if (ready) return ready;      await this.fill();    }    return fail(`${table} ${held.id} could not be sealed`);  }  /** Writes a prepared new row, with its blind tokens. */  made(w: Writer, table: string, id: string, p: Prepared, stamps: { created_at?: string; updated_at?: string } = {}): StoredRow {    const row = w.create(table, p.data, { id, ...stamps });    if (p.tokens) this.ctx.store.setBlind(table, id, p.tokens);    return row;  }  /** Writes a prepared change over the row as stored (never as opened), with its blind tokens. */  changed(w: Writer, table: string, held: StoredRow, p: Prepared, stamps: { updated_at?: string } = {}): StoredRow {    // The row as the store holds it: a view's opened row is never handed to a write (window.ts openedView).    const row = w.update(this.ctx.store.get(table, held.id) ?? held, p.data, stamps);    if (p.tokens) this.ctx.store.setBlind(table, held.id, p.tokens);    return row;  }  private held(table: string, id: string, values: Data, patch: Data | null): Prepared | null {    const key = JSON.stringify([table, id, values, patch]);    const ready = this.prepared.get(key);    if (ready) return ready;    this.wants.push({ kind: "seal", key, table, id, values, patch });    return null;  }  private async sealNow(t: One, id: string, values: Data, patch: Data | null): Promise<Prepared> {    const stored = storedValues(t.table, values);    const p = t.keys ? await sealedWrite(this.ctx, t.table, t.keys, id, stored) : { data: await arriving(this.ctx, t.table, id, stored), tokens: null };    // A clear column the patch cleared is written as null so the engine sees it move.    if (patch) for (const [k, v] of Object.entries(patch)) if (v === null && !(k in p.data)) p.data[k] = null;    return p;  }}function rowKey(row: StoredRow): string {  return `${row.id}@${row.version}`;}