Cotton code
3154 lines · 169.5 KB · TypeScriptRaw
/** * The business's rows, people, codes and sessions in the object's own SQLite. * * ONE ROW TABLE FOR EVERY DEFINITION TABLE. A business row is `(table_id, id, * data JSON, owner, version, deleted)`. The definitions say what the data * holds; the object never issues DDL for a package, so a new business — or a * changed package — is JSON, never a migration. `owner` is the person a * `mine()` row belongs to, written when the row is written, so a member's read * is one indexed filter. `version` is the object's change counter stamped on * every write; a phone pulls `version > since`. A deleted row stays as a * tombstone so the phone drops it too. */import { isWitnessed, noteLogged } from "./row_witness.ts";import * as blind from "./blind.ts";import * as neverAgain from "./never_again.ts";import type { Definitions, TableDef } from "./definitions.ts";import { refuse } from "./http.ts";import { PERSONAL } from "./kits.ts";import { ruled } from "./seal.ts";import * as memoryLock from "./memory_lock.ts";import * as orderShadow from "./order_shadow.ts";import * as openTablesLock from "./open_tables_lock.ts";import { storageParts, type StorageParts } from "./storage_parts.ts";import { lastMeasure, measureDue, measureNow, measureStep, measuring, SMALL_FILE, type LinkTarget, type Measure } from "./storage_measure.ts";/** The tables the personal kit ships, by id: the ones the seal rule reads (`Store.definitions`). */const KIT_TABLES = new Set(PERSONAL.tables.map((t) => String(t.id)));import type { Role, WirePerson, WireRow } from "./protocol.ts";/** What the `definitions` table keeps: the tools, the tables, the flavour, the boards (Home and the screens a database draws as data) and the themes it wears. */export type DefinitionKind = "tool" | "table" | "flavour" | "board" | "theme";export type { StoredRow } from "./stored_row.ts";import type { StoredRow } from "./stored_row.ts";import * as sealWide from "./seal_wide.ts";/** Times a write carries over from another database instead of taking now. */export interface Stamps {  created_at?: string;  updated_at?: string;}/** A place in the change order: the last row a page carried. */export interface Cursor {  version: number;  table: string;  id: string;}/** A row's place in a first order: its `by` value (null as ''), then its id. */export type FirstKey = [SqlStorageValue, string];/** One table's first order in a pass (src/first.ts `planFirst`), frozen in the pass's cursor. */export interface FirstSpec {  table: string;  by: string;  asc: boolean;  /** Rows that come first: of the table, or of each group; null is every row. */  rows: number | null;  /** Rows with any of these columns set wait for the tail. */  unless: string[];  /** Only rows whose `by` is from `from` and before `to` come first. */  around: { from: string; to: string } | null;  /** Each group (a row of `of`, in `of`'s own order by `by`) brings its first rows. */  per: { column: string; of: string; by: string; asc: boolean; groups: number | null; early: number | null } | null;  /** A small table (src/business.ts SMALL_TABLE_ROWS): its tail comes before the other tables, so it stands whole early, as every small table does. */  soon: boolean;  /**   * A late table (src/first.ts `late`): its first rows wait for the group run, after every table that is not late,   * and its spec stands after theirs, so its tail comes after theirs too. Absent in a cursor from before the word.   */  late?: boolean;}/** The runs of a pass carrying first rows first, in their order. */export type FirstRun = "lead" | "early" | "small" | "group" | "soon" | "soonrest" | "change" | "tail" | "rest";/** * Where such a pass stands: the run, the spec or small table (`i`), the last * row carried there (`key`), how many rows that slice or group has carried * (`n`), and in the group run the group (`group`) and how many groups came. */export interface FirstAt {  run: FirstRun;  i: number;  key: FirstKey | null;  n: number;  group: FirstKey | null;  groups: number;  change: Cursor | null;}/** A pass carrying first rows first: its id (the groups' cuts are kept under it), small tables, specs, and each ungrouped spec's cut. */export interface FirstPlan {  pass: string;  small: string[];  specs: FirstSpec[];  /** The last row each ungrouped spec carried first: the rows at or before it in its order came. */  cuts: (FirstKey | null)[];  /** Where each grouped spec's early groups ended (the last early group, and how many came): the group run goes on after it. */  from?: ({ group: FirstKey; groups: number } | null)[];}/** Who reads: the owner reads every table; anyone else the tables their role may read whole, and their own rows of their own tables. *//** The rows a sync may carry: everything, or whole tables plus a person's own rows; `except` names the object's internal tables (tokens, OAuth state), which no device holds. */export type SyncScope = ({ kind: "all" } | { kind: "tables"; whole: Set<string>; own: Set<string>; person: string | null }) & { except: Set<string> };/** A table the phone keeps only from a day on: rows whose `column` is before `from` stay out. */export interface SyncWindow {  table: string;  column: string;  from: string;  /**   * A kit's `only` (21 Nov 2026): the live rows of `table` whose clear `column` holds one of these values, and no   * other live row of it (Words keeps the documents that are web pages and the memories' project links, never every   * document or link). A tombstone still comes. `from` is "" for such a window.   */  is?: string[];}export interface Person {  id: string;  phone: string;  name: string | null;  role: Exclude<Role, "public">;  created_at: string;  version: number;}export const SCHEMA = `CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);CREATE TABLE IF NOT EXISTS definitions (id TEXT PRIMARY KEY, kind TEXT NOT NULL, json TEXT NOT NULL);-- Moved by every write to definitions, whatever writes it (SLOW READ, 26 Nov 2026): the object's parsed definitions are-- kept per instance and read again only when this moves (src/business.ts \`definitions\`).CREATE TABLE IF NOT EXISTS definitions_version (one INTEGER PRIMARY KEY CHECK (one = 1), n INTEGER NOT NULL);INSERT OR IGNORE INTO definitions_version (one, n) VALUES (1, 0);CREATE TRIGGER IF NOT EXISTS definitions_written_insert AFTER INSERT ON definitions BEGIN UPDATE definitions_version SET n = n + 1; END;CREATE TRIGGER IF NOT EXISTS definitions_written_update AFTER UPDATE ON definitions BEGIN UPDATE definitions_version SET n = n + 1; END;CREATE TRIGGER IF NOT EXISTS definitions_written_delete AFTER DELETE ON definitions BEGIN UPDATE definitions_version SET n = n + 1; END;CREATE TABLE IF NOT EXISTS rows (  table_id TEXT NOT NULL, id TEXT NOT NULL, data TEXT NOT NULL, owner TEXT,  version INTEGER NOT NULL, deleted INTEGER NOT NULL DEFAULT 0,  created_at TEXT NOT NULL, updated_at TEXT NOT NULL,  PRIMARY KEY (table_id, id));DROP INDEX IF EXISTS rows_version;CREATE INDEX IF NOT EXISTS rows_cursor ON rows (version, table_id, id);CREATE INDEX IF NOT EXISTS rows_owner ON rows (table_id, owner);CREATE INDEX IF NOT EXISTS rows_made ON rows (table_id, created_at, id);CREATE INDEX IF NOT EXISTS rows_message_external ON rows (json_extract(data, '$.external_id')) WHERE table_id = 'message' AND deleted = 0;CREATE INDEX IF NOT EXISTS rows_message_minute ON rows (json_extract(data, '$.thread_id'), json_extract(data, '$.sent_at')) WHERE table_id = 'message' AND deleted = 0;CREATE INDEX IF NOT EXISTS rows_contact_handle ON rows (json_extract(data, '$.value')) WHERE table_id = 'message_contact_handle' AND deleted = 0;CREATE INDEX IF NOT EXISTS rows_contact_phone ON rows (json_extract(data, '$.phone_e164')) WHERE table_id = 'message_contact' AND deleted = 0;CREATE INDEX IF NOT EXISTS rows_thread_key ON rows (json_extract(data, '$.external_key')) WHERE table_id = 'thread' AND deleted = 0;CREATE TABLE IF NOT EXISTS links (  table_id TEXT NOT NULL, id TEXT NOT NULL, column TEXT NOT NULL, target TEXT NOT NULL,  PRIMARY KEY (table_id, id, column));CREATE INDEX IF NOT EXISTS links_target ON links (table_id, column, target);-- AUDIT D: a list link column's elements (a note's people, a photo's people), one row each, so "the rows whose list-- holds X" is a seek, not a read of the whole table. Filled for older rows a step at a time (Store.listLinksStep).CREATE TABLE IF NOT EXISTS list_links (  table_id TEXT NOT NULL, column TEXT NOT NULL, target TEXT NOT NULL, id TEXT NOT NULL,  PRIMARY KEY (table_id, column, target, id)) WITHOUT ROWID;CREATE INDEX IF NOT EXISTS list_links_row ON list_links (table_id, id);CREATE TABLE IF NOT EXISTS row_counts (  table_id TEXT NOT NULL, day TEXT NOT NULL, deleted INTEGER NOT NULL, n INTEGER NOT NULL,  PRIMARY KEY (table_id, day, deleted));CREATE TABLE IF NOT EXISTS people (  id TEXT PRIMARY KEY, phone TEXT NOT NULL UNIQUE, name TEXT, role TEXT NOT NULL,  created_at TEXT NOT NULL, version INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS codes (  id TEXT PRIMARY KEY, phone TEXT NOT NULL, code_hash TEXT NOT NULL, device_id TEXT NOT NULL,  expires_at INTEGER NOT NULL, tries INTEGER NOT NULL DEFAULT 0, used INTEGER NOT NULL DEFAULT 0,  created_at INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS codes_phone ON codes (phone, created_at);CREATE TABLE IF NOT EXISTS sessions (  token_hash TEXT PRIMARY KEY, person_id TEXT NOT NULL, device_id TEXT NOT NULL,  issued_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS acts (  id TEXT PRIMARY KEY, at TEXT NOT NULL, person_id TEXT, act TEXT NOT NULL, args TEXT NOT NULL, outcome TEXT NOT NULL);CREATE TABLE IF NOT EXISTS change (  id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, actor TEXT, via TEXT, table_id TEXT NOT NULL, record_id TEXT NOT NULL,  kind TEXT NOT NULL, before TEXT, after TEXT, version INTEGER NOT NULL, undone_by INTEGER);CREATE INDEX IF NOT EXISTS change_record ON change (table_id, record_id, id);CREATE INDEX IF NOT EXISTS change_at ON change (at);CREATE TABLE IF NOT EXISTS change_size (one INTEGER PRIMARY KEY CHECK (one = 1), bytes INTEGER NOT NULL, below INTEGER NOT NULL);CREATE TRIGGER IF NOT EXISTS change_size_in AFTER INSERT ON change BEGIN  UPDATE change_size SET bytes = bytes + coalesce(length(NEW.before), 0) + coalesce(length(NEW.after), 0) WHERE NEW.id > below;END;CREATE TRIGGER IF NOT EXISTS change_size_out AFTER DELETE ON change BEGIN  UPDATE change_size SET bytes = bytes - coalesce(length(OLD.before), 0) - coalesce(length(OLD.after), 0) WHERE OLD.id > below;END;CREATE TRIGGER IF NOT EXISTS change_size_up AFTER UPDATE OF before, after ON change BEGIN  UPDATE change_size SET bytes = bytes + coalesce(length(NEW.before), 0) + coalesce(length(NEW.after), 0) - coalesce(length(OLD.before), 0) - coalesce(length(OLD.after), 0) WHERE NEW.id > below;END;CREATE TABLE IF NOT EXISTS blind_row (rid INTEGER PRIMARY KEY, table_id TEXT NOT NULL, id TEXT NOT NULL, toks BLOB, UNIQUE (table_id, id));CREATE TABLE IF NOT EXISTS blind (tok INTEGER NOT NULL, rid INTEGER NOT NULL, PRIMARY KEY (tok, rid)) WITHOUT ROWID;CREATE TABLE IF NOT EXISTS first_pass (pass TEXT PRIMARY KEY, made INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS first_cut (pass TEXT NOT NULL, tbl TEXT NOT NULL, grp, seq INTEGER NOT NULL, at, id TEXT NOT NULL, PRIMARY KEY (pass, tbl, grp)) WITHOUT ROWID;CREATE INDEX IF NOT EXISTS first_cut_seq ON first_cut (pass, tbl, seq);`;type Sql = SqlStorage;/** One SQL condition over a table's rows, with its bound values: `json_extract(data, '$."status"') = ?`. */export interface Cond {  sql: string;  args: SqlStorageValue[];}const KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;/** A sync page closes once its rows hold this much (MAIL ALL ON PHONE, 24 Nov 2026): ~700 sealed mails. */export const PAGE_BYTES = 4 * 1024 * 1024;/** The most rows one read of a sync page takes: a page closes between reads, so it holds at most PAGE_BYTES and one read (~9 MB at the largest mails). */export const READ_ROWS = 100;/** * MAIL SYNC BOUNDED (24 Nov 2026): the version-index entries one page's walk may pass. A walk in change order reads * every entry of the tables a scope leaves out on its way to the next row it carries (650,393 rows on one page of * Comms' pass from nothing on a 2.4 GB invented object). Past this many the page ends where the walk stands, and * the next walks on from that version (Store.walkTop). */export const PAGE_READS = 100_000;/** * A walk's resume point names no table: "~" sorts after every table id ([a-z0-9_]), so the next page starts past its * version; and it is Latin-1, as a cursor must be (writeCursor's btoa). */const WALK_PAST = "~";/** Each stored row's size as read, for the page's bytes. */const STORED_BYTES = new WeakMap<StoredRow, number>();/** A row's column as SQL: its data value by key, or the row's own frame (id, times). *//** The meta key holding the media folders still to delete. */const MEDIA_TO_DROP = "media_to_drop";/** How many values one IN list of a statement binds at most: a Durable Object statement binds at most 100 in all, and an IN list of 45 with what else it binds stays under 50. */export const IN_LIST_MOST = 45;/** `values` in parts of at most IN_LIST_MOST, each one statement's IN list. */export function bound<T>(values: T[]): T[][] {  const parts: T[][] = [];  for (let i = 0; i < values.length; i += IN_LIST_MOST) parts.push(values.slice(i, i + IN_LIST_MOST));  return parts;}export function col(key: string): string {  if (key === "id" || key === "created_at" || key === "updated_at") return key;  if (!KEY.test(key)) refuse(400, "bad_column", `${JSON.stringify(key)} is not a column key`);  return `json_extract(data, '$."${key}"')`;}/** * `json_type` of a row's data value by key: 'text', 'integer', 'real', * 'true', 'false', 'object', 'array', or 'null' — absent reads as null too, so * a test on the type is never SQL NULL and a NOT around it means what it says. */export function typeOf(key: string): string {  if (!KEY.test(key)) refuse(400, "bad_column", `${JSON.stringify(key)} is not a column key`);  return `COALESCE(json_type(data, '$."${key}"'), 'null')`;}/** The meta key holding the row counts' plan: the date column each counted table was counted by, and the tables still to count, the first from after `after`. *//** The order indexes reads asked for (Store.selectOrdered), by name, each with the statement that makes it. */const ORDER_INDEXES = "order_indexes_wanted";/** Below this file size a pass's first-order index is made in the request (Store.firstIndexes); above, by the alarm. */export const FIRST_INDEX_NOW_BYTES = 64 * 1024 * 1024;/** * LIVE CPU 3 (24 Nov 2026): at or above this file size no order index is made at all, not even by the alarm. Making one * reads every row of the file whatever its WHERE (1.4 million rows, 9 to 12 s, on an invented 1.9 GB object), so on his * 3.7 GB object the alarm ran past its CPU limit, was reset, rolled the index back and tried again, and every request in * the object then waited and failed. Reads there keep the order they had before these indexes. */export const ORDER_INDEX_MAX_BYTES = 256 * 1024 * 1024;/** A lookup shadow (READ COST) is asked for only on a table with at least this many live rows; a smaller one is walked. */export const LOOKUP_SHADOW_LEAST = 5_000;/** JOBS OUT PROOF: a dev account's file counts as past ORDER_INDEX_MAX_BYTES (set only by the dev Worker's seed). */export const DEV_INDEX_TOO_BIG = "dev_index_too_big";const COUNT_PLAN = "row_counts_plan";interface CountPlan {  /** Each dated table's column, as counted (or as it will be once its recount ends); an undated table is absent. */  by: Record<string, string>;  /** The tables still to count, in order, each by its column (`""`: undated); their counts in `row_counts` are partial. */  queue: { table: string; column: string }[];  /** The last id the head of the queue was counted to; null before its first step. */  after: string | null;  /** Progress, for `countsProgress` (never a row's content): rows the head was counted to, steps taken, when it began and when the last step ran. */  headRows?: number;  steps?: number;  began?: string;  stepAt?: string;}/** Whether `a` sorts after `b` as SQLite's BINARY collation sorts text (by UTF-8 bytes), which `ORDER BY id` walks. */export function sqlTextAfter(a: string, b: string): boolean {  // eslint-disable-next-line no-control-regex  if (/^[\u0000-\u007f]*$/.test(a) && /^[\u0000-\u007f]*$/.test(b)) return a > b;  const x = new TextEncoder().encode(a);  const y = new TextEncoder().encode(b);  for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i]! > y[i]!;  return x.length > y.length;}/** The most changes one trim deletes. */export const TRIM_STEP = 10_000;/** About how many characters of the change log one trim step takes (Store.trimChanges): 32 MB of entries a transaction. *//** * One row's write, refused in words when the object's SQLite cannot hold it ("string or blob too big"): a 500 there * stopped a Mac's run on the same row every time, with nothing said of why (the Mac's mail, 23 Nov 2026). */function keepingRow(table: string, id: string, text: string, write: () => unknown): void {  try {    write();  } catch (error) {    if (error instanceof Error && /SQLITE_TOOBIG|string or blob too big/.test(error.message)) {      refuse(413, "row_too_large", `${table} ${id} is too large to keep (${text.length} characters): send it smaller`);    }    throw error;  }}export const CHANGE_STEP_CHARS = 32_000_000;/** How many rows a page of a keyed scan reads. */const SCAN_PAGE = 500;/** Where the list links fill stands (AUDIT D, Store.listLinksStep), and that it is done. */const LIST_LINKS_AT = "list_links_at";const LIST_LINKS_DONE = "list_links_done";export class Store {  private readonly sql: Sql;  private readonly now: () => Date;  /** The link columns of each table, so a row's links are indexed as it is written and a rollup or a lookup finds its rows by index. */  private linkColumns = new Map<string, string[]>();  /** Each dated table's date column, from the definitions: what a sync window keeps a table by. */  private dateColumns = new Map<string, string>();  /** RESTORE AUDIT 2: a logged write on a token or device row keeps what the row now holds (src/row_witness.ts). */  witnessLogged(table: string, id: string, before: Record<string, unknown> | null, after: Record<string, unknown>): void {    if (isWitnessed(table)) noteLogged(this.sql, table, id, before, after);  }  constructor(sql: Sql, now: () => Date) {    this.sql = sql;    this.now = now;  }  // ── row counts ─────────────────────────────────────────────────────────  //  // HOW MANY ROWS A PHONE HOLDS, WITHOUT READING THEM (sync status, 26 Oct  // 2026). A pass says the live rows a phone ends holding, and counting them  // in SQL reads every row up to the version, about a second per million on  // the personal object, which blocks the object for every pass of every  // phone. So the store keeps `row_counts`: each table's rows by the day of  // its date column (the column a window keeps it by), live and tombstones  // apart, kept by every write here. A window is then a sum over days.  //  // A RECOUNT IS NEVER ONE STATEMENT (21 Nov 2026). It was: one GROUP BY over  // every row of a table, which sorts them all in a temporary B-tree, and on  // the personal object (about 800,000 rows, a few tables of 300,000 with  // sealed bodies) it ran out of SQLite's memory and every sync answered 500  // for hours. Now a table is counted again only when its own date column  // changed (a kit gaining a dated table recounts that table, nothing else; a  // table losing its date folds its days into one, reading no row), and a  // recount walks the table along its primary key a few thousand rows at a  // time, its place kept in meta (`row_counts_plan`), so any request picks it  // up where the last left it: each pass's count carries one step, and the  // alarm carries steps within a time bound until it is done. A write to a  // table being recounted is counted only when its row is behind the place  // reached (the walk counts the rest). Until every table is counted, passes  // count in SQL, as they did before `row_counts`.  /** Tell the store which column dates each table; a table whose column differs from the one `row_counts` holds it by is counted again. */  setDateColumns(columns: Map<string, string>): void {    this.dateColumns = columns;    this.datesKnown = true;  }  /** Whether the definitions' date columns were given: a store that was never told never replans the counts by an empty set. */  private datesKnown = false;  /**   * Rows one recount step reads: bounded memory, CPU and transaction per step   * whatever the table's size. 500 rows of the personal object's largest   * bodies is well under a second of reading. A test lowers it in place.   */  recountChunk = 500;  /** The plan as meta holds it, parsed once per text: read on every write, so a transaction rolled back never leaves a stale plan in memory. */  private planText: string | null = null;  private planParsed: CountPlan | null = null;  private countPlan(): CountPlan | null {    const raw = this.meta(COUNT_PLAN);    if (raw !== this.planText) {      this.planText = raw;      this.planParsed = raw ? (JSON.parse(raw) as CountPlan) : null;    }    return this.planParsed;  }  private saveCountPlan(plan: CountPlan): void {    const text = JSON.stringify(plan);    this.setMeta(COUNT_PLAN, text);    this.planText = text;    this.planParsed = plan;  }  /** A table's date column under `plan` (`""`: undated), whether queued for its recount or counted. */  private static planned(plan: CountPlan, table: string): string {    return plan.queue.find((q) => q.table === table)?.column ?? plan.by[table] ?? "";  }  /**   * Bring the plan to the definitions' date columns: each table whose column   * differs is queued for its recount (its counts dropped), folded into one   * day when it lost its date, or simply marked when it holds no row. With no   * plan at all (never counted, or counted before plans, when a failed   * recount could leave the counts half deleted) every table is queued.   */  private replanCounts(): CountPlan {    let plan = this.countPlan();    if (!plan) {      this.sql.exec("DELETE FROM row_counts");      this.setMeta("row_counts_by", null);      const queue = this.tablesHeld().map((table) => ({ table, column: this.dateColumns.get(table) ?? "" }));      plan = { by: Object.fromEntries(this.dateColumns), queue, after: null, headRows: 0, steps: 0, began: this.now().toISOString() };      this.saveCountPlan(plan);      return plan;    }    const tables = new Set([...Object.keys(plan.by), ...plan.queue.map((q) => q.table), ...this.dateColumns.keys()]);    let changed = false;    for (const table of tables) {      const want = this.dateColumns.get(table) ?? "";      if (Store.planned(plan, table) === want) continue;      if (!changed) plan = structuredClone(plan);      changed = true;      const at = plan.queue.findIndex((q) => q.table === table);      if (want === "") delete plan.by[table];      else plan.by[table] = want;      if (at >= 0) {        // Queued already: counted again by the new column, from its start.        plan.queue[at]!.column = want;        if (at === 0) [plan.after, plan.headRows] = [null, 0];        this.sql.exec("DELETE FROM row_counts WHERE table_id = ?", table);      } else if (!this.sql.exec("SELECT 1 FROM rows WHERE table_id = ? LIMIT 1", table).toArray().length) {        this.sql.exec("DELETE FROM row_counts WHERE table_id = ?", table);      } else if (want === "") {        // Undated now: every live row's days fold into one, from the counts alone.        const sums = this.sql.exec<{ deleted: number; n: number }>("SELECT deleted, SUM(n) AS n FROM row_counts WHERE table_id = ? GROUP BY deleted", table).toArray();        this.sql.exec("DELETE FROM row_counts WHERE table_id = ?", table);        for (const s of sums) this.sql.exec("INSERT INTO row_counts (table_id, day, deleted, n) VALUES (?, '', ?, ?)", table, s.deleted, Number(s.n));      } else {        this.sql.exec("DELETE FROM row_counts WHERE table_id = ?", table);        plan.queue.push({ table, column: want });      }    }    if (changed) this.saveCountPlan(plan);    return plan;  }  /** The SQL for a row's day under `column` (as `dayOf` says it): `""` for undated. */  private static daySql(column: string): string {    if (column === "") return "''";    if (!KEY.test(column)) refuse(400, "bad_column", `${JSON.stringify(column)} is not a column key`);    const own = column === "created_at" || column === "updated_at";    const value = own ? column : `json_extract(data, '$."${column}"')`;    const kind = own ? "'text'" : `json_type(data, '$."${column}"')`;    return `CASE WHEN deleted = 1 THEN '' WHEN ${kind} IS NULL OR ${kind} = 'null' THEN '' WHEN ${kind} = 'text' AND ${value} <> '' THEN substr(${value}, 1, 10) ELSE '0' END`;  }  /**   * One step of the recount: the next `recountChunk` rows of the table at the   * head of the queue, along its primary key, added to its counts; the table   * done when the step reads fewer. False once nothing is left to count.   */  private recountStep(plan: CountPlan): boolean {    const head = plan.queue[0];    if (!head) return false;    const after = plan.after;    const rows = this.sql      .exec<{ id: string; day: string; deleted: number }>(        `SELECT id, ${Store.daySql(head.column)} AS day, deleted FROM rows WHERE table_id = ?${after === null ? "" : " AND id > ?"} ORDER BY id LIMIT ?`,        head.table,        ...(after === null ? [] : [after]),        this.recountChunk,      )      .toArray();    const sums = new Map<string, { day: string; deleted: number; n: number }>();    for (const r of rows) {      const k = `${r.deleted}\u0000${r.day}`;      const s = sums.get(k);      if (s) s.n += 1;      else sums.set(k, { day: r.day, deleted: r.deleted, n: 1 });    }    for (const s of sums.values()) {      this.sql.exec("INSERT INTO row_counts (table_id, day, deleted, n) VALUES (?, ?, ?, ?) ON CONFLICT (table_id, day, deleted) DO UPDATE SET n = n + excluded.n", head.table, s.day, s.deleted, s.n);    }    const next = structuredClone(plan);    next.steps = (next.steps ?? 0) + 1;    next.stepAt = this.now().toISOString();    if (rows.length < this.recountChunk) {      next.queue.shift();      next.after = null;      next.headRows = 0;    } else {      next.after = rows[rows.length - 1]!.id;      next.headRows = (next.headRows ?? 0) + rows.length;    }    this.saveCountPlan(next);    return next.queue.length > 0;  }  /**   * Carry the recount on by at most `steps` steps: what the alarm runs   * (src/business.ts), each step in a transaction of its own. Bounded by   * steps, never by time: a Worker's clock does not move while its code runs,   * so a loop until a time ran the whole recount in one transaction on the   * personal object, its storage timed out and the object was reset (live,   * 21 Nov 2026). True while rows are left to count.   */  carryCounts(steps: number, inTransaction: (step: () => void) => void = (step) => step()): boolean {    if (!this.datesKnown) return false;    inTransaction(() => void this.replanCounts());    for (let i = 0; i < steps && (this.countPlan()?.queue.length ?? 0) > 0; i++) inTransaction(() => void this.recountStep(this.countPlan()!));    return (this.countPlan()?.queue.length ?? 0) > 0;  }  /** How far the recount stands, from its plan alone (table names, columns and numbers, never a row): `GET /v1/admin/row-counts`. */  countsProgress(): { ready: boolean; planned: boolean; left: { table: string; column: string }[]; head_rows: number; steps: number; began: string | null; last_step: string | null; step_rows: number; failed_at: string | null } {    const plan = this.countPlan();    return {      ready: plan !== null && plan.queue.length === 0,      planned: plan !== null,      left: plan?.queue ?? [],      head_rows: plan?.headRows ?? 0,      steps: plan?.steps ?? 0,      began: plan?.began ?? null,      last_step: plan?.stepAt ?? null,      step_rows: this.recountChunk,      failed_at: this.countsFailedAt ? new Date(this.countsFailedAt).toISOString() : null,    };  }  /** Whether a recount is under way: the object keeps its alarm close until it ends. */  countsPending(): boolean {    const plan = this.countPlan();    if (!plan) return this.datesKnown;    return plan.queue.length > 0;  }  /**   * The day a row is counted under: its date column's first ten characters,   * `""` for no date (a window keeps it), `"0"` for a value a window's text   * comparison puts before every day (an empty text, a number, a flag). A   * tombstone is always `""`: a window never holds one back.   */  private static dayOf(column: string, row: { data: Record<string, unknown>; deleted: boolean; created_at: string; updated_at: string }): string {    if (!column || row.deleted) return "";    const value = column === "created_at" ? row.created_at : column === "updated_at" ? row.updated_at : row.data[column];    if (value === null || value === undefined) return "";    return typeof value === "string" && value !== "" ? value.slice(0, 10) : "0";  }  /** Count `row` in (`by` 1) or out (`by` -1) of `row_counts`, once a plan exists: a table waiting for its recount is left to it, and so is a row the recount has not reached. */  private counted(row: { table: string; id: string; data: Record<string, unknown>; deleted: boolean; created_at: string; updated_at: string }, by: 1 | -1): void {    const plan = this.countPlan();    if (!plan) return;    const at = plan.queue.findIndex((q) => q.table === row.table);    if (at > 0) return;    if (at === 0 && (plan.after === null || sqlTextAfter(row.id, plan.after))) return;    const column = at === 0 ? plan.queue[0]!.column : (plan.by[row.table] ?? "");    this.sql.exec(      "INSERT INTO row_counts (table_id, day, deleted, n) VALUES (?, ?, ?, ?) ON CONFLICT (table_id, day, deleted) DO UPDATE SET n = n + excluded.n",      row.table,      Store.dayOf(column, row),      row.deleted ? 1 : 0,      by,    );  }  /** When the last recount step failed, in ms: a step that cannot finish is not tried again on every pass. */  private countsFailedAt = 0;  /**   * Whether `row_counts` can be read now: every table counted by the date   * column the definitions give it. A pass that finds the recount under way   * carries it one step and counts in SQL; counts are a figure for the   * progress line, never a reason to refuse a pass, so a step that fails is   * logged and tried again in ten minutes.   */  private countsReady(): boolean {    if (!this.datesKnown) return false;    const now = this.now().getTime();    if (this.countsFailedAt && now - this.countsFailedAt < 600_000) return false;    try {      const plan = this.replanCounts();      if (!plan.queue.length) return true;      this.recountStep(plan);      this.countsFailedAt = 0;      return this.countPlan()!.queue.length === 0;    } catch (e) {      this.countsFailedAt = now;      console.warn(`cottondb: row_counts recount step failed, counting in SQL: ${e instanceof Error ? e.message : String(e)}`);      return false;    }  }  // ── links index ────────────────────────────────────────────────────────  /** Tell the store which columns are links; a definitions change calls `relink` after, with the ones it held before. */  /** How many writes the definitions have had (the triggers above), or null where the counter is not kept. */  definitionsVersion(): number | null {    try {      const row = this.sql.exec<{ n: number }>("SELECT n FROM definitions_version WHERE one = 1").toArray()[0];      return row ? Number(row.n) : null;    } catch {      return null;    }  }  setLinkColumns(columns: Map<string, string[]>): void {    this.linkColumns = columns;  }  /**   * Bring the links index from the link columns it was kept by (`was`) to the   * ones the store holds now, in SQL: a column no longer a link drops its   * links, a column newly a link indexes its table's live rows, and every   * other link stands, since a definition moves no row. Never the whole index   * again: the personal object holds 800,000 rows and millions of links, and   * rebuilding them on a kit that grew one table took 27 s of the object's CPU   * in one transaction, its storage timing out and the object reset (29 Oct   * 2026).   */  relink(was: Map<string, string[]>): void {    const pairs = (columns: Map<string, string[]>): Map<string, [string, string]> => new Map([...columns].flatMap(([table, keys]) => keys.map((key): [string, [string, string]] => [JSON.stringify([table, key]), [table, key]])));    const before = pairs(was);    const after = pairs(this.linkColumns);    for (const [pair, [table, column]] of before) {      if (after.has(pair)) continue;      this.sql.exec("DELETE FROM links WHERE table_id = ? AND column = ?", table, column);      this.sql.exec("DELETE FROM list_links WHERE table_id = ? AND column = ?", table, column);    }    for (const [pair, [table, column]] of after) {      if (before.has(pair)) continue;      const path = `$.${column}`;      this.sql.exec("DELETE FROM links WHERE table_id = ? AND column = ?", table, column);      // A column newly a link: its lists too (AUDIT D), once the fill of older rows is done (until then the fill does it).      if (this.listLinksReady()) {        this.sql.exec("DELETE FROM list_links WHERE table_id = ? AND column = ?", table, column);        this.sql.exec(          "INSERT OR IGNORE INTO list_links (table_id, column, target, id) SELECT r.table_id, ?, j.value, r.id FROM rows r, json_each(r.data, ?) j WHERE r.table_id = ? AND r.deleted = 0 AND json_type(r.data, ?) = 'array' AND j.type = 'text' AND j.value <> ''",          column,          path,          table,          path,        );      }      this.sql.exec(        "INSERT INTO links (table_id, id, column, target) SELECT table_id, id, ?, json_extract(data, ?) FROM rows WHERE table_id = ? AND deleted = 0 AND json_type(data, ?) = 'text' AND json_extract(data, ?) <> ''",        column,        path,        table,        path,        path,      );    }  }  private rowColumns: Set<string> | null = null;  /**   * SNAPSHOTS 1 (src/snapshots.ts): a row from a snapshot laid back exactly as it was stored, at its own version, with   * its links and blind tokens; one older than what is held is skipped. Only a restore from snapshots calls it, on an   * object it emptied first.   */  restoreStoredRow(line: Record<string, unknown>, tokens: string[] | null): boolean {    const table = String(line.table_id);    const id = String(line.id);    const version = Number(line.version);    const held = this.sql.exec<{ version: number }>("SELECT version FROM rows WHERE table_id = ? AND id = ?", table, id).toArray()[0];    if (held && held.version >= version) return false;    this.rowColumns ??= new Set(this.sql.exec<{ name: string }>("PRAGMA table_info(rows)").toArray().map((c) => c.name));    const columns = Object.keys(line).filter((k) => this.rowColumns!.has(k));    this.sql.exec(`INSERT OR REPLACE INTO rows (${columns.join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`, ...columns.map((c) => line[c] as SqlStorageValue));    if (Number(line.deleted)) {      this.sql.exec("DELETE FROM links WHERE table_id = ? AND id = ?", table, id);      this.sql.exec("DELETE FROM list_links WHERE table_id = ? AND id = ?", table, id);      this.setBlind(table, id, []);    } else {      this.writeLinks(table, id, JSON.parse(String(line.data)) as Record<string, unknown>);      this.setBlind(table, id, tokens ?? []);    }    return true;  }  private writeLinks(table: string, id: string, data: Record<string, unknown>): void {    this.sql.exec("DELETE FROM links WHERE table_id = ? AND id = ?", table, id);    for (const column of this.linkColumns.get(table) ?? []) {      const target = data[column];      if (typeof target === "string" && target !== "") this.sql.exec("INSERT INTO links (table_id, id, column, target) VALUES (?, ?, ?, ?)", table, id, column, target);    }    this.writeListLinks(table, id, data, true);  }  /** A row's list link elements, one `list_links` row each (AUDIT D); `fresh` drops what the row held before. */  private writeListLinks(table: string, id: string, data: Record<string, unknown>, fresh: boolean): void {    const columns = (this.linkColumns.get(table) ?? []).filter((c) => Array.isArray(data[c]));    if (fresh) this.sql.exec("DELETE FROM list_links WHERE table_id = ? AND id = ?", table, id);    for (const column of columns) {      for (const target of new Set((data[column] as unknown[]).filter((v): v is string => typeof v === "string" && v !== ""))) {        this.sql.exec("INSERT OR IGNORE INTO list_links (table_id, column, target, id) VALUES (?, ?, ?, ?)", table, column, target, id);      }    }  }  /**   * AUDIT D: the list links of rows written before `list_links` existed, filled a page at a time on the alarm, table by   * table in a keyed cursor kept in meta, so no step reads more than one page. Answers whether more is left.   */  listLinksStep(page = SCAN_PAGE): boolean {    if (this.meta(LIST_LINKS_DONE) === "1") return false;    const tables = [...this.linkColumns].filter(([, columns]) => columns.length).map(([t]) => t).sort();    if (!tables.length) return false;    const at = JSON.parse(this.meta(LIST_LINKS_AT) ?? "null") as { table: string; created_at: string; id: string } | null;    let i = at ? tables.indexOf(at.table) : 0;    if (i < 0) i = tables.findIndex((t) => t > at!.table);    if (i < 0) {      this.setMeta(LIST_LINKS_DONE, "1");      return false;    }    const table = tables[i]!;    const after = at && at.table === table ? at : { created_at: "", id: "" };    const rows = this.sql.exec<{ id: string; data: string; created_at: string }>("SELECT id, data, created_at FROM rows WHERE table_id = ? AND deleted = 0 AND (created_at, id) > (?, ?) ORDER BY created_at, id LIMIT ?", table, after.created_at, after.id, page).toArray();    for (const r of rows) {      if (!r.data.includes("[")) continue;      try {        this.writeListLinks(table, r.id, JSON.parse(r.data) as Record<string, unknown>, false);      } catch {        // A row whose data is not JSON holds no list.      }    }    const last = rows[rows.length - 1];    if (rows.length === page && last) this.setMeta(LIST_LINKS_AT, JSON.stringify({ table, created_at: last.created_at, id: last.id }));    else if (i + 1 < tables.length) this.setMeta(LIST_LINKS_AT, JSON.stringify({ table: tables[i + 1]!, created_at: "", id: "" }));    else {      this.setMeta(LIST_LINKS_DONE, "1");      return false;    }    return true;  }  /** Whether every row's list links are in `list_links` (the step above has gone through every table). */  listLinksReady(): boolean {    return this.meta(LIST_LINKS_DONE) === "1";  }  // ── landed ─────────────────────────────────────────────────────────────  private landed = false;  /**   * Rows gain `landed_at` once, the first time this object writes a row. ADD COLUMN with a constant default rewrites   * nothing: every row held before reads the moment the column came, which is no earlier than it landed and earlier   * than any cut made after it (a cut is a row, so it lands after this too).   */  private landing(): void {    if (this.landed) return;    const has = this.sql.exec<{ name: string }>("PRAGMA table_info(rows)").toArray().some((c) => c.name === "landed_at");    if (!has) {      const since = this.now().toISOString();      if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(since)) throw new Error(`landed_at default ${since}`);      this.sql.exec(`ALTER TABLE rows ADD COLUMN landed_at TEXT NOT NULL DEFAULT '${since}'`);    }    this.landed = true;  }  // ── meta ───────────────────────────────────────────────────────────────  meta(key: string): string | null {    const row = this.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", key).toArray()[0];    return row ? row.value : null;  }  setMeta(key: string, value: string | null): void {    // The sealing locks are "never again" facts: a restore lays them back (src/never_again.ts).    if (neverAgain.LEDGER_META.has(key) && this.meta(key) !== value) neverAgain.note(this.sql, { kind: "meta", key, value, at: new Date().toISOString() });    this.setMetaQuiet(key, value);  }  /** A meta value set with no ledger entry: the ledger's own replay. */  setMetaQuiet(key: string, value: string | null): void {    if (value === null) this.sql.exec("DELETE FROM meta WHERE key = ?", key);    else this.sql.exec("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", key, value);  }  /** The media folders erased rows played from, and single keys a write let go (a converted film's upload), waiting for the object to delete them from R2 (src/business.ts `dropMedia`). A folder ends in `/`. */  mediaToDrop(): string[] {    return JSON.parse(this.meta(MEDIA_TO_DROP) ?? "[]") as string[];  }  /** A folder (ending in `/`) or one key to delete once this write commits: kept in the write's own transaction, so a write rolled back drops nothing. */  dropMediaLater(folder: string): void {    const held = this.mediaToDrop();    if (!held.includes(folder)) this.setMeta(MEDIA_TO_DROP, JSON.stringify([...held, folder]));  }  /** A folder deleted (or never this database's): off the list. */  mediaDropped(folder: string): void {    const left = this.mediaToDrop().filter((f) => f !== folder);    this.setMeta(MEDIA_TO_DROP, left.length ? JSON.stringify(left) : null);  }  version(): number {    return Number(this.meta("version") ?? "0");  }  /** Every record, person, code, credential and act goes; the definitions and the business's meta stay. A development re-seed, nothing else. */  wipeRecords(): void {    for (const table of ["rows", "links", "row_counts", "people", "codes", "sessions", "acts", "change", "blind", "blind_row"]) this.sql.exec(`DELETE FROM ${table}`);  }  /** Set while the account is frozen for a restore (src/restore.ts): no row write lands, even from work already under way (M1). */  frozen = false;  /** Every device signed out at once (an account set to be deleted): written in the never-again ledger with it. */  revokeAllSessions(): void {    this.sql.exec("UPDATE sessions SET revoked = 1");    neverAgain.note(this.sql, { kind: "sessions_all_revoked", at: this.now().toISOString() });  }  bump(): number {    // The code leads the words (RESTORE 2 SERVER 4, L5): a call between objects keeps only an error's message, and the    // sender judges "try again" by this code (src/handover.ts `retryable`).    if (this.frozen) refuse(503, "account_frozen", "account_frozen: this account is frozen for a restore; not written, try again");    const next = this.version() + 1;    this.setMeta("version", String(next));    return next;  }  /** Whether `table` holds a live row. */  holdsRows(table: string): boolean {    return this.sql.exec("SELECT 1 FROM rows WHERE table_id = ? AND deleted = 0 LIMIT 1", table).toArray().length > 0;  }  // ── definitions ────────────────────────────────────────────────────────  /** The seal the rule wrote out for a table definition, by its stored text: worked out once per text, never per read. */  private readonly ruledSeals = new Map<string, unknown>();  /** Whether any definition of `kind` is held: asked on every request, so it reads one row and parses none (the kit's tables are megabytes of JSON). */  holdsDefinitions(kind: DefinitionKind): boolean {    return this.sql.exec("SELECT 1 FROM definitions WHERE kind = ? LIMIT 1", kind).toArray().length > 0;  }  /**   * The definitions of `kind`. A personal database's tables the personal kit   * ships are read through the seal rule (e2e rulings R1, src/seal.ts   * `ruled`): one with no seal block of its own is served, checked and   * enforced with the default's, so a kit table added later is sealed without   * anyone writing a block for it. A table an assistant made over MCP is as   * it was made: its rows are written by the object (the R2 seam), and a lane   * token gets no window to read them back (R4, the window lane).   */  definitions(kind: DefinitionKind): Record<string, unknown>[] {    const rows = this.sql.exec<{ json: string }>("SELECT json FROM definitions WHERE kind = ? ORDER BY id", kind).toArray();    const personal = kind === "table" && this.meta("kind") === "personal";    // The memory lock (src/memory_lock.ts): while it is on, memory's seal block is laid on every read, whatever the    // held definition or a kit keep says, so no device or keep can read memory as open again.    const lockedMemory = personal && memoryLock.readLock(this.meta(memoryLock.META)) !== null;    // The open tables lock (src/open_tables_lock.ts), the same way: the session tables and projects carry their seal blocks.    const lockedTables = personal && openTablesLock.readLock(this.meta(openTablesLock.META)) !== null;    // The passwords' own switch (src/open_tables_lock.ts SECRET_META): secret's seal block alone, with no gate.    const lockedSecret = personal && openTablesLock.readLock(this.meta(openTablesLock.SECRET_META)) !== null;    return rows.map((r) => {      const doc = JSON.parse(r.json) as Record<string, unknown>;      if (lockedMemory && doc.id === memoryLock.MEMORY) return memoryLock.locked(doc);      if (lockedTables && openTablesLock.TABLES.includes(String(doc.id))) return openTablesLock.locked(doc);      if (lockedSecret && doc.id === openTablesLock.SECRET) return openTablesLock.locked(doc);      if (!personal || !KIT_TABLES.has(String(doc.id))) return doc;      let seal = this.ruledSeals.get(r.json);      if (seal === undefined) {        seal = ruled(doc).seal ?? null;        this.ruledSeals.set(r.json, seal);      }      return seal === null || doc.seal !== undefined ? doc : { ...doc, seal };    });  }  replaceDefinitions(kind: DefinitionKind, docs: Record<string, unknown>[]): void {    this.sql.exec("DELETE FROM definitions WHERE kind = ?", kind);    for (const doc of docs) {      const id = kind === "flavour" ? "flavour" : typeof doc.id === "string" ? doc.id : null;      if (!id) refuse(400, "bad_definition", `a ${kind} definition has no id`);      this.sql.exec("INSERT INTO definitions (id, kind, json) VALUES (?, ?, ?)", `${kind}:${id}`, kind, JSON.stringify(doc));    }  }  /** Mark a sealed row as holding `columns` in the clear beside its seal, or clear its mark (src/seal_wide.ts). */  markWide(table: string, id: string, columns: readonly string[], now: string): void {    sealWide.mark(this.sql, table, id, columns, now);  }  /** The definitions of `kind` with these ids go; every other stays. */  removeDefinitions(kind: Exclude<DefinitionKind, "flavour">, ids: readonly string[]): void {    for (const id of ids) this.sql.exec("DELETE FROM definitions WHERE id = ?", `${kind}:${id}`);  }  /** Each of `docs` in place of the definition of its id, the rest of the kind left as they are; answers how many differed from what was held. */  mergeDefinitions(kind: Exclude<DefinitionKind, "flavour">, docs: Record<string, unknown>[]): number {    let changed = 0;    for (const doc of docs) {      if (typeof doc.id !== "string" || !doc.id) refuse(400, "bad_definition", `a ${kind} definition has no id`);      const key = `${kind}:${doc.id}`;      const text = JSON.stringify(doc);      const held = this.sql.exec<{ json: string }>("SELECT json FROM definitions WHERE id = ?", key).toArray()[0]?.json;      if (held === text) continue;      this.sql.exec("INSERT INTO definitions (id, kind, json) VALUES (?, ?, ?) ON CONFLICT (id) DO UPDATE SET kind = excluded.kind, json = excluded.json", key, kind, text);      changed += 1;    }    return changed;  }  // ── rows ───────────────────────────────────────────────────────────────  /** A row's weight on a page: its data as stored (read with it, never measured again), and the frame's few names. */  private static bytesOf(row: StoredRow): number {    return (STORED_BYTES.get(row) ?? 0) + 200;  }  private static row(r: { table_id: string; id: string; data: string; owner: string | null; version: number; deleted: number; created_at: string; updated_at: string; landed_at?: string | null }): StoredRow {    const made: StoredRow = {      table: r.table_id,      id: r.id,      data: JSON.parse(r.data) as Record<string, unknown>,      owner: r.owner,      version: Number(r.version),      deleted: r.deleted === 1,      created_at: r.created_at,      updated_at: r.updated_at,    };    if (typeof r.landed_at === "string") made.landed_at = r.landed_at;    STORED_BYTES.set(made, r.data.length);    return made;  }  get(table: string, id: string): StoredRow | null {    const r = this.sql      .exec<RawRow>("SELECT * FROM rows WHERE table_id = ? AND id = ? AND deleted = 0", table, id)      .toArray()[0];    return r ? Store.row(r) : null;  }  /** Live rows of a table, optionally where one JSON column equals a value. */  /** The live rows whose `column` equals `equals`, oldest first. A table is never read whole: `scan` streams one, `select` pages one. */  list(table: string, where: { column: string; equals: unknown }): StoredRow[] {    const indexed = typeof where.equals === "string" && (this.linkColumns.get(table) ?? []).includes(where.column);    const rows = indexed      ? this.sql          .exec<RawRow>(            // CROSS JOIN keeps links outer, along links_target: the planner otherwise walks the table's rows (on a million rows,            // list_sessions read 30,000 a session for its tasks, coordinator 23 Nov 2026).            "SELECT r.* FROM links l CROSS JOIN rows r ON r.table_id = l.table_id AND r.id = l.id WHERE l.table_id = ? AND l.column = ? AND l.target = ? AND r.deleted = 0 ORDER BY r.created_at, r.id",            table,            where.column,            where.equals as string,          )          .toArray()      : this.listAlong(table, where.column, where.equals as SqlStorageValue);    return rows.map(Store.row);  }  /**   * Live rows of `table` whose plain column equals `equals` (READ COST, 28 Nov 2026): `log_session` found a session by   * its external id walking every session (100k rows read for one call beside 200k). Read along a partial index of the   * one lookup, or on a file too big to make one, its shadow (Store.lookup). A table or column that is not a plain   * word, or a lookup whose index or shadow does not stand yet, is read as before.   */  private listAlong(table: string, column: string, equals: SqlStorageValue): RawRow[] {    const old = () => this.sql.exec<RawRow>("SELECT * FROM rows WHERE table_id = ? AND deleted = 0 AND json_extract(data, ?) = ? ORDER BY created_at, id", table, `$.${column}`, equals).toArray();    if (!KEY.test(table) || !KEY.test(column)) return old();    const at = `json_extract(data, '$."${column}"')`;    const name = `rows_eq_${table}__${column}`;    const along = this.lookup(name, `CREATE INDEX IF NOT EXISTS ${name} ON rows (${at}) WHERE table_id = '${table}' AND deleted = 0`, {      name: `eq_${table}__${column}`,      table,      terms: [{ expr: at }, { expr: "id" }],      live: true,      where: `${at} IS NOT NULL`,    });    if (along === "index") return this.sql.exec<RawRow>(`SELECT * FROM rows INDEXED BY ${name} WHERE table_id = '${table}' AND deleted = 0 AND ${at} = ? ORDER BY created_at, id`, equals).toArray();    if (along) return this.sql.exec<RawRow>(`SELECT rows.* FROM ${orderShadow.from(along)} WHERE ${orderShadow.value(along, 0)} = ? AND rows.deleted = 0 ORDER BY rows.created_at, rows.id`, equals).toArray();    return old();  }  /**   * What a lookup (READ COST) reads along: its partial index when it stands ("index"), else its shadow once filled (the   * spec), else null (read as before). Nothing is made in a request (LIVE CPU 3: making an index reads every row of the   * file, 9 to 12 s on a 1.9 GB object). A file under ORDER_INDEX_MAX_BYTES asks the alarm for the index   * (buildOrderIndex). A bigger one, with the account's shadow switch on, asks for the shadow, which the alarm fills a   * bounded step at a time from that one table (src/order_shadow.ts).   */  lookup(name: string, statement: string, shadow: orderShadow.Spec): "index" | orderShadow.Spec | null {    const said = (what: string, rows: number | null = null): void => {      // READ COST 3: what each lookup last did, for GET /v1/admin/order-shadow and one log line a change.      const was = this.lookupsSaid.get(shadow.name);      this.lookupsSaid.set(shadow.name, { table: shadow.table, said: what, rows, at: new Date().toISOString() });      if (was?.said !== what) console.log(`cottondb: lookup ${shadow.name}: ${what}${rows === null ? "" : ` (${rows} rows)`}`);    };    if (this.hasIndex(name)) return said("index"), "index";    if (!this.indexTooBig()) {      const wanted = this.orderIndexesWanted();      if (!(name in wanted)) this.setMeta(ORDER_INDEXES, JSON.stringify({ ...wanted, [name]: statement }));      return said("index asked of the alarm"), null;    }    const meta = this.shadowMeta();    if (!orderShadow.on(meta)) return said("walked: shadow switch off"), null;    // A small table is read as before (its walk is its few rows): a shadow's fill is spent on the tables it saves.    // Counted here, up to the floor, along the table's own key: row_counts can stand "ready" with a count far behind the    // table (READ COST 3: every lookup said under 5,000 beside 50,000 sessions, and live asked for no shadow at all).    const rows = orderShadow.ready(meta, shadow.name) ? null : this.rowsUpTo(shadow.table, LOOKUP_SHADOW_LEAST);    if (rows !== null && rows < LOOKUP_SHADOW_LEAST) return said(`walked: under ${LOOKUP_SHADOW_LEAST} rows`, rows), null;    if (orderShadow.ask(meta, shadow)) return said("shadow", rows), shadow;    return said("walked: shadow filling", rows), null;  }  /**   * A table's rows (tombstones too), counted no further than `most` along its key, the count kept ten minutes in this   * instance: what a lookup's floor reads, never the table.   */  private rowsUpTo(table: string, most: number): number {    const kept = this.rowsCounted.get(table);    if (kept && Date.now() - kept.at < 600_000) return kept.n;    const n = Number(this.sql.exec<{ n: number }>("SELECT count(*) AS n FROM (SELECT 1 FROM rows WHERE table_id = ? LIMIT ?)", table, most).one().n);    this.rowsCounted.set(table, { n, at: Date.now() });    return n;  }  private readonly rowsCounted = new Map<string, { n: number; at: number }>();  /** What each lookup last did in this instance (READ COST 3), by shadow name. */  readonly lookupsSaid = new Map<string, { table: string; said: string; rows: number | null; at: string }>();  /**   * The prompts older than a moment, for the 30-day keep and the erase (READ COST): the FROM, the WHERE (one `?`, the   * moment) and the id column, along the prompts' index, their shadow, or the table as before.   */  promptsBefore(): { from: string; where: string; id: string } {    const at = "coalesce(json_extract(data, '$.ts'), created_at)";    const along = this.lookup("rows_prompt_ts", `CREATE INDEX IF NOT EXISTS rows_prompt_ts ON rows (${at}) WHERE table_id = 'prompt' AND deleted = 0`, {      name: "prompt_ts",      table: "prompt",      terms: [{ expr: at }, { expr: "id" }],      live: true,    });    const plain = `table_id = 'prompt' AND deleted = 0 AND ${at} < ?`;    if (along === "index") return { from: "rows INDEXED BY rows_prompt_ts", where: plain, id: "id" };    if (along) {      const n = orderShadow.names(along.name);      return { from: `${n.table} AS o INDEXED BY ${n.index}`, where: `${orderShadow.value(along, 0)} < ?`, id: "o.sid" };    }    return { from: "rows", where: plain, id: "id" };  }  /** Live rows of `table` whose list column `column` (a JSON array of ids) holds `target`, oldest first (a person merge). */  listHolding(table: string, column: string, target: string): StoredRow[] {    // AUDIT D: along list_links once every row's lists are in it: a seek, not a read of every row of the table.    if (this.listLinksReady() && (this.linkColumns.get(table) ?? []).includes(column)) {      return this.sql        .exec<RawRow>(          "SELECT r.* FROM list_links l CROSS JOIN rows r ON r.table_id = l.table_id AND r.id = l.id WHERE l.table_id = ? AND l.column = ? AND l.target = ? AND r.deleted = 0 ORDER BY r.created_at, r.id",          table,          column,          target,        )        .toArray()        .map(Store.row);    }    return this.sql      .exec<RawRow>(        "SELECT * FROM rows WHERE table_id = ? AND deleted = 0 AND json_type(data, ?) = 'array' AND EXISTS (SELECT 1 FROM json_each(data, ?) WHERE value = ?) ORDER BY created_at, id",        table,        `$.${column}`,        `$.${column}`,        target,      )      .toArray()      .map(Store.row);  }  /**   * Live rows of a table, oldest first, read a page at a time by a keyed   * cursor on (created_at, id): a caller that keeps only what it needs holds   * one page, however many rows the table has.   */  *scan(table: string, where: Cond[] = []): Generator<StoredRow> {    const extra = where.map((w) => ` AND (${w.sql})`).join("");    const args = where.flatMap((w) => w.args);    let after: { created_at: string; id: string } | null = null;    for (;;) {      const page: StoredRow[] = (        after          ? this.sql.exec<RawRow>(`SELECT * FROM rows WHERE table_id = ? AND deleted = 0 AND (created_at, id) > (?, ?)${extra} ORDER BY created_at, id LIMIT ?`, table, after.created_at, after.id, ...args, SCAN_PAGE)          : this.sql.exec<RawRow>(`SELECT * FROM rows WHERE table_id = ? AND deleted = 0${extra} ORDER BY created_at, id LIMIT ?`, table, ...args, SCAN_PAGE)      )        .toArray()        .map(Store.row);      yield* page;      if (page.length < SCAN_PAGE) return;      const last: StoredRow = page[page.length - 1]!;      after = { created_at: last.created_at, id: last.id };    }  }  /** One page of a table's live rows where every condition holds, in `order` (SQL over the row; the id last). */  select(table: string, where: Cond[], order: string, limit: number, offset = 0): StoredRow[] {    const extra = where.map((w) => ` AND (${w.sql})`).join("");    return this.sql      .exec<RawRow>(`SELECT * FROM rows WHERE table_id = ? AND deleted = 0${extra} ORDER BY ${order} LIMIT ? OFFSET ?`, table, ...where.flatMap((w) => w.args), limit, offset)      .toArray()      .map(Store.row);  }  /**   * One page of a table read newest made first along rows_made: the live rows among the next `step` made before   * `before` (null: from the newest) that every condition holds for, and where the page ended (null: the table's start).   * A read of a big table a page at a time, each statement bounded (search_records, coordinator 23 Nov 2026).   */  pageBack(table: string, where: Cond[], before: { created_at: string; id: string } | null, step: number): { rows: StoredRow[]; next: { created_at: string; id: string } | null } {    const past = before ? " AND (created_at, id) < (?, ?)" : "";    const pastArgs = before ? [before.created_at, before.id] : [];    const end = this.sql      .exec<{ created_at: string; id: string }>(`SELECT created_at, id FROM rows WHERE table_id = ?${past} ORDER BY created_at DESC, id DESC LIMIT 1 OFFSET ?`, table, ...pastArgs, Math.max(0, step - 1))      .toArray()[0];    const floor = end ? " AND (created_at, id) >= (?, ?)" : "";    const floorArgs = end ? [end.created_at, end.id] : [];    const extra = where.map((w) => ` AND (${w.sql})`).join("");    const rows = this.sql      .exec<RawRow>(`SELECT * FROM rows WHERE table_id = ?${past}${floor} AND deleted = 0${extra}`, table, ...pastArgs, ...floorArgs, ...where.flatMap((w) => w.args))      .toArray()      .map(Store.row);    return { rows, next: end ? { created_at: end.created_at, id: end.id } : null };  }  /**   * A page of a big table in a made table's order (list_records), read along a partial index on exactly that order   * (the table's id written into the statement, so the planner can take it): a page reads a page, where a sort of the   * whole table read 368,000 rows and took 1.8 to 2.7 s on 200,000 prompts (coordinator, 23 Nov 2026). Making the index   * reads the whole file (about 2 s at a million rows), so a read never makes it: the first read in an order asks for it   * and answers null (sort as before), and the alarm makes it (buildOrderIndex); every read after walks it.   */  selectOrdered(table: string, where: Cond[], order: string, limit: number, offset = 0): StoredRow[] | null {    const t = Store.named(table);    let h = 0;    for (let i = 0; i < order.length; i++) h = (Math.imul(h, 31) + order.charCodeAt(i)) >>> 0;    const index = `rows_order_${t}_${h.toString(36)}`;    if (!this.hasIndex(index)) {      // ORDER INDEX: with the account's switch on, a shadow filled across alarms stands in on a file that is not small.      if (orderShadow.on(this.shadowMeta()) && this.sql.databaseSize >= FIRST_INDEX_NOW_BYTES) {        const spec: orderShadow.Spec = { name: index, table: t, terms: orderShadow.terms(order), live: true };        if (!orderShadow.ask(this.shadowMeta(), spec)) return null;        const extra = where.map((w) => ` AND (${w.sql})`).join("");        return this.sql          .exec<RawRow>(`SELECT rows.* FROM ${orderShadow.from(spec)} WHERE deleted = 0${extra} ORDER BY ${orderShadow.orderBy(spec)} LIMIT ? OFFSET ?`, ...where.flatMap((w) => w.args), limit, offset)          .toArray()          .map(Store.row);      }      if (this.indexTooBig()) return null;      const wanted = this.orderIndexesWanted();      if (!(index in wanted)) this.setMeta(ORDER_INDEXES, JSON.stringify({ ...wanted, [index]: `CREATE INDEX IF NOT EXISTS ${index} ON rows (${order}) WHERE table_id = '${t}' AND deleted = 0` }));      return null;    }    const extra = where.map((w) => ` AND (${w.sql})`).join("");    // INDEXED BY: without statistics the planner takes rows_made for the table's equality and sorts every row.    return this.sql      .exec<RawRow>(`SELECT * FROM rows INDEXED BY ${index} WHERE table_id = '${t}' AND deleted = 0${extra} ORDER BY ${order} LIMIT ? OFFSET ?`, ...where.flatMap((w) => w.args), limit, offset)      .toArray()      .map(Store.row);  }  private orderIndexesWanted(): Record<string, string> {    try {      return JSON.parse(this.meta(ORDER_INDEXES) ?? "{}") as Record<string, string>;    } catch {      return {};    }  }  /** Whether this file is too big for an order index to be made in one invocation (ORDER_INDEX_MAX_BYTES). */  indexTooBig(): boolean {    // DEV_INDEX_TOO_BIG: set only by the dev Worker's jobs proof seed (business.ts), so an invented account's file    // counts as past the limit without 256 MB of rows.    return this.sql.databaseSize >= ORDER_INDEX_MAX_BYTES || this.meta(DEV_INDEX_TOO_BIG) === "on";  }  /** Whether a read asked for an order index the alarm has still to make. */  orderIndexAsked(): boolean {    return this.meta(ORDER_INDEXES) !== null;  }  /** The alarm's share of selectOrdered: makes one order index a read asked for. Answers whether more are asked for. */  buildOrderIndex(): boolean {    // Too big to make one inside an alarm's CPU: what was asked is dropped, and reads keep their old order.    if (this.indexTooBig()) {      if (this.orderIndexAsked()) {        console.log(`cottondb: order indexes not made, the file is ${Math.round(this.sql.databaseSize / 1e6)} MB: ${Object.keys(this.orderIndexesWanted()).join(", ")}`);        this.setMeta(ORDER_INDEXES, null);      }      return false;    }    const wanted = this.orderIndexesWanted();    const [name, statement] = Object.entries(wanted)[0] ?? [];    if (!name || !statement) return false;    this.sql.exec(statement);    this.indexMade();    delete wanted[name];    this.setMeta(ORDER_INDEXES, Object.keys(wanted).length ? JSON.stringify(wanted) : null);    return Object.keys(wanted).length > 0;  }  /** A table's live rows as row_counts keeps them, or null while it is still being counted (then count in SQL). */  liveCount(table: string): number | null {    if (!this.countsReady()) return null;    return Number(this.sql.exec<{ n: number | null }>("SELECT SUM(n) AS n FROM row_counts WHERE table_id = ? AND deleted = 0", table).one().n ?? 0);  }  /** How many live rows of a table every condition holds for. */  count(table: string, where: Cond[] = []): number {    const extra = where.map((w) => ` AND (${w.sql})`).join("");    const r = this.sql.exec<{ n: number }>(`SELECT COUNT(*) AS n FROM rows WHERE table_id = ? AND deleted = 0${extra}`, table, ...where.flatMap((w) => w.args)).toArray()[0];    return r ? Number(r.n) : 0;  }  /** How many live rows of `table` link to one of `targets` by `column`, along links_target (the photo prune, src/photo_prune.ts). */  countLinks(table: string, column: string, targets: string[]): number {    let n = 0;    for (const part of bound(targets)) {      const marks = part.map(() => "?").join(", ");      n += Number(this.sql.exec<{ n: number }>(`SELECT COUNT(*) AS n FROM links WHERE table_id = ? AND column = ? AND target IN (${marks})`, table, column, ...part).one().n);    }    return n;  }  /** Which of `targets` a live row of `table` links to by `column`. */  linkSources(table: string, column: string, targets: string[]): string[] {    const found: string[] = [];    for (const part of bound(targets)) {      const marks = part.map(() => "?").join(", ");      for (const r of this.sql.exec<{ target: string }>(`SELECT DISTINCT target FROM links WHERE table_id = ? AND column = ? AND target IN (${marks})`, table, column, ...part)) found.push(r.target);    }    return found;  }  /** How many live rows of `table` hold one of `values` in any of `columns`: one walk of the table reading those columns alone, never a row's body into memory whole. */  countWhereIn(table: string, columns: string[], values: string[]): number {    if (!values.length) return 0;    const wanted = new Set(values);    const read = columns.map((c, i) => `${col(c)} AS c${i}`).join(", ");    let n = 0;    for (const r of this.sql.exec<Record<string, SqlStorageValue>>(`SELECT ${read} FROM rows WHERE table_id = ? AND deleted = 0`, table)) {      if (columns.some((_, i) => typeof r[`c${i}`] === "string" && wanted.has(r[`c${i}`] as string))) n++;    }    return n;  }  /** A page of a table's live rows in id order after `after`: id and the named columns only (the photo prune reads keys, not embeddings and previews). */  slimPage(table: string, after: string, limit: number, columns: string[]): { id: string; data: Record<string, unknown> }[] {    const read = columns.map((c, i) => `${col(c)} AS c${i}`).join(", ");    return this.sql      .exec<Record<string, SqlStorageValue>>(`SELECT id, ${read} FROM rows WHERE table_id = ? AND deleted = 0 AND id > ? ORDER BY id LIMIT ?`, table, after, limit)      .toArray()      .map((r) => ({ id: String(r.id), data: Object.fromEntries(columns.map((c, i) => [c, r[`c${i}`] ?? null])) }));  }  /** How many rows a table holds, live or deleted: whether the kit may reshape it (src/kit_keep.ts). */  held(table: string): number {    const r = this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rows WHERE table_id = ?", table).toArray()[0];    return r ? Number(r.n) : 0;  }  /** One SQL value over a table's live rows where every condition holds: `MAX(updated_at)`, `MIN(…)`. */  value(table: string, expression: string, where: Cond[] = []): SqlStorageValue {    const extra = where.map((w) => ` AND (${w.sql})`).join("");    const r = this.sql.exec<{ v: SqlStorageValue }>(`SELECT ${expression} AS v FROM rows WHERE table_id = ? AND deleted = 0${extra}`, table, ...where.flatMap((w) => w.args)).toArray()[0];    return r ? r.v : null;  }  /** Live rows counted by the value of one expression (a column), where every condition holds. */  countBy(table: string, expression: string, where: Cond[] = []): Map<SqlStorageValue, number> {    const extra = where.map((w) => ` AND (${w.sql})`).join("");    const out = new Map<SqlStorageValue, number>();    for (const r of this.sql.exec<{ k: SqlStorageValue; n: number }>(`SELECT ${expression} AS k, COUNT(*) AS n FROM rows WHERE table_id = ? AND deleted = 0${extra} GROUP BY k`, table, ...where.flatMap((w) => w.args))) out.set(r.k, Number(r.n));    return out;  }  /**   * A fixed read the import engine asks (src/import/reader.ts): its statements   * are written there, against `rows` and the expression indexes above, one per   * question the Rust engine's driver answers.   */  query<T extends Record<string, SqlStorageValue>>(sql: string, ...args: SqlStorageValue[]): T[] {    return this.sql.exec<T>(sql, ...args).toArray();  }  /** Live rows of a table a person owns. */  owned(table: string, owner: string): StoredRow[] {    return this.sql      .exec<RawRow>("SELECT * FROM rows WHERE table_id = ? AND deleted = 0 AND owner = ? ORDER BY created_at, id", table, owner)      .toArray()      .map(Store.row);  }  /** The owner of a row (the person id a mine() row belongs to), reading the definitions. */  ownerOf(defs: Definitions, t: TableDef, data: Record<string, unknown>, depth = 0): string | null {    const v = t.visibility;    if (v.kind === "customer") return typeof data.person === "string" ? data.person : null;    if (v.kind !== "mine") return null;    const value = data[v.through];    if (typeof value !== "string" || !value) return null;    const column = t.columns.find((c) => c.key === v.through);    if (v.through === "person" || !column?.link_to || column.link_to === "person") return value;    if (depth > 4) return null;    const linked = defs.table(column.link_to);    const target = this.get(column.link_to, value);    if (!linked || !target) return null;    return target.owner ?? this.ownerOf(defs, linked, target.data, depth + 1);  }  /** A new row; `stamps` keeps the times an imported row was made and last changed in the database it came from. */  insert(table: string, id: string, data: Record<string, unknown>, owner: string | null, version: number, stamps: Stamps = {}): StoredRow {    const now = this.now().toISOString();    const created = stamps.created_at ?? now;    const updated = stamps.updated_at ?? created;    // LANDED (MAIL PREDICATE phase 2, rule 3): when the row landed in THIS object, by the object's clock alone. No    // stamp, import or device can set it (created_at they can), so a mail cut, which covers mail landed at or before    // its moment, never covers an old mailbox imported after it.    this.landing();    const landed = now;    // A rows table made again under this store (a reset, a restore) comes without the column: add it, write again.    const exec = (statement: () => void) => {      try {        statement();      } catch (error) {        const said = String(error);        if (!said.includes("no column named landed_at") && !said.includes("no such column: landed_at")) throw error;        this.landed = false;        this.landing();        statement();      }    };    // A derived id (a session's task by its place) may come back after its row was deleted: the tombstone lives again.    const held = this.any(table, id);    if (held && !held.deleted) refuse(409, "duplicate_id", `${table} already holds ${id}`);    const made: StoredRow = { table, id, data, owner, version, deleted: false, created_at: created, updated_at: updated, landed_at: landed };    // A deleted token or device made again under its id: its deletion no longer stands (RESTORE 2 SERVER 4, L4).    if (held && neverAgain.REVOCABLE.has(table)) neverAgain.note(this.sql, { kind: "row_revived", table, id, at: landed });    if (held) {      const text = JSON.stringify(data);      keepingRow(table, id, text, () => exec(() =>        this.sql.exec(          "UPDATE rows SET data = ?, owner = ?, version = ?, deleted = 0, created_at = ?, updated_at = ?, landed_at = ? WHERE table_id = ? AND id = ?",          text,          owner,          version,          created,          updated,          landed,          table,          id,        ),      ));      this.writeLinks(table, id, data);      this.counted(held, -1);      this.counted(made, 1);      return made;    }    const text = JSON.stringify(data);    keepingRow(table, id, text, () => exec(() => this.sql.exec(      "INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at, landed_at) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?)",      table,      id,      text,      owner,      version,      created,      updated,      landed,    )));    this.writeLinks(table, id, data);    this.counted(made, 1);    return made;  }  /** A row by id whether live or a tombstone: an id is never reused, so an import that finds one knows it was here. */  any(table: string, id: string): StoredRow | null {    const r = this.sql.exec<RawRow>("SELECT * FROM rows WHERE table_id = ? AND id = ?", table, id).toArray()[0];    return r ? Store.row(r) : null;  }  update(row: StoredRow, data: Record<string, unknown>, owner: string | null, version: number, stamps: Stamps = {}): StoredRow {    const at = stamps.updated_at ?? this.now().toISOString();    // A token or a device revoked, by whatever path (an act, OAuth, a phone's own write): revoked for good, whatever a    // restore puts back (src/never_again.ts; RESTORE 2 SERVER 3, M2: written where it happens, not at its callers).    if (neverAgain.REVOCABLE.has(row.table) && !row.data.revoked_at && data.revoked_at) neverAgain.note(this.sql, { kind: "row_revoked", table: row.table, id: row.id, at: String(data.revoked_at) });    // Ended by its date brought forward (a legacy token renewed, RESTORE 2 SERVER 4 L4): ended for good too.    if (neverAgain.REVOCABLE.has(row.table) && typeof data.expires_at === "string" && data.expires_at && (typeof row.data.expires_at !== "string" || !row.data.expires_at || data.expires_at < row.data.expires_at)) neverAgain.note(this.sql, { kind: "row_expires", table: row.table, id: row.id, expires_at: data.expires_at, at });    const before = this.countPlan() ? this.any(row.table, row.id) : null;    const text = JSON.stringify(data);    keepingRow(row.table, row.id, text, () =>      this.sql.exec(        "UPDATE rows SET data = ?, owner = ?, version = ?, updated_at = ? WHERE table_id = ? AND id = ?",        text,        owner,        version,        at,        row.table,        row.id,      ),    );    this.writeLinks(row.table, row.id, data);    const next = { ...row, data, owner, version, updated_at: at };    if (before) {      this.counted(before, -1);      this.counted({ ...before, data, updated_at: at }, 1);    }    return next;  }  /**   * A row deleted: its data goes. An erased one (`erase`: why, as the phone's erase receipt said) keeps only that,   * as `{ "$erase": <why> }`, so every copy that pulls the tombstone ends the row for good too (CONTRACT.md   * "WhatsApp through the Mac").   */  tombstone(row: StoredRow, version: number, erase: string | null = null, kept: Record<string, unknown> = {}): StoredRow {    // A token or a device deleted outright: gone for good, whatever a restore puts back (RESTORE 2 SERVER 4, L4).    if (neverAgain.REVOCABLE.has(row.table) && !row.deleted) neverAgain.note(this.sql, { kind: "row_deleted", table: row.table, id: row.id, at: this.now().toISOString() });    const at = this.now().toISOString();    const before = this.countPlan() ? this.any(row.table, row.id) : null;    const data: Record<string, unknown> = erase ? { [ERASED_KEY]: erase } : { ...kept };    this.sql.exec(      "UPDATE rows SET deleted = 1, data = ?, version = ?, updated_at = ? WHERE table_id = ? AND id = ?",      JSON.stringify(data),      version,      at,      row.table,      row.id,    );    this.sql.exec("DELETE FROM links WHERE table_id = ? AND id = ?", row.table, row.id);    this.sql.exec("DELETE FROM list_links WHERE table_id = ? AND id = ?", row.table, row.id);    this.setBlind(row.table, row.id, []);    if (before) {      this.counted(before, -1);      this.counted({ ...before, data, deleted: true, updated_at: at }, 1);    }    return { ...row, data, deleted: true, version, updated_at: at };  }  /**   * One page of what changed after `since`, up to `upto`, after `after`: the   * rows `scope` may see, less the rows a window leaves out. The filters are   * SQL, so a page is `limit` rows the caller may see, never fewer because   * others were dropped after the read; one more row is read to know whether   * another page follows.   *   * With no `small` tables a pass is in (version, table, id) order. With them   * (a pass from nothing, `smallFirst`) it is two runs: the `small` tables   * first, one whole table after another in the order given, each by id; then   * every other table in (version, table, id) order. The run `after` stands   * in is its table's: a row of a `small` table is in the first. A page that   * ends the first run goes on into the second; `after` null is the pass's   * start. A row is in the pass while its version is at most `upto`, and its   * table and id never change, so in either order no row comes twice and none   * is skipped: a row written again mid-pass moves past `upto` and comes with   * the next pass.   *   * `floor` is where a pass begun in change order had got to when it went on   * small tables first (the one bridge, `readCursor` in src/business.ts):   * every row at or before it in change order was carried, so both runs read   * only the rows after it.   */  changedPage(q: { since: number; upto: number; limit: number; scope: SyncScope; windows: SyncWindow[]; small: string[]; floor: Cursor | null; after: Cursor | null; wholeSince?: number }): { rows: StoredRow[]; more: boolean; resume: Cursor | null } {    const seen = Store.seenBy(q.scope, q.windows);    const past = (c: Cursor | null): { where: string[]; args: SqlStorageValue[] } =>      c ? { where: ["(version, table_id, id) > (?, ?, ?)"], args: [c.version, c.table, c.id] } : { where: [], args: [] };    const floor = past(q.floor);    const rows: StoredRow[] = [];    // Bounded by bytes as well as rows, as firstPage's: reads of READ_ROWS at most, and the page closes at PAGE_BYTES.    let bytes = 0;    let counted = 0;    let full = false;    const want = (): number => {      for (; counted < rows.length; counted++) bytes += Store.bytesOf(rows[counted]!);      if (bytes >= PAGE_BYTES && rows.length <= q.limit) full = true;      return full ? 0 : Math.min(READ_ROWS, q.limit + 1 - rows.length);    };    let resume: Cursor | null = null;    const inSmall = q.after !== null && q.small.includes(q.after.table);    if (q.after === null || inSmall) {      // The first run: each small table along its primary key, (table_id, id).      let at = q.after ? q.small.indexOf(q.after.table) : 0;      for (let afterId = q.after?.id ?? null; at < q.small.length && want() > 0; ) {        const where = ["table_id = ?", "version > ?", "version <= ?", ...(afterId === null ? [] : ["id > ?"]), ...floor.where, ...seen.where];        // A pass that carries some tables again whole (`again`, src/business.ts) reads them from `wholeSince`.        const args: SqlStorageValue[] = [q.small[at]!, q.wholeSince ?? q.since, q.upto, ...(afterId === null ? [] : [afterId]), ...floor.args, ...seen.args];        const take = want();        const read = this.sql.exec<RawRow>(`SELECT * FROM rows WHERE ${where.join(" AND ")} ORDER BY id LIMIT ?`, ...args, take).toArray().map(Store.row);        rows.push(...read);        if (read.length < take) {          at++;          afterId = null;        } else afterId = read[read.length - 1]!.id;      }    }    // A scope of named tables all carried whole in the first run, or holding no row (Notes, `tables=note`), has no other table to walk to.    const others = q.scope.kind !== "tables" || [...q.scope.whole, ...(q.scope.person !== null ? q.scope.own : [])].some((t) => !q.small.includes(t) && !q.scope.except.has(t) && this.sql.exec("SELECT 1 FROM rows WHERE table_id = ? LIMIT 1", t).toArray().length > 0);    if (want() > 0 && others) {      // Every other table, in change order.      let from = q.after && !inSmall ? past(q.after) : floor;      // The walk's lower bound is the cursor's version, never `since` again: SQLite bounds rows_cursor by `version > ?`      // alone (the row value is no range), so a kit's pass read the index from its start on every page, a million rows      // a page on an object of the owner's size (21 Nov 2026).      let low = q.after && !inSmall ? Math.max(q.since, q.after.version - 1) : q.floor ? Math.max(q.since, q.floor.version - 1) : q.since;      // Along rows_cursor always: a scope of named tables (`tables=`, every app keeping to its kit) left to the      // planner read every row of its tables through their table_id indexes and sorted them whole, bodies and all,      // on every page of every pass (audit, 21 Nov 2026); the index walk sorts nothing and reads a row only once its      // index entry is in the scope.      // No further than `hi` this page (PAGE_READS): every row of the walk up to it comes, then the next page walks on.      const hi = this.walkTop(low, q.upto);      for (let take = want(); take > 0; take = want()) {        const where = ["version > ?", "version <= ?", "table_id NOT IN (SELECT value FROM json_each(?))", ...from.where, ...seen.where];        const args: SqlStorageValue[] = [low, hi, JSON.stringify(q.small), ...from.args, ...seen.args];        const read = this.sql.exec<RawRow>(`SELECT * FROM rows INDEXED BY rows_cursor WHERE ${where.join(" AND ")} ORDER BY version, table_id, id LIMIT ?`, ...args, take).toArray().map(Store.row);        rows.push(...read);        const last = read[read.length - 1];        if (read.length < take || !last) {          if (hi < q.upto) resume = { version: hi, table: WALK_PAST, id: "" };          break;        }        from = past({ version: last.version, table: last.table, id: last.id });        low = Math.max(q.since, last.version - 1);      }    }    want();    // A page closed by its bytes says more: the next page goes on from its last row (and may find nothing). One whose    // walk stopped at `hi` goes on from there (`resume`), rows or none.    const over = rows.length > q.limit;    const more = over || full || resume !== null;    return { rows: over ? rows.slice(0, q.limit) : rows, more, resume: over ? null : resume };  }  /**   * How far along rows_cursor one page's walk may go: the version PAGE_READS entries past `low` (read from the index   * alone), or `upto` when fewer stand.   */  private walkTop(low: number, upto: number): number {    const hi = this.sql.exec<{ version: number }>("SELECT version FROM rows INDEXED BY rows_cursor WHERE version > ? AND version <= ? ORDER BY version LIMIT 1 OFFSET ?", low, upto, PAGE_READS).toArray()[0]?.version;    return hi === undefined ? upto : Number(hi);  }  /** A name the object's first-order SQL is written with (a table id or column key): checked, since it is inlined. */  private static named(name: string): string {    if (!/^[a-z_][a-z0-9_]*$/.test(name)) refuse(400, "bad_cursor", `${JSON.stringify(name)} is not a table or column`);    return name;  }  /** A first order's value as SQL: `by`, '' for a row without it. Index and query say it alike, so the planner walks the index. */  private static ord(by: string, of = ""): string {    return `IFNULL(json_extract(${of}data, '$.${Store.named(by)}'), '')`;  }  /** The shadow that stands in for `rows_first_<t>` (or `rows_first_<t>__<column>`): the same terms, every row. */  private static firstShadow(t: string, by: string, column?: string): orderShadow.Spec {    const terms: orderShadow.Term[] = [{ expr: Store.ord(by) }, { expr: "id" }];    return column ? { name: `rows_first_${t}__${column}`, table: t, terms: [{ expr: `json_extract(data, '$.${column}')` }, ...terms], live: false } : { name: `rows_first_${t}`, table: t, terms, live: false };  }  private shadowMeta(): orderShadow.Meta {    return { get: (k) => this.meta(k), set: (k, v) => this.setMeta(k, v) };  }  private hasIndex(name: string): boolean {    // Asked once a row on a page (each ask reads the whole schema, 166 rows on his object): kept for this turn of    // the object's work only, and forgotten wherever this store makes or drops an index (indexMade).    if (!this.indexSeen) {      this.indexSeen = new Map();      queueMicrotask(() => {        this.indexSeen = null;      });    }    // Every index's name in one read of the schema (READ COST 2: list_bin asks for one a table, and the schema holds    // the shadows' tables and triggers too), not one read a name.    if (!this.indexSeen.size) for (const r of this.sql.exec<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'index'")) this.indexSeen.set(r.name, true);    return this.indexSeen.get(name) ?? false;  }  /** An index was made or dropped: what hasIndex holds is forgotten. */  private indexMade(): void {    this.indexSeen = null;  }  /**   * Where a first-order read walks: the partial index when it stands, else its shadow once ready. `k` and `id` are   * the order's value and the row's id as that walk holds them, `g` the group column's.   */  private indexSeen: Map<string, boolean> | null = null;  private firstFrom(t: string, by: string, column?: string): { from: string; k: string; id: string; g: string } {    const name = column ? `rows_first_${t}__${column}` : `rows_first_${t}`;    const g = column ? `json_extract(data, '$.${column}')` : "";    const shadow = this.hasIndex(name) ? null : orderShadow.ready(this.shadowMeta(), name);    if (!shadow) return { from: `rows INDEXED BY ${name}`, k: Store.ord(by), id: "id", g };    return column ? { from: orderShadow.from(shadow), k: orderShadow.value(shadow, 1), id: "o.sid", g: orderShadow.value(shadow, 0) } : { from: orderShadow.from(shadow), k: orderShadow.value(shadow, 0), id: "o.sid", g: "" };  }  /** One bounded step of a shadow's filling (the alarm's), when the account's switch is on. Answers whether more waits. */  shadowStep(most?: number): boolean {    if (!orderShadow.on(this.shadowMeta())) return false;    const did = orderShadow.step(this.sql, this.shadowMeta(), most);    // One line a step, so a tail's CPU for each alarm reads beside the step it took (ORDER INDEX on dev).    if (did) console.log(`cottondb: order shadow ${did.name}: ${did.did}${did.did === "laid" ? ` ${did.rows} rows` : ""}`);    return orderShadow.filling(this.shadowMeta());  }  /** Whether the account's switch is on and a shadow is asked for and not filled yet (READ COST 4: the alarm's to fill). */  shadowsFilling(): boolean {    const meta = this.shadowMeta();    return orderShadow.on(meta) && orderShadow.filling(meta);  }  /** The bell (business.ts): an alarm was reset while a shadow filled; its steps are halved. */  shadowReset(): number | null {    return orderShadow.smallerSteps(this.shadowMeta());  }  shadowProgress(): ReturnType<typeof orderShadow.progress> {    return orderShadow.progress(this.shadowMeta());  }  /** The account's switch. Off drops every shadow and its triggers. */  setShadows(on: boolean): void {    this.setMeta(orderShadow.SWITCH, on ? "on" : null);    if (!on) orderShadow.dropAll(this.sql, this.shadowMeta());  }  /**   * The indexes a pass's first orders walk: one partial index per table on   * its order, and per group column, so each walk reads that table's rows   * alone in order and sorts nothing. Answers the specs whose indexes stand.   * A missing one is never made here: making it reads the whole file, which on   * an object of 3.7 GB took a request past its CPU limit and reset the   * object (live, 23 Nov 2026, 18:13 to 18:17 UTC), again on every pass from   * nothing, since a reset rolls the index back. It is asked for instead, and   * the alarm makes one an alarm (buildOrderIndex); until then that table's   * rows come in the pass's own order, as before first orders. A file under   * FIRST_INDEX_NOW_BYTES has its index made at once, as before.   */  firstIndexes(specs: FirstSpec[]): FirstSpec[] {    const wanted = this.orderIndexesWanted();    const asked = Object.keys(wanted).length;    // A small file's index is made at once (well under a second), as it always was.    const small = this.sql.databaseSize < FIRST_INDEX_NOW_BYTES;    const shadows = orderShadow.on(this.shadowMeta());    const stand = (name: string, statement: string, shadow: orderShadow.Spec): boolean => {      if (this.hasIndex(name)) return true;      if (small) {        this.sql.exec(statement);        this.indexMade();        return true;      }      // ORDER INDEX (24 Nov 2026): with the account's switch on, a shadow filled across alarms stands in for it.      if (shadows) return orderShadow.ask(this.shadowMeta(), shadow);      if (!this.indexTooBig()) wanted[name] = statement;      return false;    };    const ready = specs.filter((s) => {      const t = Store.named(s.table);      let ok = stand(`rows_first_${t}`, `CREATE INDEX IF NOT EXISTS rows_first_${t} ON rows (${Store.ord(s.by)}, id) WHERE table_id = '${t}'`, Store.firstShadow(t, s.by));      if (!s.per) return ok;      const of = Store.named(s.per.of);      const column = Store.named(s.per.column);      ok = stand(`rows_first_${t}__${column}`, `CREATE INDEX IF NOT EXISTS rows_first_${t}__${column} ON rows (json_extract(data, '$.${column}'), ${Store.ord(s.by)}, id) WHERE table_id = '${t}'`, Store.firstShadow(t, s.by, column)) && ok;      return stand(`rows_first_${of}`, `CREATE INDEX IF NOT EXISTS rows_first_${of} ON rows (${Store.ord(s.per.by)}, id) WHERE table_id = '${of}'`, Store.firstShadow(of, s.per.by)) && ok;    });    if (Object.keys(wanted).length !== asked) this.setMeta(ORDER_INDEXES, JSON.stringify(wanted));    return ready;  }  /** A new pass carrying first rows first: its cuts are kept under `pass`; passes begun before `stale` (seconds) are forgotten. */  firstPass(pass: string, now: number, stale: number): void {    for (const r of this.sql.exec<{ pass: string }>("SELECT pass FROM first_pass WHERE made < ?", stale).toArray()) {      this.sql.exec("DELETE FROM first_cut WHERE pass = ?", r.pass);      this.sql.exec("DELETE FROM first_pass WHERE pass = ?", r.pass);    }    this.sql.exec("INSERT OR IGNORE INTO first_pass (pass, made) VALUES (?, ?)", pass, now);  }  /**   * One page of a pass from nothing that carries what a person looks at   * first before the long tail (src/first.ts). Five runs, in order:   *   *   lead    each ungrouped spec's first rows, in its order (every chat's   *           row, newest first; the notes list; the days around today);   *   early   a grouped spec's first `early` groups' first rows (the 20   *           most recent chats' newest messages), before the small tables;   *   small   the small tables whole, as `changedPage` carries them;   *   group   each grouped spec's first rows of each group, the groups in   *           their own table's order (each chat's newest 50 messages, the   *           most recent chats first);   *   soon    a small spec's other rows (`soon`), so it stands whole as   *           early as any small table: its tail, then its rest;   *   change  every other table, in change order;   *   tail    every other spec's other rows, in its order, a grouped one   *           group by group from its cut (each chat's older messages,   *           newest first, the chats in the order they came);   *   rest    a grouped spec's rows of no group that came first (its   *           tombstones, a chat the pass did not hold), group by group.   *   * A row is in the pass while its version is at most `upto`, so the pass's   * rows only ever leave it (a row written again comes with the next pass),   * and a row's place in an order, its group and whether it comes first never   * change while it is in the pass. Each run walks its order from `at`, so   * nothing comes twice and nothing is skipped; the tail leaves out what came   * first by each spec's cut, the last row its first run carried (`plan.cuts`,   * in the cursor) or each group's (`first_cut`, kept on the object under the   * pass's id, since a pass has as many as the account has chats). A cut that   * is gone (a pass older than a month) only lets a row come twice.   */  firstPage(q: { since: number; upto: number; limit: number; scope: SyncScope; windows: SyncWindow[]; plan: FirstPlan; at: FirstAt | null }): { rows: StoredRow[]; more: boolean; at: FirstAt; plan: FirstPlan } {    const seen = Store.seenBy(q.scope, q.windows);    const plan = q.plan;    type Got = { row: StoredRow; at: FirstAt; cut?: number; group?: { spec: number; grp: SqlStorageValue; seq: number } };    const got: Got[] = [];    // PAGES BOUNDED BY BYTES AS WELL AS ROWS (MAIL ALL ON PHONE, 24 Nov 2026): a page of 5,000 mail rows, each up to    // 65,536 characters sealed and padded, could hold hundreds of MB in the object's 128 MB. Each read takes at most    // READ_ROWS rows, and once the page's rows hold PAGE_BYTES the page closes as if its limit were where it stands:    // one row more is read past it, as the limit's own row past is, and the next page goes on from there.    let top: number | null = null;    let walked: FirstAt | null = null;    let cap = q.limit;    let bytes = 0;    let counted = 0;    const want = (): number => {      for (; counted < got.length; counted++) bytes += Store.bytesOf(got[counted]!.row);      if (bytes >= PAGE_BYTES && got.length <= cap) cap = got.length;      return Math.min(READ_ROWS, cap + 1 - got.length);    };    const start = (run: FirstRun, i = 0): FirstAt => ({ run, i, key: null, n: 0, group: null, groups: 0, change: null });    const dir = (asc: boolean): { past: string; within: string; sort: string } => (asc ? { past: ">", within: "<=", sort: "ASC" } : { past: "<", within: ">=", sort: "DESC" });    const firstOnly = (sp: FirstSpec): { where: string[]; args: SqlStorageValue[] } => ({      where: ["deleted = 0", ...sp.unless.map((c) => `json_extract(data, '$.${Store.named(c)}') IS NULL`), ...(sp.around ? [`${Store.ord(sp.by)} >= ?`, `${Store.ord(sp.by)} < ?`] : [])],      args: sp.around ? [sp.around.from, sp.around.to] : [],    });    type Keyed = RawRow & { k: SqlStorageValue };    // Each ungrouped spec's cut as this page stands, and each group's cut as it stood before this page wrote it.    const live: (FirstKey | null)[] = [...plan.cuts];    const earlyEnd: ({ group: FirstKey; groups: number } | null)[] = plan.specs.map((_, i) => plan.from?.[i] ?? null);    type Held = { seq: number; at: SqlStorageValue; id: string } | null;    const before = new Map<string, Held>();    const cutAt = (table: string, grp: SqlStorageValue, seq: number, key: FirstKey | null, put?: Held): void => {      const name = `${table}\u0000${String(grp)}`;      if (!before.has(name)) before.set(name, this.sql.exec<{ seq: number; at: SqlStorageValue; id: string }>("SELECT seq, at, id FROM first_cut WHERE pass = ? AND tbl = ? AND grp = ?", plan.pass, table, grp).toArray()[0] ?? null);      const was = put === undefined ? undefined : put;      if (was === null) this.sql.exec("DELETE FROM first_cut WHERE pass = ? AND tbl = ? AND grp = ?", plan.pass, table, grp);      else if (was) this.sql.exec("INSERT OR REPLACE INTO first_cut (pass, tbl, grp, seq, at, id) VALUES (?, ?, ?, ?, ?, ?)", plan.pass, table, grp, was.seq, was.at, was.id);      else this.sql.exec("INSERT OR REPLACE INTO first_cut (pass, tbl, grp, seq, at, id) VALUES (?, ?, ?, ?, ?, ?)", plan.pass, table, grp, seq, key![0], key![1]);    };    let at: FirstAt = q.at ?? start("lead");    // An ungrouped spec's first rows, from where `at` stands in `run`: the lead run's, or a late spec's in the group run.    const ungrouped = (sp: FirstSpec, run: FirstRun): void => {      const t = Store.named(sp.table);      const d = dir(sp.asc);      const f = this.firstFrom(t, sp.by);      const only = firstOnly(sp);      const take = sp.rows === null ? want() : Math.min(want(), sp.rows - at.n);      const where = [`table_id = '${t}'`, "version > ?", "version <= ?", ...only.where, ...(at.key ? [`(${f.k}, ${f.id}) ${d.past} (?, ?)`] : []), ...seen.where];      const args: SqlStorageValue[] = [q.since, q.upto, ...only.args, ...(at.key ?? []), ...seen.args];      const read = this.sql.exec<Keyed>(`SELECT rows.*, ${f.k} AS k FROM ${f.from} WHERE ${where.join(" AND ")} ORDER BY ${f.k} ${d.sort}, ${f.id} ${d.sort} LIMIT ?`, ...args, take).toArray();      for (const r of read) {        at = { ...at, key: [r.k, r.id], n: at.n + 1 };        got.push({ row: Store.row(r), at, cut: at.i });        live[at.i] = at.key;      }      if (read.length < take) at = start(run, at.i + 1);    };    while (want() > 0) {      if (at.run === "lead") {        const sp = plan.specs[at.i];        if (!sp) {          at = start("early");          continue;        }        if (sp.per || sp.late || (sp.rows !== null && at.n >= sp.rows)) {          at = start("lead", at.i + 1);          continue;        }        ungrouped(sp, "lead");        continue;      }      if (at.run === "small") {        const t = plan.small[at.i];        if (t === undefined) {          at = start("group");          continue;        }        const take = want();        const afterId = at.key?.[1] ?? null;        const where = ["table_id = ?", "version > ?", "version <= ?", ...(afterId === null ? [] : ["id > ?"]), ...seen.where];        const args: SqlStorageValue[] = [t, q.since, q.upto, ...(afterId === null ? [] : [afterId]), ...seen.args];        const read = this.sql.exec<RawRow>(`SELECT * FROM rows WHERE ${where.join(" AND ")} ORDER BY id LIMIT ?`, ...args, take).toArray();        for (const r of read) {          at = { ...at, key: [null, r.id] };          got.push({ row: Store.row(r), at });        }        if (read.length < take) at = start("small", at.i + 1);        continue;      }      if (at.run === "group" || at.run === "early") {        const run = at.run;        const sp = plan.specs[at.i];        if (!sp) {          at = start(run === "early" ? "small" : "soon");          continue;        }        // A late spec without groups comes here, in its place after every spec that is not late.        if (!sp.per && sp.late && run === "group") {          if (sp.rows !== null && at.n >= sp.rows) at = start("group", at.i + 1);          else ungrouped(sp, "group");          continue;        }        const per = sp.per;        if (!per || (run === "early" && (per.early === null || sp.late))) {          at = start(run, at.i + 1);          continue;        }        // The group run picks up after the groups that came early.        let skip = false;        const early = earlyEnd[at.i] ?? null;        if (run === "group" && at.group === null && at.groups === 0 && early) {          at = { ...start("group", at.i), group: early.group, groups: early.groups };          skip = true;        }        if (!skip && at.group !== null && (sp.rows === null || at.n < sp.rows)) {          // The rows of the group in hand, from where it stands.          const t = Store.named(sp.table);          const d = dir(sp.asc);          const f = this.firstFrom(t, sp.by, Store.named(per.column));          const only = firstOnly(sp);          const take = sp.rows === null ? want() : Math.min(want(), sp.rows - at.n);          const where = [`table_id = '${t}'`, `${f.g} = ?`, "version > ?", "version <= ?", ...only.where, ...(at.key ? [`(${f.k}, ${f.id}) ${d.past} (?, ?)`] : []), ...seen.where];          const args: SqlStorageValue[] = [at.group[1], q.since, q.upto, ...only.args, ...(at.key ?? []), ...seen.args];          const read = this.sql.exec<Keyed>(`SELECT rows.*, ${f.k} AS k FROM ${f.from} WHERE ${where.join(" AND ")} ORDER BY ${f.k} ${d.sort}, ${f.id} ${d.sort} LIMIT ?`, ...args, take).toArray();          const grp = at.group[1];          for (const r of read) {            at = { ...at, key: [r.k, r.id], n: at.n + 1 };            got.push({ row: Store.row(r), at, group: { spec: at.i, grp, seq: at.groups } });          }          // Written as the rows are read, so this page's own tail and rest already leave them out.          const lastRead = read[read.length - 1];          if (lastRead) cutAt(sp.table, grp, at.groups, [lastRead.k, lastRead.id]);          if (read.length === take) continue;        }        // The next group, in its own table's order.        const enough = per.groups !== null && at.groups >= per.groups;        if (run === "early" && (enough || at.groups >= per.early!)) {          earlyEnd[at.i] = at.group ? { group: at.group, groups: at.groups } : null;          at = start("early", at.i + 1);          continue;        }        if (enough) {          at = start(run, at.i + 1);          continue;        }        const of = Store.named(per.of);        const gd = dir(per.asc);        const fp = this.firstFrom(of, per.by);        const next = this.sql          .exec<{ id: string; k: SqlStorageValue }>(            `SELECT ${fp.id} AS id, ${fp.k} AS k FROM ${fp.from} WHERE ${[`table_id = '${of}'`, "deleted = 0", "version <= ?", ...(at.group ? [`(${fp.k}, ${fp.id}) ${gd.past} (?, ?)`] : [])].join(" AND ")} ORDER BY ${fp.k} ${gd.sort}, ${fp.id} ${gd.sort} LIMIT 1`,            q.upto,            ...(at.group ?? []),          )          .toArray()[0];        if (!next && run === "early") earlyEnd[at.i] = at.group ? { group: at.group, groups: at.groups } : null;        at = next ? { ...start(run, at.i), group: [next.k, next.id], groups: at.groups + 1 } : start(run, at.i + 1);        continue;      }      if (at.run === "change") {        const leftOut = [...plan.small, ...plan.specs.map((sp) => sp.table)];        const others = q.scope.kind !== "tables" || [...q.scope.whole, ...(q.scope.person !== null ? q.scope.own : [])].some((t) => !leftOut.includes(t) && !q.scope.except.has(t) && this.sql.exec("SELECT 1 FROM rows WHERE table_id = ? LIMIT 1", t).toArray().length > 0);        if (!others) {          at = start("tail");          continue;        }        const take = want();        const from = at.change;        // The walk's lower bound is the cursor's version, never `since` again (as changedPage's, 21 Nov 2026).        const low = from ? Math.max(q.since, from.version - 1) : q.since;        // No further than `top` this page (PAGE_READS), found once where the page's walk begins.        top ??= this.walkTop(low, q.upto);        const where = ["version > ?", "version <= ?", "table_id NOT IN (SELECT value FROM json_each(?))", ...(from ? ["(version, table_id, id) > (?, ?, ?)"] : []), ...seen.where];        const args: SqlStorageValue[] = [low, top, JSON.stringify(leftOut), ...(from ? [from.version, from.table, from.id] : []), ...seen.args];        const read = this.sql.exec<RawRow>(`SELECT * FROM rows INDEXED BY rows_cursor WHERE ${where.join(" AND ")} ORDER BY version, table_id, id LIMIT ?`, ...args, take).toArray();        for (const r of read) {          at = { ...start("change"), change: { version: r.version, table: r.table_id, id: r.id } };          got.push({ row: Store.row(r), at });        }        if (read.length < take && top < q.upto) {          // Short of `top`: the page ends there, and the next walks on past it.          walked = { ...start("change"), change: { version: top, table: WALK_PAST, id: "" } };          break;        }        if (read.length < take) at = start("tail");        continue;      }      if (at.run === "tail" || at.run === "soon") {        // Each spec's rows that did not come first, in its order. A grouped spec's go group by group, in the order        // the groups came first (their cuts' `seq`), each from its cut on: never a walk over the rows that came.        const run = at.run;        const sp = plan.specs[at.i];        if (!sp) {          at = start(run === "soon" ? "soonrest" : "rest");          continue;        }        if (sp.soon !== (run === "soon")) {          at = start(run, at.i + 1);          continue;        }        const t = Store.named(sp.table);        const d = dir(sp.asc);        const ord = Store.ord(sp.by);        const only = firstOnly(sp);        const take = want();        if (sp.per) {          const col = Store.named(sp.per.column);          const f = this.firstFrom(t, sp.by, col);          if (at.group !== null) {            const cut = this.sql.exec<{ at: SqlStorageValue; id: string }>("SELECT at, id FROM first_cut WHERE pass = ? AND tbl = ? AND grp = ?", plan.pass, t, at.group[1]).toArray()[0];            const came = cut ? { where: [`NOT (${[...only.where, `(${ord}, id) ${d.within} (?, ?)`].join(" AND ")})`], args: [...only.args, cut.at, cut.id] } : { where: [], args: [] };            const where = [`table_id = '${t}'`, `${f.g} = ?`, "version > ?", "version <= ?", ...(at.key ? [`(${f.k}, ${f.id}) ${d.past} (?, ?)`] : []), ...came.where, ...seen.where];            const args: SqlStorageValue[] = [at.group[1], q.since, q.upto, ...(at.key ?? []), ...came.args, ...seen.args];            const read = this.sql.exec<Keyed>(`SELECT rows.*, ${f.k} AS k FROM ${f.from} WHERE ${where.join(" AND ")} ORDER BY ${f.k} ${d.sort}, ${f.id} ${d.sort} LIMIT ?`, ...args, take).toArray();            for (const r of read) {              at = { ...at, key: [r.k, r.id] };              got.push({ row: Store.row(r), at });            }            if (read.length === take) continue;          }          const next = this.sql.exec<{ grp: SqlStorageValue; seq: number }>("SELECT grp, seq FROM first_cut WHERE pass = ? AND tbl = ? AND seq > ? ORDER BY seq LIMIT 1", plan.pass, t, at.groups).toArray()[0];          at = next ? { ...start(run, at.i), group: [next.seq, String(next.grp)], groups: next.seq } : start(run, at.i + 1);          continue;        }        const f = this.firstFrom(t, sp.by);        const cut = live[at.i] ?? null;        const came = cut ? { where: [`NOT (${[...only.where, `(${ord}, id) ${d.within} (?, ?)`].join(" AND ")})`], args: [...only.args, ...cut] } : { where: [], args: [] };        const where = [`table_id = '${t}'`, "version > ?", "version <= ?", ...(at.key ? [`(${f.k}, ${f.id}) ${d.past} (?, ?)`] : []), ...came.where, ...seen.where];        const args: SqlStorageValue[] = [q.since, q.upto, ...(at.key ?? []), ...came.args, ...seen.args];        const read = this.sql.exec<Keyed>(`SELECT rows.*, ${f.k} AS k FROM ${f.from} WHERE ${where.join(" AND ")} ORDER BY ${f.k} ${d.sort}, ${f.id} ${d.sort} LIMIT ?`, ...args, take).toArray();        for (const r of read) {          at = { ...at, key: [r.k, r.id] };          got.push({ row: Store.row(r), at });        }        if (read.length < take) at = start(run, at.i + 1);        continue;      }      // The rest of each grouped spec: the rows of every group that never came first (tombstones, a chat the pass      // did not hold, one past `groups`), each group whole, found along the group index one value at a time.      const run = at.run;      const sp = plan.specs[at.i];      if (!sp) {        if (run === "rest") break;        at = start("change");        continue;      }      if (!sp.per || sp.soon !== (run === "soonrest")) {        at = start(run, at.i + 1);        continue;      }      const t = Store.named(sp.table);      const col = Store.named(sp.per.column);      const f = this.firstFrom(t, sp.by, col);      const gx = f.g;      const d = dir(sp.asc);      const take = want();      // `n` 0: the rows with no group (NULL first along the index); 1: a group's, `group` [value, value].      if (at.n === 1 && at.group === null) {        at = start(run, at.i + 1);        continue;      }      const inGroup = at.n === 0 ? { where: [`${gx} IS NULL`], args: [] as SqlStorageValue[] } : { where: [`${gx} = ?`], args: [at.group![0]] };      const where = [`table_id = '${t}'`, ...inGroup.where, "version > ?", "version <= ?", ...(at.key ? [`(${f.k}, ${f.id}) ${d.past} (?, ?)`] : []), ...seen.where];      const args: SqlStorageValue[] = [...inGroup.args, q.since, q.upto, ...(at.key ?? []), ...seen.args];      const read = this.sql.exec<Keyed>(`SELECT rows.*, ${f.k} AS k FROM ${f.from} WHERE ${where.join(" AND ")} ORDER BY ${f.k} ${d.sort}, ${f.id} ${d.sort} LIMIT ?`, ...args, take).toArray();      for (const r of read) {        at = { ...at, key: [r.k, r.id] };        got.push({ row: Store.row(r), at });      }      if (read.length === take) continue;      // The next group value along the index that never came first.      let from: SqlStorageValue = at.n === 0 ? null : at.group![0];      let next: SqlStorageValue | undefined;      for (;;) {        next = this.sql.exec<{ g: SqlStorageValue }>(`SELECT ${gx} AS g FROM ${f.from} WHERE table_id = '${t}' AND ${from === null ? `${gx} IS NOT NULL` : `${gx} > ?`} ORDER BY ${gx} LIMIT 1`, ...(from === null ? [] : [from])).toArray()[0]?.g;        if (next === undefined || next === null) break;        if (this.sql.exec("SELECT 1 FROM first_cut WHERE pass = ? AND tbl = ? AND grp = ?", plan.pass, t, next).toArray().length === 0) break;        from = next;      }      at = next === undefined || next === null ? start(run, at.i + 1) : { ...start(run, at.i), n: 1, group: [next, String(next)] };    }    want();    const over = got.length > cap;    const more = over || walked !== null;    const kept = over ? got.slice(0, cap) : got;    const cuts = [...plan.cuts];    for (const g of kept) if (g.cut !== undefined) cuts[g.cut] = g.at.key;    // The row read past the page does not come with it: its group's cut goes back to the last row of the group    // this page carries, or to what it was before the page.    const dropped = over ? got[cap] : undefined;    if (dropped?.group) {      const sp = plan.specs[dropped.group.spec]!;      const mine = kept.filter((g) => g.group && g.group.spec === dropped.group!.spec && g.group.grp === dropped.group!.grp);      const lastKept = mine[mine.length - 1];      if (lastKept) cutAt(sp.table, dropped.group.grp, dropped.group.seq, lastKept.at.key);      else cutAt(sp.table, dropped.group.grp, 0, null, before.get(`${sp.table}\u0000${String(dropped.group.grp)}`) ?? null);    }    const last = kept[kept.length - 1];    return { rows: kept.map((g) => g.row), more, at: walked && !over ? walked : last ? last.at : at, plan: { ...plan, cuts: cuts.map((c) => c ?? null), from: earlyEnd } };  }  /**   * The tables a pass from nothing carries first (owner, 2 Nov 2026: a fresh   * install holds the small tables whole in its first minutes — people,   * todos, notes, money — and the big ones after): each table whose rows in   * the pass, under `scope` and `windows`, tombstones too, number at most   * `most`, the fewest first (then by name), so the smallest stand whole   * soonest. Counted as the pass begins and carried in its cursor, so a table   * that grows mid-pass stays in the run it began in.   */  smallFirst(q: { since: number; upto: number; scope: SyncScope; windows: SyncWindow[]; most: number }): string[] {    return [...this.passTables(q)]      .filter(([, n]) => n > 0 && n <= q.most)      .sort(([a, x], [b, y]) => x - y || (a < b ? -1 : a > b ? 1 : 0))      .map(([table]) => table);  }  /**   * The tables an owner's pass reads whole, so `row_counts` can count it:   * every table (null) for `all`, the named ones for an owner's `tables=`   * (an app keeping to its kit: no person, no rows of their own); undefined   * for a narrower scope, counted in SQL. Before an owner's `tables=` was   * counted here (launch-fast, 21 Nov 2026), every pass's first page of every   * app keeping to a kit counted all the rows of its tables in SQL.   */  private static countable(scope: SyncScope): Set<string> | null | undefined {    if (scope.kind === "all") return null;    return scope.person === null && scope.own.size === 0 ? scope.whole : undefined;  }  /** `row_counts`' conditions for `whole` (null: every table) and `windows`, beside the internal tables left out (and `queued`, whose counts a recount is still making). */  private static countedWhere(except: Set<string>, whole: Set<string> | null, windows: SyncWindow[], queued: Set<string> = new Set()): { kept: string[]; args: SqlStorageValue[] } {    const left = new Set([...except, ...queued]);    const kept = ["table_id NOT IN (SELECT value FROM json_each(?))", ...(whole ? ["table_id IN (SELECT value FROM json_each(?))"] : []), ...windows.map(() => "NOT (table_id = ? AND day <> '' AND day < ?)")];    const args: SqlStorageValue[] = [JSON.stringify([...left]), ...(whole ? [JSON.stringify([...whole])] : []), ...windows.flatMap((w): SqlStorageValue[] => [w.table, w.from])];    return { kept, args };  }  /**   * SLOW READ (26 Nov 2026, dev at size): while a recount is under way, the tables it has still to count, whose   * `row_counts` are partial; every other table's are whole and are read as when every table is counted. Null when   * the counts cannot be read at all (the date columns not yet given, or a step failed in the last ten minutes).   *   * Before, any table queued sent every pass's first page to count the whole object in SQL. `rows` holds `data` before   * `version` and `deleted`, so a count reads every row whole, overflow pages and all: on an invented object of 1.8 GB   * a sync's first page took 3 to 4.5 s until the recount ended (0.85 s after). A kit that dates one table now has that   * one table counted in SQL.   */  /**   * `table` counted again from nothing, as a kit dating it anew would have it: its counts dropped and it queued   * behind any table already queued; every other table's counts stand. With no plan yet, nothing to do (the first   * recount queues every table). The dev Worker's /dev/plant-rows asks it.   */  recountTable(table: string): void {    const plan = this.countPlan();    if (!plan) return;    const next = structuredClone(plan);    if (!next.queue.some((q) => q.table === table)) next.queue.push({ table, column: this.dateColumns.get(table) ?? plan.by[table] ?? "" });    this.sql.exec("DELETE FROM row_counts WHERE table_id = ?", table);    if (next.queue[0]?.table === table) [next.after, next.headRows] = [null, 0];    this.saveCountPlan(next);  }  private countsQueued(): Set<string> | null {    if (!this.datesKnown) return null;    if (this.countsFailedAt && this.now().getTime() - this.countsFailedAt < 600_000) return null;    try {      return new Set(this.replanCounts().queue.map((q) => q.table));    } catch {      return null;    }  }  /** Each table's rows one pass from `since` to `upto` carries (tombstones too): for the owner from nothing, a sum over `row_counts`; else counted in SQL. */  passTables(q: { since: number; upto: number; scope: SyncScope; windows: SyncWindow[] }): Map<string, number> {    const whole = Store.countable(q.scope);    const queued = q.since === 0 && whole !== undefined && q.windows.every((w) => !w.is && this.dateColumns.get(w.table) === w.column) ? (this.countsReady() ? new Set<string>() : this.countsQueued()) : null;    const seen = Store.seenBy(q.scope, q.windows);    if (queued) {      const { kept, args } = Store.countedWhere(q.scope.except, whole!, q.windows, queued);      const counted = this.sql.exec<{ table_id: string; n: number }>(`SELECT table_id, SUM(n) AS n FROM row_counts WHERE ${kept.join(" AND ")} GROUP BY table_id`, ...args).toArray();      const out = new Map(counted.map((r) => [r.table_id, Number(r.n)]));      // A table the recount has still to count: counted in SQL, alone.      for (const table of queued) {        if (q.scope.except.has(table) || (whole && !whole.has(table))) continue;        const n = Number(this.sql.exec<{ n: number }>(`SELECT COUNT(*) AS n FROM rows WHERE ${["table_id = ?", "version <= ?", ...seen.where].join(" AND ")}`, table, q.upto, ...seen.args).one().n);        if (n > 0) out.set(table, n);      }      return out;    }    if (q.since > 0) {      // A later pass: the rows changed since, along rows_cursor, tallied as they stream (a GROUP BY would sort them, and a phone back after months has most of the object to come).      const out = new Map<string, number>();      for (const r of this.sql.exec<{ table_id: string }>(`SELECT table_id FROM rows INDEXED BY rows_cursor WHERE ${["version > ?", "version <= ?", ...seen.where].join(" AND ")}`, q.since, q.upto, ...seen.args)) out.set(r.table_id, (out.get(r.table_id) ?? 0) + 1);      return out;    }    // From nothing: one count per table, along its own index. One GROUP BY over every row sorts them all in a    // temporary B-tree, the shape that ran out of SQLite's memory on the personal object (21 Nov 2026).    const out = new Map<string, number>();    for (const table of this.tablesHeld()) {      if (q.scope.except.has(table) || (q.scope.kind === "tables" && !q.scope.whole.has(table) && !(q.scope.person !== null && q.scope.own.has(table)))) continue;      const n = Number(this.sql.exec<{ n: number }>(`SELECT COUNT(*) AS n FROM rows WHERE ${["table_id = ?", "version > ?", "version <= ?", ...seen.where].join(" AND ")}`, table, q.since, q.upto, ...seen.args).one().n);      if (n > 0) out.set(table, n);    }    return out;  }  /** Each table holding rows (tombstones too), by one seek per table along the primary key: never a scan of every row. */  private tablesHeld(): string[] {    const tables: string[] = [];    for (;;) {      const next = this.sql.exec<{ table_id: string }>("SELECT table_id FROM rows WHERE table_id > ? ORDER BY table_id LIMIT 1", tables[tables.length - 1] ?? "").toArray()[0]?.table_id;      if (next === undefined) return tables;      tables.push(next);    }  }  /**   * What one sync pass from `since` to `upto` holds, under the scope and   * windows its pages read: `total` the live rows a phone holds at `upto`,   * `pass` every row the pass's pages carry (tombstones too), `passLive` the   * live ones among them. Made on a pass's first page, while `upto` is the   * object's version, and carried in its cursor.   *   * The owner reads every table, so their total is a sum over `row_counts`   * and only the rows changed since `since` are read; a narrower scope (a   * member's, a business's few rows) is counted in SQL.   */  syncCounts(q: { since: number; upto: number; scope: SyncScope; windows: SyncWindow[] }): { total: number; pass: number; passLive: number } {    const whole = Store.countable(q.scope);    if (whole !== undefined && q.windows.every((w) => !w.is && this.dateColumns.get(w.table) === w.column)) {      if (this.countsReady()) return this.countedPass({ ...q, whole });      const queued = this.countsQueued();      if (queued) return this.countedPass({ ...q, whole }, queued);    }    const seen = Store.seenBy(q.scope, q.windows);    const r = this.sql      .exec<{ total: number | null; pass: number | null; pass_live: number | null }>(        `SELECT SUM(deleted = 0) AS total, SUM(version > ?) AS pass, SUM(version > ? AND deleted = 0) AS pass_live FROM rows WHERE ${["version <= ?", ...seen.where].join(" AND ")}`,        q.since,        q.since,        q.upto,        ...seen.args,      )      .toArray()[0];    return { total: Number(r?.total ?? 0), pass: Number(r?.pass ?? 0), passLive: Number(r?.pass_live ?? 0) };  }  /** `syncCounts` for the owner, from `row_counts`: a window is the days from its start, and a day of `"0"` is before every start. */  private countedPass(q: { since: number; upto: number; scope: SyncScope; windows: SyncWindow[]; whole: Set<string> | null }, queued: Set<string> = new Set()): { total: number; pass: number; passLive: number } {    const { kept, args } = Store.countedWhere(q.scope.except, q.whole, q.windows, queued);    const r = this.sql      .exec<{ live: number | null; dead: number | null }>(        `SELECT SUM(CASE WHEN deleted = 0 THEN n ELSE 0 END) AS live, SUM(CASE WHEN deleted = 1 THEN n ELSE 0 END) AS dead FROM row_counts WHERE ${["1 = 1", ...kept].join(" AND ")}`,        ...args,      )      .toArray()[0];    const seen = Store.seenBy(q.scope, q.windows);    // The tables a recount has still to count (`countsQueued`), counted in SQL, those tables alone.    const mine = [...queued].filter((t) => !q.scope.except.has(t) && (q.whole === null || q.whole.has(t)));    const sql = mine.length      ? this.sql          .exec<{ live: number | null; all: number | null }>(            `SELECT SUM(deleted = 0) AS live, COUNT(*) AS "all" FROM rows WHERE ${["table_id IN (SELECT value FROM json_each(?))", "version <= ?", ...seen.where].join(" AND ")}`,            JSON.stringify(mine),            q.upto,            ...seen.args,          )          .toArray()[0]      : undefined;    const total = Number(r?.live ?? 0) + Number(sql?.live ?? 0);    if (q.since === 0) return { total, pass: Number(r?.live ?? 0) + Number(r?.dead ?? 0) + Number(sql?.all ?? 0), passLive: total };    const c = this.sql      .exec<{ pass: number | null; pass_live: number | null }>(        `SELECT COUNT(*) AS pass, SUM(deleted = 0) AS pass_live FROM rows INDEXED BY rows_cursor WHERE ${["version > ?", "version <= ?", ...seen.where].join(" AND ")}`,        q.since,        q.upto,        ...seen.args,      )      .toArray()[0];    return { total, pass: Number(c?.pass ?? 0), passLive: Number(c?.pass_live ?? 0) };  }  /** One table's rows a pass from `since` to `upto` carries under `scope` and `windows`, and the live ones among them, along its primary key. */  tableCounts(q: { table: string; since: number; upto: number; scope: SyncScope; windows: SyncWindow[] }): { n: number; live: number } {    // LIVE CPU 2 (23 Nov 2026): counted along the table's own index this read every row of it, twice a table a pass    // carries again (375,000 messages on an object of his shape). The owner's whole table from nothing is a sum over    // row_counts, and the rows changed since are read along rows_cursor, as a later pass's figures are.    const whole = Store.countable(q.scope);    // A recount under way leaves this table's counts whole unless it is one it has still to count (`countsQueued`).    const counted = whole !== undefined && (whole === null || whole.has(q.table)) && q.windows.every((w) => !w.is && this.dateColumns.get(w.table) === w.column) && (this.countsReady() || this.countsQueued()?.has(q.table) === false);    if (counted && q.since === 0) {      const { kept, args } = Store.countedWhere(q.scope.except, whole, q.windows);      const r = this.sql        .exec<{ live: number | null; dead: number | null }>(`SELECT SUM(CASE WHEN deleted = 0 THEN n ELSE 0 END) AS live, SUM(CASE WHEN deleted = 1 THEN n ELSE 0 END) AS dead FROM row_counts WHERE ${["table_id = ?", ...kept].join(" AND ")}`, q.table, ...args)        .toArray()[0];      const live = Number(r?.live ?? 0);      return { n: live + Number(r?.dead ?? 0), live };    }    const seen = Store.seenBy(q.scope, q.windows);    if (q.since > 0) {      const r = this.sql        .exec<{ n: number; live: number | null }>(`SELECT COUNT(*) AS n, SUM(deleted = 0) AS live FROM rows INDEXED BY rows_cursor WHERE ${["version > ?", "version <= ?", "table_id = ?", ...seen.where].join(" AND ")}`, q.since, q.upto, q.table, ...seen.args)        .one();      return { n: Number(r.n), live: Number(r.live ?? 0) };    }    const r = this.sql      .exec<{ n: number; live: number | null }>(`SELECT COUNT(*) AS n, SUM(deleted = 0) AS live FROM rows WHERE ${["table_id = ?", "version > ?", "version <= ?", ...seen.where].join(" AND ")}`, q.table, q.since, q.upto, ...seen.args)      .one();    return { n: Number(r.n), live: Number(r.live ?? 0) };  }  /** The rows `scope` may see, less the rows a window leaves out, as SQL conditions over `rows`. */  private static seenBy(scope: SyncScope, windows: SyncWindow[]): { where: string[]; args: SqlStorageValue[] } {    const where: string[] = ["table_id NOT IN (SELECT value FROM json_each(?))"];    const args: SqlStorageValue[] = [JSON.stringify([...scope.except])];    if (scope.kind === "tables") {      const own = scope.person === null ? [] : [...scope.own];      where.push("(table_id IN (SELECT value FROM json_each(?)) OR (owner = ? AND table_id IN (SELECT value FROM json_each(?))))");      args.push(JSON.stringify([...scope.whole]), scope.person, JSON.stringify(own));    }    for (const w of windows) {      if (w.is) {        // A kit's `only`: a live row whose value is none of these (or is no value) stays out; a tombstone comes.        where.push("NOT (table_id = ? AND deleted = 0 AND COALESCE(json_extract(data, ?) NOT IN (SELECT value FROM json_each(?)), 1))");        args.push(w.table, `$.${w.column}`, JSON.stringify(w.is));        continue;      }      // A live row dated before the window's start stays out; a tombstone, or a row with no date, comes.      // A table dated by when its rows were made or changed reads the row's own time.      if (w.column === "created_at" || w.column === "updated_at") {        where.push(`NOT (table_id = ? AND deleted = 0 AND ${w.column} < ?)`);        args.push(w.table, w.from);      } else {        where.push("NOT (table_id = ? AND deleted = 0 AND COALESCE(json_extract(data, ?) < ?, 0))");        args.push(w.table, `$.${w.column}`, w.from);      }    }    return { where, args };  }  /**   * One page of live mail's (id, landed_at) after `after`, in id order (`GET /v1/landed`): the primary key and the   * column the object stamps itself. A row held before the column came reads its default from the record header,   * never its data.   */  landedPage(after: string | null, limit: number): { rows: [string, string][]; more: boolean } {    this.landing();    const rows = this.sql      .exec<{ id: string; landed_at: string }>(        `SELECT id, landed_at FROM rows WHERE table_id = ? AND deleted = 0${after !== null ? " AND id > ?" : ""} ORDER BY id LIMIT ?`,        LANDED_TABLE,        ...(after !== null ? [after] : []),        limit + 1,      )      .toArray()      .map((r): [string, string] => [r.id, r.landed_at]);    const more = rows.length > limit;    return { rows: more ? rows.slice(0, limit) : rows, more };  }  /** The (id, landed_at) of the named live mail the object holds; an id it does not hold is left out. */  landedOf(ids: string[]): [string, string][] {    this.landing();    const out: [string, string][] = [];    for (let i = 0; i < ids.length; i += 100) {      const part = ids.slice(i, i + 100);      const found = this.sql        .exec<{ id: string; landed_at: string }>(`SELECT id, landed_at FROM rows WHERE table_id = ? AND deleted = 0 AND id IN (${part.map(() => "?").join(", ")})`, LANDED_TABLE, ...part)        .toArray();      for (const r of found) out.push([r.id, r.landed_at]);    }    return out;  }  /**   * One page of the ids `tables` hold, live and deleted alike, in (table, id)   * order after `after`: ids and the deleted mark only, never a row's data   * (`GET /v1/held`, src/business.ts). Reads the primary key alone.   */  heldPage(tables: string[], after: { table: string; id: string } | null, limit: number): { ids: { table: string; id: string; deleted: boolean }[]; more: boolean } {    const where = ["table_id IN (SELECT value FROM json_each(?))", ...(after ? ["(table_id, id) > (?, ?)"] : [])];    const args: SqlStorageValue[] = [JSON.stringify(tables), ...(after ? [after.table, after.id] : [])];    const ids = this.sql      .exec<{ table_id: string; id: string; deleted: number }>(`SELECT table_id, id, deleted FROM rows WHERE ${where.join(" AND ")} ORDER BY table_id, id LIMIT ?`, ...args, limit + 1)      .toArray()      .map((r) => ({ table: r.table_id, id: r.id, deleted: r.deleted === 1 }));    const more = ids.length > limit;    return { ids: more ? ids.slice(0, limit) : ids, more };  }  /**   * The latest binned rows of one table, by its bin column (`trashed_at`, `deleted_at`) newest first (READ COST, 28 Nov   * 2026): a partial index holds only rows whose bin column is set, ordered by it, so `list_bin` reads the page it   * answers, never the table (it walked every binned table whole: 190k rows read beside 200k). Null where the index   * nor its shadow stands (Store.lookup): the caller reads as it did.   */  binnedLatest(table: string, bin: string, limit: number): StoredRow[] | null {    const at = col(bin);    const name = `rows_bin_${bin.replace(/[^A-Za-z0-9_]/g, "_")}`;    const set = `json_type(data, '$."${bin}"') = 'text'`;    const along = this.lookup(name, `CREATE INDEX IF NOT EXISTS ${name} ON rows (table_id, ${at} DESC, id) WHERE deleted = 0 AND ${set}`, {      name: `bin_${table.replace(/[^A-Za-z0-9_]/g, "_")}__${bin.replace(/[^A-Za-z0-9_]/g, "_")}`,      table,      terms: [{ expr: at, desc: true }, { expr: "id" }],      live: true,      where: `${set} AND ${at} <> ''`,    });    if (!along) return null;    if (along !== "index") {      return this.sql        .exec<RawRow>(`SELECT rows.* FROM ${orderShadow.from(along)} WHERE rows.deleted = 0 ORDER BY ${orderShadow.orderBy(along)} LIMIT ?`, limit)        .toArray()        .map(Store.row);    }    return this.sql      .exec<RawRow>(`SELECT * FROM rows INDEXED BY ${name} WHERE table_id = ? AND deleted = 0 AND ${set} AND ${at} <> '' ORDER BY ${at} DESC, id LIMIT ?`, table, limit)      .toArray()      .map(Store.row);  }  /**   * One page of binned rows (a clear `trashed_at` set, not deleted) of `tables`, in (table, id) order after `after`   * (TRIM 3, 21 Nov 2026): what a phone's Bin lists from the object once its copy no longer keeps rows binned more   * than 7 days ago. A partial index holds only binned rows, so a page reads only them.   */  binnedPage(tables: string[], after: { table: string; id: string } | null, limit: number): { rows: StoredRow[]; more: boolean } {    this.sql.exec("CREATE INDEX IF NOT EXISTS rows_binned ON rows (table_id, id) WHERE deleted = 0 AND json_extract(data, '$.trashed_at') IS NOT NULL");    const where = ["deleted = 0", "json_extract(data, '$.trashed_at') IS NOT NULL", "table_id IN (SELECT value FROM json_each(?))", ...(after ? ["(table_id, id) > (?, ?)"] : [])];    const args: SqlStorageValue[] = [JSON.stringify(tables), ...(after ? [after.table, after.id] : [])];    const rows = this.sql      .exec<RawRow>(`SELECT * FROM rows INDEXED BY rows_binned WHERE ${where.join(" AND ")} ORDER BY table_id, id LIMIT ?`, ...args, limit + 1)      .toArray()      .map(Store.row);    const more = rows.length > limit;    return { rows: more ? rows.slice(0, limit) : rows, more };  }  /**   * Same-name `#` tag groups of notes (the old 409 loop, 21 Nov 2026), counted without a key: a group's name is   * sealed, but its blind tokens are the same for the same name in any case, so live note groups are gathered by   * their tokens (an open name by itself, without case). Two names of the same words but other punctuation   * (`#home/garden`, `#home garden`) are counted as one: the count is an upper bound. Counts only, no name.   */  duplicateNoteGroups(): { note_groups: number; names_held_twice: number; later_groups: number; largest: number } {    const rows = this.sql      .exec<{ n: number }>(        `WITH g AS (           SELECT r.id, json_extract(r.data, '$.name') AS name FROM rows r           WHERE r.table_id = 'record_group' AND r.deleted = 0 AND json_extract(r.data, '$.deleted_at') IS NULL             AND json_extract(r.data, '$.table_id') = 'note' AND json_extract(r.data, '$.filter') IS NULL         ), s AS (           SELECT g.id, COALESCE(             (SELECT CASE WHEN br.toks IS NOT NULL THEN 'k:' || hex(br.toks) ELSE (SELECT group_concat(tok, ',') FROM (SELECT b.tok FROM blind b WHERE b.rid = br.rid ORDER BY b.tok)) END FROM blind_row br WHERE br.table_id = 'record_group' AND br.id = g.id),             CASE WHEN typeof(g.name) = 'text' AND g.name LIKE '#%' THEN 'open:' || lower(trim(g.name)) END           ) AS sig FROM g         )         SELECT COUNT(*) AS n FROM s WHERE sig IS NOT NULL GROUP BY sig`,      )      .toArray();    const held = rows.filter((r) => r.n > 1);    return {      note_groups: rows.reduce((sum, r) => sum + r.n, 0),      names_held_twice: held.length,      later_groups: held.reduce((sum, r) => sum + r.n - 1, 0),      largest: held.reduce((most, r) => Math.max(most, r.n), 0),    };  }  /** One page of live rows in (table, id) order after `after`, for the export. */  livePage(after: { table: string; id: string } | null, limit: number): { rows: StoredRow[]; more: boolean } {    const rows = (      after        ? this.sql.exec<RawRow>("SELECT * FROM rows WHERE deleted = 0 AND (table_id, id) > (?, ?) ORDER BY table_id, id LIMIT ?", after.table, after.id, limit + 1)        : this.sql.exec<RawRow>("SELECT * FROM rows WHERE deleted = 0 ORDER BY table_id, id LIMIT ?", limit + 1)    )      .toArray()      .map(Store.row);    const more = rows.length > limit;    return { rows: more ? rows.slice(0, limit) : rows, more };  }  /**   * One figure per group over a table's live rows where every condition holds:   * `group` an SQL expression over the row (null for one group of all), each   * of `measures` an aggregate (`COUNT(*)`, `SUM(...)`). Groups come in the   * group's order, at most `limit`.   */  summary(table: string, where: Cond[], group: string | null, measures: string[], limit: number): { group: SqlStorageValue; figures: SqlStorageValue[] }[] {    const extra = where.map((w) => ` AND (${w.sql})`).join("");    const picks = [`${group ?? "NULL"} AS g`, ...measures.map((m, i) => `${m} AS m${i}`)].join(", ");    const tail = group ? ` GROUP BY g ORDER BY g IS NULL, g LIMIT ${Math.trunc(limit)}` : "";    return this.sql      .exec<Record<string, SqlStorageValue>>(`SELECT ${picks} FROM rows WHERE table_id = ? AND deleted = 0${extra}${tail}`, table, ...where.flatMap((w) => w.args))      .toArray()      .map((r) => ({ group: r.g ?? null, figures: measures.map((_, i) => r[`m${i}`] ?? null) }));  }  /** Each table's rows, live and tombstones, and the bytes their data holds; the change log's rows. */  storage(): { tables: { table: string; rows: number; tombstones: number; bytes: number }[]; changes: number } {    const tables = this.sql      .exec<{ table_id: string; live: number; dead: number; bytes: number }>("SELECT table_id, SUM(deleted = 0) AS live, SUM(deleted = 1) AS dead, SUM(LENGTH(CAST(data AS BLOB)) + LENGTH(id) + 64) AS bytes FROM rows GROUP BY table_id ORDER BY bytes DESC, table_id")      .toArray()      .map((r) => ({ table: r.table_id, rows: Number(r.live), tombstones: Number(r.dead), bytes: Number(r.bytes) }));    const changes = Number(this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM change").one().n);    return { tables, changes };  }  /** The change log's entries, counted along its smallest index. */  changeCount(): number {    return Number(this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM change").one().n);  }  /** Where the file's bytes go, part by part, sizes only (src/storage_parts.ts). */  parts(): StorageParts {    return storageParts(this.sql);  }  /**   * What storage_summary says of the tables, the parts and the change log's writers (src/storage_measure.ts): a small   * object's worked out now; a big one's as its alarm last measured them, with when, and how far a new measure is.   */  storageMeasure(now: Date): { measure: Measure | null; measuring: { since: string; done: number } | null } {    if (this.sql.databaseSize < SMALL_FILE) return { measure: measureNow(this.sql, now, this.linkTargets()), measuring: null };    const host = this.measureHost();    return { measure: lastMeasure(host), measuring: measuring(host) };  }  /** One alarm's share of measuring a big object (src/storage_measure.ts); answers whether more is left. */  measureStorage(now: Date): boolean {    if (this.sql.databaseSize < SMALL_FILE) return false;    return measureStep(this.measureHost(), now);  }  /** JOBS OUT C3: whether a measure step would do anything now: a big object whose measure is under way or due. Meta only. */  measureOwed(now: Date): boolean {    if (this.sql.databaseSize < SMALL_FILE) return false;    return measureDue({ sql: this.sql, meta: (key) => this.meta(key), setMeta: (key, value) => this.setMeta(key, value) }, now);  }  private measureHost(): { sql: SqlStorage; meta(key: string): string | null; setMeta(key: string, value: string | null): void; links: LinkTarget[] } {    return { sql: this.sql, meta: (key) => this.meta(key), setMeta: (key, value) => this.setMeta(key, value), links: this.linkTargets() };  }  /**   * Every single-valued link column the links index holds and the table it links to, read from the stored table   * definitions: what the measure's `dangling` checks a target against. A column linking to a table the object does   * not define (a business's `person`, kept in `people`) is left out: its rows are not in `rows` to be found.   */  linkTargets(): LinkTarget[] {    const tables = this.definitions("table");    const defined = new Set(tables.map((t) => String(t.id)));    const out: LinkTarget[] = [];    for (const t of tables) {      for (const c of Array.isArray(t.columns) ? (t.columns as Record<string, unknown>[]) : []) {        if (c.type !== "link" || c.computed || c.multiple === true || typeof c.key !== "string" || typeof c.link_to !== "string" || !defined.has(c.link_to)) continue;        out.push([String(t.id), c.key, c.link_to]);      }    }    return out;  }  /**   * Who fills the change log: its entries by what wrote them (`via`, an act's or a tool's name), the table and the   * kind, with the characters their before and after take, the largest first. Names and sizes only, never a value.   */  changesBy(most = 30): { via: string | null; table: string; kind: string; entries: number; chars: number }[] {    return this.sql      .exec<{ via: string | null; table_id: string; kind: string; n: number; chars: number }>(        "SELECT via, table_id, kind, COUNT(*) AS n, SUM(coalesce(length(before), 0) + coalesce(length(after), 0)) AS chars FROM change GROUP BY via, table_id, kind ORDER BY chars DESC LIMIT ?",        most,      )      .toArray()      .map((r) => ({ via: r.via, table: r.table_id, kind: r.kind, entries: Number(r.n), chars: Number(r.chars) }));  }  /**   * The entries machine writers left with bodies (logged before src/changes.ts MACHINE_WRITERS, or as acts), by writer:   * how many and the characters their before and after take. With `apply`, at most `most` of them, the largest first,   * keep only that they happened (kind `machine`, no before or after): no record is touched, and no entry goes.   */  thinMachineChanges(vias: readonly string[], apply: boolean, most = 2_000): { by: { via: string; entries: number; chars: number }[]; thinned: number; more: boolean } {    if (!vias.length) return { by: [], thinned: 0, more: false };    const marks = vias.map(() => "?").join(", ");    const fat = `via IN (${marks}) AND kind NOT IN ('machine', 'import') AND (before IS NOT NULL OR after IS NOT NULL)`;    const by = this.sql      .exec<{ via: string; n: number; chars: number }>(`SELECT via, COUNT(*) AS n, SUM(coalesce(length(before), 0) + coalesce(length(after), 0)) AS chars FROM change WHERE ${fat} GROUP BY via ORDER BY chars DESC`, ...vias)      .toArray()      .map((r) => ({ via: r.via, entries: Number(r.n), chars: Number(r.chars) }));    if (!apply) return { by, thinned: 0, more: by.length > 0 };    const ids = this.sql      .exec<{ id: number }>(`SELECT id FROM change WHERE ${fat} ORDER BY coalesce(length(before), 0) + coalesce(length(after), 0) DESC LIMIT ?`, ...vias, most)      .toArray()      .map((r) => Number(r.id));    for (const id of ids) this.sql.exec("UPDATE change SET kind = 'machine', before = NULL, after = NULL WHERE id = ?", id);    const left = this.sql.exec(`SELECT 1 FROM change WHERE ${fat} LIMIT 1`, ...vias).toArray().length > 0;    return { by, thinned: ids.length, more: left };  }  /** Live rows by table: what the object holds, counted without reading a row. */  counts(): Record<string, number> {    const out: Record<string, number> = {};    // From row_counts once every table is counted; else one count per table along its own index, never one GROUP BY over every row.    if (this.countsReady()) {      for (const r of this.sql.exec<{ table_id: string; n: number }>("SELECT table_id, SUM(n) AS n FROM row_counts WHERE deleted = 0 GROUP BY table_id ORDER BY table_id")) if (Number(r.n) > 0) out[r.table_id] = Number(r.n);      return out;    }    for (const table of this.tablesHeld()) {      const n = Number(this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rows WHERE table_id = ? AND deleted = 0", table).one().n);      if (n > 0) out[table] = n;    }    return out;  }  // ── people ─────────────────────────────────────────────────────────────  person(id: string): Person | null {    const r = this.sql.exec<RawPerson>("SELECT * FROM people WHERE id = ?", id).toArray()[0];    return r ? Store.person(r) : null;  }  personByPhone(phone: string): Person | null {    const r = this.sql.exec<RawPerson>("SELECT * FROM people WHERE phone = ?", phone).toArray()[0];    return r ? Store.person(r) : null;  }  people(): Person[] {    return this.sql.exec<RawPerson>("SELECT * FROM people ORDER BY created_at, id").toArray().map(Store.person);  }  peopleSince(since: number): Person[] {    return this.sql.exec<RawPerson>("SELECT * FROM people WHERE version > ? ORDER BY version", since).toArray().map(Store.person);  }  addPerson(id: string, phone: string, name: string | null, role: Person["role"], version: number): Person {    const at = this.now().toISOString();    this.sql.exec("INSERT INTO people (id, phone, name, role, created_at, version) VALUES (?, ?, ?, ?, ?, ?)", id, phone, name, role, at, version);    return { id, phone, name, role, created_at: at, version };  }  setPerson(id: string, patch: { name?: string | null; role?: Person["role"] }, version: number): Person {    const current = this.person(id);    if (!current) refuse(404, "no_such_person", "no such person");    const name = patch.name === undefined ? current.name : patch.name;    const role = patch.role ?? current.role;    this.sql.exec("UPDATE people SET name = ?, role = ?, version = ? WHERE id = ?", name, role, version, id);    return { ...current, name, role, version };  }  private static person(r: RawPerson): Person {    return { id: r.id, phone: r.phone, name: r.name, role: r.role as Person["role"], created_at: r.created_at, version: Number(r.version) };  }  // ── codes and sessions ─────────────────────────────────────────────────  codesIssuedRecently(phone: string, sinceSeconds: number): number {    const r = this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM codes WHERE phone = ? AND created_at > ?", phone, sinceSeconds).toArray()[0];    return r ? Number(r.n) : 0;  }  addCode(id: string, phone: string, codeHash: string, deviceId: string, expiresAt: number): void {    const now = Math.floor(this.now().getTime() / 1000);    this.sql.exec(      "INSERT INTO codes (id, phone, code_hash, device_id, expires_at, tries, used, created_at) VALUES (?, ?, ?, ?, ?, 0, 0, ?)",      id,      phone,      codeHash,      deviceId,      expiresAt,      now,    );  }  code(id: string): { id: string; phone: string; code_hash: string; device_id: string; expires_at: number; tries: number; used: number } | null {    const r = this.sql      .exec<{ id: string; phone: string; code_hash: string; device_id: string; expires_at: number; tries: number; used: number }>(        "SELECT id, phone, code_hash, device_id, expires_at, tries, used FROM codes WHERE id = ?",        id,      )      .toArray()[0];    return r ?? null;  }  codeTried(id: string): void {    this.sql.exec("UPDATE codes SET tries = tries + 1 WHERE id = ?", id);  }  /** Mark a challenge proven. `proof` (a hash of the challenge and the code that proved it) is kept so the same form sent twice can be told from a new guess. */  codeUsed(id: string, proof?: string): void {    if (proof) this.sql.exec("UPDATE codes SET used = 1, code_hash = ? WHERE id = ?", proof, id);    else this.sql.exec("UPDATE codes SET used = 1 WHERE id = ?", id);  }  addSession(tokenHash: string, personId: string, deviceId: string, issuedAt: number, expiresAt: number): void {    this.sql.exec(      "INSERT INTO sessions (token_hash, person_id, device_id, issued_at, expires_at, revoked) VALUES (?, ?, ?, ?, ?, 0)",      tokenHash,      personId,      deviceId,      issuedAt,      expiresAt,    );  }  session(tokenHash: string): { person_id: string; device_id: string; expires_at: number; revoked: number } | null {    const r = this.sql      .exec<{ person_id: string; device_id: string; expires_at: number; revoked: number }>(        "SELECT person_id, device_id, expires_at, revoked FROM sessions WHERE token_hash = ?",        tokenHash,      )      .toArray()[0];    return r ?? null;  }  revokeSession(tokenHash: string): void {    if (this.sql.exec("UPDATE sessions SET revoked = 1 WHERE token_hash = ? AND revoked = 0", tokenHash).rowsWritten > 0) neverAgain.note(this.sql, { kind: "session_revoked", token_hash: tokenHash, at: new Date().toISOString() });  }  revokePersonSessions(personId: string): void {    // Each sign-in by its own hash: a later sign-in of the same person is never caught by a restore's replay.    for (const { token_hash } of this.sql.exec<{ token_hash: string }>("UPDATE sessions SET revoked = 1 WHERE person_id = ? AND revoked = 0 RETURNING token_hash", personId).toArray()) neverAgain.note(this.sql, { kind: "session_revoked", token_hash, at: new Date().toISOString() });  }  // ── the act log ────────────────────────────────────────────────────────  logAct(id: string, personId: string | null, act: string, args: unknown, outcome: string): void {    this.sql.exec(      "INSERT INTO acts (id, at, person_id, act, args, outcome) VALUES (?, ?, ?, ?, ?, ?)",      id,      this.now().toISOString(),      personId,      act,      JSON.stringify(args).slice(0, 4000),      outcome,    );  }  // ── the blind index (src/seal.ts, sealing plan §4) ─────────────────────  /**   * A sealed row's blind tokens, replacing whatever it held; none clears it.   * A token is the decimal text of a signed 64-bit number, bound as text and   * cast by SQLite so no digit is lost to a JavaScript number.   */  setBlind(table: string, id: string, tokens: string[]): void {    const held = this.sql.exec<{ rid: number }>("SELECT rid FROM blind_row WHERE table_id = ? AND id = ?", table, id).toArray()[0];    // The row's old tokens go along their own list (src/blind.ts), never a scan of the index by row.    if (held) blind.dropTokens(this.sql, held.rid);    if (!tokens.length) {      if (held) this.sql.exec("DELETE FROM blind_row WHERE rid = ?", held.rid);      return;    }    const toks = blind.pack(tokens);    const rid = held ? held.rid : Number(this.sql.exec<{ rid: number }>("INSERT INTO blind_row (table_id, id, toks) VALUES (?, ?, ?) RETURNING rid", table, id, toks).one().rid);    if (held) this.sql.exec("UPDATE blind_row SET toks = ? WHERE rid = ?", toks, rid);    // One statement for the row's tokens (LIVE CPU 4: one a token cost more in statements than in the index).    this.sql.exec("INSERT OR IGNORE INTO blind (tok, rid) SELECT CAST(value AS INTEGER), ? FROM json_each(?)", rid, JSON.stringify(tokens));  }  /** A row's blind tokens, as decimal text, in order (for tests and checks): from its own list once it holds one. */  blindOf(table: string, id: string): string[] {    const held = this.sql.exec<{ rid: number; toks: ArrayBuffer | null }>("SELECT rid, toks FROM blind_row WHERE table_id = ? AND id = ?", table, id).toArray()[0];    if (!held) return [];    if (held.toks !== null) return blind.unpack(held.toks);    return this.sql      .exec<{ tok: string }>("SELECT CAST(tok AS TEXT) AS tok FROM blind WHERE rid = ? ORDER BY tok", held.rid)      .toArray()      .map((r) => r.tok);  }  /**   * The ids of `table`'s live rows holding every one of `tokens`, newest   * first by the table's clear date column (else by when they were made),   * at most `limit`.   */  /**   * A dated table's live rows older than a place, newest first by `by` (MAIL.md, 21 Nov 2026: a phone keeps a window   * of mail and pages what is older from here as a person scrolls). `before` is exclusive, `[at, id]` the last row a   * page carried (`id` "" before every row of that moment); `from` and `to` bound `by` inclusively; `eq` keeps the rows   * whose `column` holds `value`. Read along the first order's index (`rows_first_<table>`, or   * `rows_first_<table>__<column>` with `eq`), so a page reads a page.   */  olderPage(table: string, by: string, q: { before: [string, string] | null; from: string | null; to: string | null; eq: { column: string; value: string } | null; limit: number }): StoredRow[] {    const t = Store.named(table);    const ord = Store.ord(by);    const column = q.eq ? Store.named(q.eq.column) : undefined;    const name = column ? `rows_first_${t}__${column}` : `rows_first_${t}`;    // A small file makes the index here, as it always did. A big one never does (LIVE CPU 3: making it reads the whole    // file in this request); there the shadow walks once the account's switch has it ready, and a sort stands in until.    let f: { from: string; k: string; id: string; g: string } | null = null;    if (this.hasIndex(name) || this.sql.databaseSize < FIRST_INDEX_NOW_BYTES) {      this.sql.exec(`CREATE INDEX IF NOT EXISTS rows_first_${t} ON rows (${ord}, id) WHERE table_id = '${t}'`);      if (column) this.sql.exec(`CREATE INDEX IF NOT EXISTS ${name} ON rows (json_extract(data, '$.${column}'), ${ord}, id) WHERE table_id = '${t}'`);      f = this.firstFrom(t, by, column);    } else if (orderShadow.on(this.shadowMeta()) && orderShadow.ask(this.shadowMeta(), Store.firstShadow(t, by, column))) f = this.firstFrom(t, by, column);    const sorted = f ?? { from: "rows", k: ord, id: "id", g: column ? `json_extract(data, '$.${column}')` : "" };    const where = [`table_id = '${t}'`, "deleted = 0"];    const args: SqlStorageValue[] = [];    if (q.eq) {      where.push(`${sorted.g} = ?`);      args.push(q.eq.value);    }    if (q.before) {      where.push(q.before[1] === "" ? `${sorted.k} < ?` : `(${sorted.k}, ${sorted.id}) < (?, ?)`);      args.push(...(q.before[1] === "" ? [q.before[0]] : q.before));    }    if (q.from !== null) {      where.push(`${sorted.k} >= ?`);      args.push(q.from);    }    if (q.to !== null) {      where.push(`${sorted.k} <= ?`);      args.push(q.to);    }    return this.sql      .exec<RawRow>(`SELECT rows.* FROM ${sorted.from} WHERE ${where.join(" AND ")} ORDER BY ${sorted.k} DESC, ${sorted.id} DESC LIMIT ?`, ...args, q.limit)      .toArray()      .map((r) => Store.row(r));  }  /**   * Cotton Data's page of any table (`GET /v1/data/page`): its live rows newest first by `created_at`, then id, older   * than `before` (exclusive; `[created_at, id]` of the last row a page carried, or `[created_at, ""]` for a moment),   * at most `limit`. Along `rows_made (table_id, created_at, id)`, which every table has: no index is made, no sort.   */  madePage(table: string, before: [string, string] | null, limit: number, opts: { order?: "made" | "changed"; from?: string | null; to?: string | null } = {}): StoredRow[] {    // `changed` orders by updated_at: there is no index on it, so the table's rows are found by rows_made's table prefix    // and sorted (a sort of one table's live rows, as a sync page's scan is).    const at = opts.order === "changed" ? "updated_at" : "created_at";    const where = ["table_id = ?", "deleted = 0"];    const args: SqlStorageValue[] = [table];    // The made-date range: from inclusive, to exclusive, both ISO instants.    if (opts.from) {      where.push("created_at >= ?");      args.push(opts.from);    }    if (opts.to) {      where.push("created_at < ?");      args.push(opts.to);    }    if (before) {      where.push(before[1] === "" ? `${at} < ?` : `(${at}, id) < (?, ?)`);      args.push(...(before[1] === "" ? [before[0]] : before));    }    return this.sql      .exec<RawRow>(`SELECT * FROM rows INDEXED BY rows_made WHERE ${where.join(" AND ")} ORDER BY ${at} DESC, id DESC LIMIT ?`, ...args, limit)      .toArray()      .map((r) => Store.row(r));  }  /** Cotton Data's Sort and dates: a table's live rows counted per year they were made, newest year first. */  madeYears(table: string): { year: number; rows: number }[] {    return this.sql      .exec<{ y: string; n: number }>("SELECT substr(created_at, 1, 4) AS y, COUNT(*) AS n FROM rows INDEXED BY rows_made WHERE table_id = ? AND deleted = 0 GROUP BY y ORDER BY y DESC", table)      .toArray()      .filter((r) => /^\d{4}$/.test(r.y))      .map((r) => ({ year: Number(r.y), rows: Number(r.n) }));  }  /**   * The live rows of `table` whose single-valued link `column` names `target` (Cotton Data's points here), along   * links_target: how many in all, and the ids of at most `most`, in the index's order. A link of a row since deleted   * or erased is left out (CROSS JOIN keeps links outer, as `linked` does).   */  pointing(table: string, column: string, target: string, most: number): { count: number; ids: string[] } {    const from = "FROM links l CROSS JOIN rows r ON r.table_id = l.table_id AND r.id = l.id WHERE l.table_id = ? AND l.column = ? AND l.target = ? AND r.deleted = 0";    const count = Number(this.sql.exec<{ n: number }>(`SELECT COUNT(*) AS n ${from}`, table, column, target).one().n);    const ids = count ? this.sql.exec<{ id: string }>(`SELECT l.id AS id ${from} LIMIT ?`, table, column, target, most).toArray().map((r) => r.id) : [];    return { count, ids };  }  /**   * A page of the change log's heads, newest first, never its before or after (Cotton Data's Lately): entries below   * `before` (an id), of `table`, never of `hidden` tables, written by `who` (assistants: a token named in   * `tokens`; apps: no token, through one of `machine`; you: no token, through anything else), at most `limit`.   */  changeHeads(q: { before: number | null; table: string | null; hidden: string[]; who: "you" | "apps" | "assistants" | null; tokens: string[]; machine: string[]; limit: number }): ChangeHead[] {    const where: string[] = [];    const args: SqlStorageValue[] = [];    if (q.before !== null) {      where.push("id < ?");      args.push(q.before);    }    if (q.table !== null) {      where.push("table_id = ?");      args.push(q.table);    }    if (q.hidden.length) {      where.push("table_id NOT IN (SELECT value FROM json_each(?))");      args.push(JSON.stringify(q.hidden));    }    const token = "(actor IS NOT NULL AND actor IN (SELECT value FROM json_each(?)))";    const machine = "(via IS NOT NULL AND via IN (SELECT value FROM json_each(?)))";    if (q.who === "assistants") {      where.push(token);      args.push(JSON.stringify(q.tokens));    } else if (q.who === "apps" || q.who === "you") {      where.push(`NOT ${token}`, q.who === "apps" ? machine : `NOT ${machine}`);      args.push(JSON.stringify(q.tokens), JSON.stringify(q.machine));    }    const clause = where.length ? ` WHERE ${where.join(" AND ")}` : "";    return this.sql      .exec<{ id: number; at: string; actor: string | null; via: string | null; table_id: string; record_id: string; kind: string }>(        `SELECT id, at, actor, via, table_id, record_id, kind FROM change${clause} ORDER BY id DESC LIMIT ?`,        ...args,        q.limit,      )      .toArray()      .map((r) => ({ id: Number(r.id), at: r.at, actor: r.actor, via: r.via, table: r.table_id, record_id: r.record_id, kind: r.kind }));  }  /** Every row id of `table`, deleted ones too (the tokens, revoked or not: who in the change log is an assistant). */  allIds(table: string): string[] {    return this.sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = ?", table).toArray().map((r) => r.id);  }  /**   * The rows of `table` holding every one of `tokens`, as a condition for a select that orders and cuts them itself   * (`select`): no row is read or sorted here. Seen at the owner's size (25 Nov 2026): `list_sessions { machine }` over   * 3,257 sealed sessions sorted the 1,086 that matched by a column of their stored row twice, once here and once in   * the select, and took 4.5 s.   */  blindCond(table: string, tokens: string[]): Cond {    if (!tokens.length) return { sql: "0", args: [] };    const marks = tokens.map(() => "CAST(? AS INTEGER)").join(", ");    return {      sql: `id IN (SELECT r.id FROM blind_row r WHERE r.table_id = ? AND r.rid IN (SELECT rid FROM blind WHERE tok IN (${marks}) GROUP BY rid HAVING COUNT(*) = ?))`,      args: [table, ...tokens, tokens.length],    };  }  blindIds(table: string, tokens: string[], dateColumn: string | null, limit: number): string[] {    if (!tokens.length) return [];    const marks = tokens.map(() => "CAST(? AS INTEGER)").join(", ");    const order = dateColumn ? `${col(dateColumn)} DESC, rows.created_at DESC, rows.id` : "rows.created_at DESC, rows.id";    return this.sql      .exec<{ id: string }>(        `SELECT rows.id AS id FROM blind_row r JOIN rows ON rows.table_id = r.table_id AND rows.id = r.id         WHERE r.table_id = ? AND rows.deleted = 0 AND r.rid IN (SELECT rid FROM blind WHERE tok IN (${marks}) GROUP BY rid HAVING COUNT(*) = ?)         ORDER BY ${order} LIMIT ?`,        table,        ...tokens,        tokens.length,        limit,      )      .toArray()      .map((r) => r.id);  }  // ── the change log (src/changes.ts) ────────────────────────────────────  /**   * One record's logged changes keep none of `columns`: a row sealed takes   * its open past's plaintext out of the log (sealing plan §7 step 3). A   * change left saying nothing keeps an empty object, so undo still reads it   * as the kind of write it was.   */  scrubChanges(table: string, recordId: string, columns: string[]): void {    if (!columns.length) return;    const drop = (text: string | null): string | null => {      if (text === null) return null;      const data = JSON.parse(text) as Record<string, unknown>;      for (const k of columns) delete data[k];      return JSON.stringify(data);    };    for (const c of this.sql.exec<{ id: number; before: string | null; after: string | null }>("SELECT id, before, after FROM change WHERE table_id = ? AND record_id = ?", table, recordId).toArray()) {      const before = drop(c.before);      const after = drop(c.after);      if (before !== c.before || after !== c.after) this.sql.exec("UPDATE change SET before = ?, after = ? WHERE id = ?", before, after, c.id);    }  }  /** Every logged change of one record goes: it was erased, and the log keeps nothing it held. */  forgetChanges(table: string, recordId: string): void {    this.sql.exec("DELETE FROM change WHERE table_id = ? AND record_id = ?", table, recordId);  }  /** One row write, logged; answers the change's id. */  addChange(c: Omit<ChangeRow, "id" | "at" | "undone_by">): number {    const r = this.sql      .exec<{ id: number }>(        "INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",        this.now().toISOString(),        c.actor,        c.via,        c.table,        c.record_id,        c.kind,        c.before === null ? null : JSON.stringify(c.before),        c.after === null ? null : JSON.stringify(c.after),        c.version,      )      .one();    return Number(r.id);  }  change(id: number): ChangeRow | null {    const r = this.sql.exec<RawChange>("SELECT * FROM change WHERE id = ?", id).toArray()[0];    return r ? Store.changeRow(r) : null;  }  /** One record's changes after `after`, the latest first. */  changesSince(table: string, recordId: string, after: number): ChangeRow[] {    return this.sql      .exec<RawChange>("SELECT * FROM change WHERE table_id = ? AND record_id = ? AND id > ? ORDER BY id DESC", table, recordId, after)      .toArray()      .map(Store.changeRow);  }  /** A page of the log, the latest first, where every condition holds (SQL over `change`). */  changes(where: Cond[], limit: number): ChangeRow[] {    const clause = where.length ? ` WHERE ${where.map((w) => `(${w.sql})`).join(" AND ")}` : "";    return this.sql      .exec<RawChange>(`SELECT * FROM change${clause} ORDER BY id DESC LIMIT ?`, ...where.flatMap((w) => w.args), limit)      .toArray()      .map(Store.changeRow);  }  markUndone(id: number, by: number): void {    this.sql.exec("UPDATE change SET undone_by = ? WHERE id = ?", by, id);  }  /**   * The log kept to its window: nothing older than `before`, at most `rows` of the latest, and, with a `budget`, at   * most that many characters of before and after (the counted size, `changeSize`). The oldest go first, a step at a   * time: at most `most` changes and about CHANGE_STEP_CHARS of them a call (an entry runs to tens of kilobytes, so a   * count alone made one alarm's transaction hundreds of megabytes). Answers how many went and whether more are left.   */  trimChanges(before: string, rows: number, budget: number | null = null, most = TRIM_STEP, stepChars = CHANGE_STEP_CHARS, floor: string | null = null): { trimmed: number; more: boolean } {    // AUDIT C 3: the count never takes an entry newer than `floor` (its age, or the size budget the account sets, does),    // so a flood of cheap writes cannot flush the recent undo history.    const old = (at: string) => floor === null || at < floor;    const ends = this.sql.exec<{ first: number | null; last: number | null }>("SELECT MIN(id) AS first, MAX(id) AS last FROM change").one();    if (ends.first === null || ends.last === null) return { trimmed: 0, more: false };    const last = Number(ends.last);    // Over the budget by this many characters, when the budget is set and the size is counted.    const size = budget === null ? null : this.changeSize();    let over = size?.ready ? size.bytes - budget! : 0;    let upto = Number(ends.first) - 1;    let step = 0;    let going = 0;    let stopped = false;    for (const c of this.sql.exec<{ id: number; at: string; n: number }>("SELECT id, at, coalesce(length(before), 0) + coalesce(length(after), 0) AS n FROM change ORDER BY id LIMIT ?", most)) {      const id = Number(c.id);      if (!(c.at < before || (old(c.at) && id <= last - rows) || over > 0) || (step > 0 && step + Number(c.n) > stepChars)) {        stopped = true;        break;      }      upto = id;      going++;      step += Number(c.n);      over -= Number(c.n);    }    // Counted here, not by rowsWritten: the size triggers' writes are counted there too.    if (going) this.sql.exec("DELETE FROM change WHERE id <= ?", upto);    const trimmed = going;    const next = this.sql.exec<{ id: number; at: string }>("SELECT id, at FROM change ORDER BY id LIMIT 1").toArray()[0];    const still = size?.ready ? this.changeSize().bytes > budget! : false;    return { trimmed, more: !!next && (next.at < before || (old(next.at) && Number(next.id) <= last - rows) || still || (!stopped && trimmed === most)) };  }  /**   * The change log's size in characters of before and after, kept by triggers on `change` (SCHEMA) once counting   * has begun: `bytes` holds every entry above `below`, and counting walks `below` down from the newest a step at a   * time (`countChanges`). Ready once nothing is left below it.   */  changeSize(): { bytes: number; ready: boolean; counting: boolean } {    const s = this.sql.exec<{ bytes: number; below: number }>("SELECT bytes, below FROM change_size").toArray()[0];    if (!s) return { bytes: 0, ready: false, counting: false };    const left = this.sql.exec("SELECT 1 FROM change WHERE id <= ? LIMIT 1", s.below).toArray().length > 0;    return { bytes: Number(s.bytes), ready: !left, counting: true };  }  /** One step of counting the log's size, newest first (`changeSize`); begins it when it has not begun. Answers whether more is left. */  countChanges(most = TRIM_STEP): boolean {    let s = this.sql.exec<{ bytes: number; below: number }>("SELECT bytes, below FROM change_size").toArray()[0];    if (!s) {      const last = Number(this.sql.exec<{ id: number | null }>("SELECT MAX(id) AS id FROM change").one().id ?? 0);      this.sql.exec("INSERT INTO change_size (one, bytes, below) VALUES (1, 0, ?)", last);      s = { bytes: 0, below: last };    }    const part = this.sql      .exec<{ n: number | null; low: number | null; k: number }>(        "SELECT SUM(n) AS n, MIN(id) AS low, COUNT(*) AS k FROM (SELECT id, coalesce(length(before), 0) + coalesce(length(after), 0) AS n FROM change WHERE id <= ? ORDER BY id DESC LIMIT ?)",        s.below,        most,      )      .one();    if (!part.k) return false;    this.sql.exec("UPDATE change_size SET bytes = bytes + ?, below = ?", Number(part.n ?? 0), Number(part.low) - 1);    return this.sql.exec("SELECT 1 FROM change WHERE id < ? LIMIT 1", Number(part.low)).toArray().length > 0;  }  /**   * The act log kept to the change log's window (owner, 22 Nov 2026: his file was 6.5 GB for 1.45 GB of records):   * nothing older than `before`, at most `rows` of the latest, `most` a call, the oldest first. The log was never   * trimmed, each line up to 4,000 characters of an act's args; nothing reads it but the seal purge and the erase,   * which only ever take lines from it. Lines go in rowid order, which is the order they were written.   */  trimActs(before: string, rows: number, most = TRIM_STEP): { trimmed: number; more: boolean } {    const ends = this.sql.exec<{ first: number | null; last: number | null }>("SELECT MIN(rowid) AS first, MAX(rowid) AS last FROM acts").one();    if (ends.first === null || ends.last === null) return { trimmed: 0, more: false };    // By age: the oldest `most` lines, up to the first that is inside the window.    let upto = Number(ends.first) - 1;    for (const a of this.sql.exec<{ r: number; at: string }>("SELECT rowid AS r, at FROM acts ORDER BY rowid LIMIT ?", most)) {      if (a.at >= before) break;      upto = Number(a.r);    }    // By number: the newest `rows` stay.    upto = Math.max(upto, Math.min(Number(ends.last) - rows, Number(ends.first) + most - 1));    const trimmed = upto >= Number(ends.first) ? this.sql.exec("DELETE FROM acts WHERE rowid <= ?", upto).rowsWritten : 0;    const next = this.sql.exec<{ r: number; at: string }>("SELECT rowid AS r, at FROM acts ORDER BY rowid LIMIT 1").toArray()[0];    return { trimmed, more: !!next && (next.at < before || Number(next.r) <= Number(ends.last) - rows) };  }  private static changeRow(r: RawChange): ChangeRow {    return {      id: Number(r.id),      at: r.at,      actor: r.actor,      via: r.via,      table: r.table_id,      record_id: r.record_id,      kind: r.kind as ChangeKind,      before: r.before === null ? null : (JSON.parse(r.before) as Record<string, unknown>),      after: r.after === null ? null : (JSON.parse(r.after) as Record<string, unknown>),      version: Number(r.version),      undone_by: r.undone_by === null ? null : Number(r.undone_by),    };  }}/** What a logged change was: by the write it made, or what it was made for (a bin put back, an act's work). */export type ChangeKind = "create" | "update" | "delete" | "restore" | "act" | "import" | "machine";/** * One row write in the change log: `before` the columns it changed as they * were (the whole record for a delete, null for a create), `after` as they * became (null for a delete), `version` the object's version the write took. *//** A change log entry's head: who, when, which row and what kind, never its before or after. */export interface ChangeHead {  id: number;  at: string;  actor: string | null;  via: string | null;  table: string;  record_id: string;  kind: string;}export interface ChangeRow {  id: number;  at: string;  /** The token (or signed-in person) that wrote it; null for the admin. */  actor: string | null;  /** The act or tool it came through. */  via: string | null;  table: string;  record_id: string;  kind: ChangeKind;  before: Record<string, unknown> | null;  after: Record<string, unknown> | null;  version: number;  undone_by: number | null;}interface RawChange extends Record<string, SqlStorageValue> {  id: number;  at: string;  actor: string | null;  via: string | null;  table_id: string;  record_id: string;  kind: string;  before: string | null;  after: string | null;  version: number;  undone_by: number | null;}interface RawRow extends Record<string, SqlStorageValue> {  table_id: string;  id: string;  data: string;  owner: string | null;  version: number;  deleted: number;  created_at: string;  updated_at: string;  landed_at: string | null;}interface RawPerson extends Record<string, SqlStorageValue> {  id: string;  phone: string;  name: string | null;  role: string;  created_at: string;  version: number;}/** What an erased row's tombstone holds, and nothing else: why it was erased (Store.tombstone). */export const ERASED_KEY = "$erase";/** The table whose rows carry `landed_at` on the wire: mail, which the cuts of MAIL PREDICATE phase 2 cover. */export const LANDED_TABLE = "email";export function wire(row: StoredRow, withOwner: boolean): WireRow {  const out: WireRow = { table: row.table, id: row.id, data: row.data, version: row.version, created_at: row.created_at, updated_at: row.updated_at };  // A mail says when it landed on the server (rule 3): what a mail cut compares against on the phone.  if (row.table === LANDED_TABLE && row.landed_at) out.landed_at = row.landed_at;  if (withOwner) out.owner = row.owner;  if (row.deleted) out.deleted = true;  return out;}export function wirePerson(p: Person): WirePerson {  return { id: p.id, phone: p.phone, name: p.name, role: p.role, created_at: p.created_at };}