Cotton code
374 lines · 26.2 KB · TypeScriptRaw
/** * OPEN TABLES, PROVEN ON THE DEV WORKER (coordinator for the owner, 24 Nov 2026; assets/design/shared/OPEN-TABLES.md, * src/open_tables_lock.ts, as test/open_tables_lock.test.ts runs it in the pool). On one invented account: *   1. projects, sessions with their prompts, tasks and replies, and passwords are planted open, as an account holds *      them before the lock; the lock is off, and the hook's token reads them as always; *   2. gate 1 refuses while the hook's token holds no grant; the phone's Allow (assistant_allow, its grant signed by *      the person key) makes it ready; *   3. the lock goes on (state handing); the phone hands the tables' keys (assistant_add); state sealing; *   4. the phone's sweep seals every open row with the data key, its blind tokens beside it; state sealed; *   5. the server reads none: the admin's export of every row holds no planted word, and seal-check counts no row *      left open; the owner reads all: the phone syncs every row and opens each with its key to the words planted, *      and the hook's token answers brief, list_sessions (by project, machine and words), get_session and *      list_projects exactly as it did before the lock. * The phone here is this script: its data key, person key and arrival key are made for the run and never leave it. * Invented data only; refuses any server but the dev Worker (or a local wrangler dev). * *   pnpm -s exec tsx scripts/open-tables-proof.ts --number +1555XXXXXXX [--sessions 60] [--turns 10] * * The sign-in code is read from ~/.cotton-credentials/cotton/dev-otp and the admin token (the lock's switch and the * export take it) from ~/.cotton-credentials/cloudflare/business-dev-admin-token; neither is printed. Against a local * wrangler dev (--base http://127.0.0.1:<port>), --code-file and --admin-token-file name that Worker's invented ones. * Since LOCKS_AT_BIRTH is on for the dev Worker (25 Nov 2026), a new account there is born locked and this proof stops at * step 1: start the local Worker with `--var LOCKS_AT_BIRTH:off` (passed 26 Nov 2026 at head, 228 rows, brief 2.4 s sealed). */import { readFileSync } from "node:fs";import { homedir } from "node:os";import { agentStatement, policy } from "../src/agent_statement.ts";import { GRANTED, SEALS, TABLES } from "../src/open_tables_lock.ts";import { blindKey, bodyAad, bucket, dekAad, parseSeal, rowTokens, tableKey } from "../src/seal.ts";import { fromBase64Url, toBase64Url } from "../src/base64.ts";import { signIn } from "./dev-seed/client.ts";import { devBase } from "./dev-server";const arg = (name: string, fallback?: string) => {  const i = process.argv.indexOf(`--${name}`);  return i > 0 ? process.argv[i + 1]! : fallback;};const DEV = arg("base", devBase())!;if (DEV !== devBase() && !/^http:\/\/127\.0\.0\.1:\d+$/.test(DEV)) throw new Error("--base is the dev Worker or a local wrangler dev");const NUMBER = arg("number");if (!NUMBER || !/^\+1555\d{7}$/.test(NUMBER)) throw new Error("--number is an invented +1555 number");const PROJECTS = 13;const SESSIONS = Number(arg("sessions", "60"));const TURNS = Number(arg("turns", "10"));const REPO = "https://git.example.test/invented/garden";const say = (line: string) => console.log(`[open-tables] ${new Date().toISOString().slice(11, 19)} ${line}`);const fail = (what: string): never => {  throw new Error(what);};const utf8 = new TextEncoder();const hex = (h: string): Uint8Array => Uint8Array.from(h.match(/../g)!.map((b) => parseInt(b, 16)));const X25519_PKCS8 = hex("302e020100300506032b656e04220420");const ED25519_PKCS8 = hex("302e020100300506032b657004220420");// ── the phone's keys and seals (as test/open_tables_lock.test.ts, the core's seal::agent and seal::row) ──async function okp(prefix: Uint8Array, secret: Uint8Array, name: "X25519" | "Ed25519", uses: string[]): Promise<{ key: Awaited<ReturnType<typeof crypto.subtle.importKey>>; pub: Uint8Array }> {  const pkcs8 = new Uint8Array(48);  pkcs8.set(prefix);  pkcs8.set(secret, 16);  const key = await crypto.subtle.importKey("pkcs8", pkcs8, { name }, true, uses as Parameters<typeof crypto.subtle.importKey>[4]);  const jwk = (await crypto.subtle.exportKey("jwk", key)) as { x?: string };  return { key, pub: fromBase64Url(jwk.x!) };}async function wrapWith(recipientPub: Uint8Array, plain: Uint8Array): Promise<string> {  const eph = await okp(X25519_PKCS8, crypto.getRandomValues(new Uint8Array(32)), "X25519", ["deriveBits"]);  const nonce = crypto.getRandomValues(new Uint8Array(12));  const peer = await crypto.subtle.importKey("raw", recipientPub, { name: "X25519" }, false, []);  const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: peer } as never, eph.key, 256));  const salt = new Uint8Array(64);  salt.set(eph.pub);  salt.set(recipientPub, 32);  const ikm = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]);  const k = await crypto.subtle.importKey("raw", await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: utf8.encode("cotton-vault-wrap-v1") }, ikm, 256), "AES-GCM", false, ["encrypt"]);  const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: recipientPub }, k, plain));  const out = new Uint8Array(32 + 12 + body.length);  out.set(eph.pub);  out.set(nonce, 32);  out.set(body, 44);  return `w1:${toBase64Url(out)}`;}function canonical(v: unknown): string {  if (v && typeof v === "object" && !Array.isArray(v)) {    const o = v as Record<string, unknown>;    return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`).join(",")}}`;  }  return JSON.stringify(v);}async function bundleOf(dk: Uint8Array, db: string, memberId: string, tables: [string, number][]): Promise<string> {  const keys: Record<string, Record<string, string>> = {};  const blind: Record<string, string> = {};  for (const [t, v] of tables) {    keys[t] = {};    for (let n = 1; n <= v; n++) keys[t]![String(n)] = toBase64Url(await tableKey(dk, db, t, n));    blind[t] = toBase64Url(await blindKey(dk, db, t));  }  return canonical({ request_id: memberId, token_id: memberId, keys, blind });}async function gcm(key: Uint8Array, plain: Uint8Array, aad: string): Promise<string> {  const nonce = crypto.getRandomValues(new Uint8Array(12));  const k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]);  const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: utf8.encode(aad) }, k, plain));  const out = new Uint8Array(12 + body.length);  out.set(nonce);  out.set(body, 12);  return toBase64Url(out);}async function ungcm(key: Uint8Array, sealed: string, aad: string): Promise<Uint8Array> {  const raw = fromBase64Url(sealed);  const k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);  return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: raw.subarray(0, 12), additionalData: utf8.encode(aad) }, k, raw.subarray(12)));}async function sealRow(dk: Uint8Array, db: string, table: string, id: string, inside: Record<string, unknown>): Promise<Record<string, unknown>> {  const text = canonical(inside);  const padded = text + " ".repeat(bucket(utf8.encode(text).length) - utf8.encode(text).length);  const dek = crypto.getRandomValues(new Uint8Array(32));  return {    sealed_enc: `s1:${await gcm(dek, utf8.encode(padded), bodyAad(db, table, id))}`,    dek_enc: `d1:${await gcm(await tableKey(dk, db, table, 1), dek, dekAad(db, table, id, 1))}`,    seal_v: 1,  };}/** A sealed row opened as the phone opens it: its data key's table key opens the row's key, which opens the body. */async function openRow(dk: Uint8Array, db: string, table: string, id: string, data: Record<string, unknown>): Promise<Record<string, unknown>> {  const v = Number(data.seal_v);  const dek = await ungcm(await tableKey(dk, db, table, v), String(data.dek_enc).slice(3), dekAad(db, table, id, v));  const body = JSON.parse(new TextDecoder().decode(await ungcm(dek, String(data.sealed_enc).slice(3), bodyAad(db, table, id))).trimEnd()) as Record<string, unknown>;  const clear = Object.fromEntries(Object.entries(data).filter(([k]) => !["sealed_enc", "dek_enc", "seal_v"].includes(k)));  return { ...clear, ...body };}// ── the dev Worker ─────────────────────────────────────────────────────async function call<T = Record<string, unknown>>(base: string, bearer: string, method: string, path: string, body?: unknown): Promise<{ status: number; body: T }> {  for (let attempt = 0; ; attempt++) {    try {      const res = await fetch(`${base}${path}`, { method, headers: { "content-type": "application/json", authorization: `Bearer ${bearer}` }, body: body === undefined ? undefined : JSON.stringify(body) });      const text = await res.text();      if (res.status >= 500 && attempt < 4) throw new Error(`${res.status} ${text.slice(0, 200)}`);      return { status: res.status, body: (text ? JSON.parse(text) : {}) as T };    } catch (error) {      if (attempt >= 4) throw error;      say(`retry ${method} ${path}: ${error instanceof Error ? error.message : String(error)}`);      await new Promise((done) => setTimeout(done, 3_000 * (attempt + 1)));    }  }}type ToolAnswer = { result?: { content: { text: string }[]; isError?: boolean }; error?: { message: string } };async function main(): Promise<void> {  const code = readFileSync(arg("code-file", `${homedir()}/.cotton-credentials/cotton/dev-otp`)!, "utf8").replace(/\D/g, "");  const admin = readFileSync(arg("admin-token-file", `${homedir()}/.cotton-credentials/cloudflare/business-dev-admin-token`)!, "utf8").trim();  const s = await signIn(DEV, NUMBER!, code);  const db = s.databaseId;  // On the workers.dev host every call names its object by its /b/<slug> address, as scripts/import-personal.ts does.  const base = `${DEV}/b/p-${db}`;  const phone = (method: string, path: string, body?: unknown) => call(base, s.credential, method, path, body);  const asAdmin = <T>(method: string, path: string, body?: unknown) => call<T>(base, admin, method, path, body);  const act = (name: string, args: Record<string, unknown>) => phone("POST", "/v1/act", { act: name, args });  say(`signed in ${NUMBER} (database ${db.slice(0, 8)}…)`);  // The sign-in's own owner token (dev-seed's client mints one) is not this proof's: revoked, so gate 1 names only  // the hook's token, as on an account whose every token is accounted for.  const revoked = await act("revoke_token", { id: s.tokenId });  if (revoked.status !== 200) fail(`revoke the sign-in's token: ${revoked.status} ${JSON.stringify(revoked.body).slice(0, 200)}`);  // The phone's keys, made for this run: the data key, the person key it signs grants with, its arrival key.  const dk = crypto.getRandomValues(new Uint8Array(32));  const person = await okp(ED25519_PKCS8, crypto.getRandomValues(new Uint8Array(32)), "Ed25519", ["sign"]);  const personPub = toBase64Url(person.pub);  const arrival = await okp(X25519_PKCS8, crypto.getRandomValues(new Uint8Array(32)), "X25519", ["deriveBits"]);  for (const [table, id, data] of [    ["person_key", personPub.slice(0, 8), { public_key: personPub, sealed_private_enc: "v2:stand-in", vmk_version: 1 }],    ["seal_key", "arrival", { pub: toBase64Url(arrival.pub) }],  ] as [string, string, Record<string, unknown>][]) {    const r = await act("create", { table, id, data });    if (r.status !== 200 && r.status !== 409) fail(`${table}: ${r.status} ${JSON.stringify(r.body).slice(0, 300)}`);  }  const hook = String(((await act("mint_token", { name: "invented-mac hook", scopes: ["owner"], expires_in_days: 1, allow: "all" })).body as { token?: string }).token ?? fail("no hook token"));  const tool = async (token: string, name: string, args: Record<string, unknown> = {}): Promise<string> => {    const r = await call<ToolAnswer>(DEV, token, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });    const text = r.body.result?.content?.[0]?.text;    if (r.status !== 200 || r.body.result?.isError || text === undefined) fail(`${name}: ${r.status} ${JSON.stringify(r.body).slice(0, 300)}`);    return text!;  };  // 1. Planted open, as the account holds them before the lock.  const pad = (n: number) => String(n).padStart(12, "0");  const uuid = (kind: number, i: number) => `00000000-0000-4000-8${kind}00-${pad(i)}`;  const baseAt = Math.floor(Date.now() / 60_000) * 60_000 - 3 * 86_400_000;  const at = (i: number) => new Date(baseAt + i * 60_000).toISOString();  const words = (n: number, t: number) => (n === 7 && t === 3 ? "the otters hold hands while they sleep, so they do not drift apart" : `invented turn ${t} of session ${n} about ${n % 2 ? "tulips" : "ferns"}`);  const rows: Record<string, unknown>[] = [];  for (let p = 0; p < PROJECTS; p++) rows.push({ verb: "put", table: "project", id: uuid(1, p), data: { slug: `invented-project-${p}`, name: `Invented project ${p}`, repos: p === 0 ? [REPO] : [], status: "active" } });  for (let n = 0; n < SESSIONS; n++) {    rows.push({ verb: "put", table: "session", id: uuid(2, n), data: { tool: "claude-code", external_id: `invented-session-${n}`, machine: n % 3 ? "invented-mac" : "invented-mini", project: uuid(1, n % PROJECTS), repo_url: REPO, branch: "main", cwd: "/invented/garden", title: `Invented session ${n}`, summary: `Invented summary ${n}`, started_at: at(n * 20), last_active_at: at(n * 20 + 10), turn_count: TURNS, prompt_count: TURNS, state: "done" } });    for (let t = 0; t < TURNS; t++) rows.push({ verb: "put", table: "prompt", id: uuid(3, n * 100 + t), data: { session: uuid(2, n), project: uuid(1, n % PROJECTS), seq: t, ts: at(n * 20 + t), role: t % 2 ? "assistant" : "user", text: words(n, t) } });    rows.push({ verb: "put", table: "session_task", id: uuid(4, n), data: { session: uuid(2, n), seq: 0, text: `Invented task of session ${n}`, state: n % 2 ? "done" : "open" } });    if (n % 10 === 0) rows.push({ verb: "put", table: "session_message", id: uuid(5, n), data: { to_kind: "session", to_session: uuid(2, n), from_kind: "owner", kind: "answer", status: "delivered", body: `Invented reply to session ${n}` } });  }  rows.push({ verb: "put", table: "secret", id: uuid(6, 1), data: { name: "Invented Garden Club", kind: "login", site: "garden.example.test", username: "mira.invented", value_enc: "v2:invented-device-sealed-value", vmk_version: 1 } });  rows.push({ verb: "put", table: "secret", id: uuid(6, 2), data: { name: "Invented Kiln Shop", kind: "login", site: "kiln.example.test", username: "mira.kiln", value_enc: "v2:invented-device-sealed-value-2", vmk_version: 1 } });  for (let i = 0; i < rows.length; i += 200) {    const r = await asAdmin("POST", "/v1/admin/import", { rows: rows.slice(i, i + 200) });    if (r.status !== 200) fail(`import: ${r.status} ${JSON.stringify(r.body).slice(0, 300)}`);  }  await tool(hook, "create_secret", { name: "Invented weather key", kind: "api_key", service: "invented-weather", value: "invented-key-0000-1111" });  /** Every word planted, which the server must never hold once the lock is sealed. */  const PLANTED = ["otters hold hands", "Invented session 7", "Invented summary", "invented-mini", "Invented project 2", "invented-project-2", "/invented/garden", "Invented task", "Invented reply", "Invented Garden Club", "garden.example.test", "mira.invented", "Invented weather key"];  say(`planted ${rows.length} rows open`);  type Lock = { state: string; ready: boolean; readers: { name: string; verdict: string }[]; open_rows: Record<string, number>; sealed_rows: Record<string, number> };  const lock = async () => (await asAdmin<Lock>("GET", "/v1/admin/open-tables-lock")).body;  const answers = async (): Promise<Record<string, string>> => ({    // The briefing's text, as test/open_tables_lock.test.ts compares it (the answer's other fields carry the moment).    brief: String((JSON.parse(await tool(hook, "brief", { repoUrl: REPO, machine: "invented-mac" })) as { briefing?: unknown }).briefing),    list: await tool(hook, "list_sessions", { limit: 50 }),    project: await tool(hook, "list_sessions", { project: "invented-project-2", limit: 50 }),    machine: await tool(hook, "list_sessions", { machine: "invented-mini", limit: 50 }),    search: await tool(hook, "list_sessions", { q: "otters hold", limit: 10 }),    get: await tool(hook, "get_session", { sessionId: uuid(2, 7) }),    projects: await tool(hook, "list_projects", {}),  });  /**   * The slowest of five calls of each kind through the hook's token, in seconds: the hook waits 3 s for a brief, and   * the switch on his account waits for this measure on dev (OPEN-TABLES.md, As built, step 6).   */  const timed = async (): Promise<Record<string, number>> => {    const calls: Record<string, () => Promise<unknown>> = {      brief: () => tool(hook, "brief", { repoUrl: REPO, machine: "invented-mac" }),      list_sessions: () => tool(hook, "list_sessions", { limit: 50 }),      by_machine: () => tool(hook, "list_sessions", { machine: "invented-mini", limit: 50 }),      search: () => tool(hook, "list_sessions", { q: "otters hold", limit: 10 }),      get_session: () => tool(hook, "get_session", { sessionId: uuid(2, 7) }),    };    const out: Record<string, number> = {};    for (const [name, call] of Object.entries(calls)) {      let slowest = 0;      for (let i = 0; i < 5; i++) {        const t0 = performance.now();        await call();        slowest = Math.max(slowest, performance.now() - t0);      }      out[name] = Math.round(slowest / 100) / 10;    }    return out;  };  const off = await lock();  // A database born with its locks on (LOCKS_AT_BIRTH, the dev Worker since 25 Nov 2026) has no "before" to prove from:  // run this against a local wrangler dev started with --var LOCKS_AT_BIRTH:off, as the owner's account was born.  if (off.state !== "off") fail(`the lock is ${off.state} before it was turned on${off.state === "sealing" || off.state === "sealed" ? ": this database was born locked (LOCKS_AT_BIRTH on); run against a local wrangler dev --env dev --var LOCKS_AT_BIRTH:off" : ""}`);  const before = await answers();  if (!before.search!.includes("otters hold hands")) fail("the hook's token does not find the planted words before the lock");  say(`off: ${JSON.stringify(off.open_rows)} open; the hook's token reads them`);  const openTimes = await timed();  say(`timing, open (slowest of 5, s): ${JSON.stringify(openTimes)}`);  // 2. Gate 1: the hook's token holds no grant; its card waits on the phone, and the phone's Allow signs one.  const refused = await asAdmin<{ code?: string }>("POST", "/v1/admin/open-tables-lock", { on: true });  if (refused.status !== 409 || refused.body.code !== "open_tables_lock_not_ready") fail(`gate 1 let the lock on with no grant: ${refused.status} ${JSON.stringify(refused.body).slice(0, 200)}`);  const synced = async (table: string) => {    const out: { id: string; data: Record<string, unknown>; deleted?: boolean }[] = [];    let path = `/v1/sync?since=0&tables=${table}&limit=5000`;    for (;;) {      const r = await phone("GET", path);      const page = r.body as { rows: { table: string; id: string; data: Record<string, unknown>; deleted?: boolean }[]; next?: string };      out.push(...page.rows.filter((x) => x.table === table && !x.deleted));      if (!page.next) return out;      path = `/v1/sync?cursor=${encodeURIComponent(page.next)}`;    }  };  const card = (await synced("unlock_request")).find((r) => r.data.state === "waiting") ?? fail("no card waits on the phone");  const withheld = policy([]);  const wrapped = await wrapWith(fromBase64Url(String(card.data.member_pub)), utf8.encode(await bundleOf(dk, db, String(card.data.member_id), [["note", 1]])));  const statement = await agentStatement(db, String(card.data.member_id), String(card.data.member_pub), withheld, wrapped);  const sig = toBase64Url(new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, person.key, utf8.encode(statement))));  const allowed = await act("assistant_allow", { request_id: card.id, tables: ["note"], withheld, wrapped, signer: personPub.slice(0, 8), sig });  if (allowed.status !== 200) fail(`allow: ${allowed.status} ${JSON.stringify(allowed.body).slice(0, 300)}`);  const gate = await lock();  if (!gate.ready) fail(`gate 1 not ready after the Allow: ${JSON.stringify(gate.readers.filter((r) => r.verdict !== "ready"))}`);  say("gate 1: refused with no grant; ready after the phone's Allow");  // 3. On, then the phone hands the tables' keys (every locked table but the passwords, which no grant carries).  const on = await asAdmin<{ state: string }>("POST", "/v1/admin/open-tables-lock", { on: true });  if (on.status !== 200 || on.body.state !== "handing") fail(`on: ${on.status} ${JSON.stringify(on.body).slice(0, 200)}`);  const grant = (await synced("unlock_grant")).find((r) => r.data.account === 1 || r.data.account === true) ?? fail("no standing grant to hand the keys to");  const memberPub = String(grant.data.member_pub ?? card.data.member_pub);  const add = await wrapWith(fromBase64Url(memberPub), utf8.encode(await bundleOf(dk, db, String(grant.data.member_id), GRANTED.map((t) => [t, 1]))));  const handed = await act("assistant_add", { grant_id: grant.id, tables: [...GRANTED], wrapped: add });  if (handed.status !== 200) fail(`assistant_add: ${handed.status} ${JSON.stringify(handed.body).slice(0, 300)}`);  say(`on: ${on.body.state}; keys handed; now ${(await lock()).state}`);  // 4. The phone's sweep: every open row of the locked tables sealed with the data key, its blind tokens beside it.  const defs = (await phone("GET", "/v1/definitions")).body as { tables: Record<string, unknown>[] };  let sealed = 0;  const refusedSeals: Record<string, number> = {};  for (const table of TABLES) {    const seal = SEALS[table]!;    const raw = { ...(defs.tables.find((t) => t.id === table) ?? fail(`no definition of ${table}`)), seal };    const spec = parseSeal(raw)!;    const bk = await blindKey(dk, db, table);    for (const r of await synced(table)) {      if (r.data.sealed_enc) continue;      const version = Number((r as unknown as { version: number }).version);      const inside: Record<string, unknown> = {};      const clear: Record<string, unknown> = {};      for (const [k, v] of Object.entries(r.data)) (seal.clear.includes(k) ? clear : inside)[k] = v;      const blind = await rowTokens(bk, raw, spec, r.data);      const res = await act("seal", { table, id: r.id, expect_version: version, data: { ...clear, ...(await sealRow(dk, db, table, r.id, inside)) }, blind });      if (res.status === 200) sealed++;      else refusedSeals[String((res.body as { code?: string }).code)] = (refusedSeals[String((res.body as { code?: string }).code)] ?? 0) + 1;    }  }  const after = await lock();  say(`sweep: ${sealed} rows sealed, refused ${JSON.stringify(refusedSeals)}; lock ${after.state}, open ${JSON.stringify(after.open_rows)}`);  if (after.state !== "sealed") fail(`the lock is ${after.state} after the sweep, not sealed`);  // 5a. The server reads none: no planted word in any row the object keeps, and seal-check finds none open.  let held = "";  for (let afterKey: string | null = null; ; ) {    const page: { rows: { table: string; data: unknown }[]; next: string | null } = (await asAdmin<{ rows: { table: string; data: unknown }[]; next: string | null }>("GET", `/v1/admin/export?limit=5000${afterKey ? `&after=${encodeURIComponent(afterKey)}` : ""}`)).body;    held += JSON.stringify(page.rows.filter((r) => (TABLES as readonly string[]).includes(r.table)));    if (!page.next) break;    afterKey = page.next;  }  const inClear = PLANTED.filter((w) => held.includes(w));  // The act log too: an earlier act's args that still hold a sealed column (acts_plain) are words the server keeps  // until seal_purge (the Mac's seal-migrate sends it; the phone's sweep does not), and staged twins left uncommitted.  const check = (await asAdmin<{ tables: { table: string; open?: number; acts_plain?: number; twins?: number }[] }>("GET", "/v1/admin/seal-check")).body;  const leftOpen = check.tables.filter((t) => (TABLES as readonly string[]).includes(t.table) && ((t.open ?? 0) > 0 || (t.acts_plain ?? 0) > 0 || (t.twins ?? 0) > 0));  say(`server: ${inClear.length ? `HOLDS ${inClear.join(", ")}` : "holds none of the planted words"}; seal-check ${leftOpen.length ? JSON.stringify(leftOpen) : "0 open, 0 in the act log, 0 twins in every locked table"}`);  if (inClear.length || leftOpen.length) fail("the server still reads planted words");  // 5b. The owner reads all: the phone opens every row to what was planted; the hook's token answers as before.  const plantedBy = new Map(rows.map((r) => [`${r.table}/${r.id}`, r.data as Record<string, unknown>]));  let opened = 0;  const differs: string[] = [];  for (const table of TABLES) {    for (const r of await synced(table)) {      const want = plantedBy.get(`${table}/${r.id}`);      if (!want) continue;      const got = await openRow(dk, db, table, r.id, r.data);      for (const [k, v] of Object.entries(want)) if (JSON.stringify(got[k]) !== JSON.stringify(v)) differs.push(`${table}/${r.id}.${k}`);      opened++;    }  }  const now = await answers();  const sealedTimes = await timed();  say(`timing, sealed (slowest of 5, s): ${JSON.stringify(sealedTimes)}; brief ${sealedTimes.brief! <= 3 ? "within" : "PAST"} the hook's 3 s`);  const changed = Object.keys(before).filter((k) => before[k] !== now[k]);  say(`owner: the phone opened ${opened} of ${plantedBy.size} planted rows to their words${differs.length ? `, ${differs.length} differ (${differs.slice(0, 5).join(", ")})` : ", every one as planted"}; the hook's token answers ${changed.length ? `differently in ${changed.join(", ")}` : "brief, list_sessions, get_session and list_projects exactly as before"}`);  for (const k of changed) {    const [a, b] = [before[k]!, now[k]!];    let i = 0;    while (i < a.length && a[i] === b[i]) i++;    say(`  ${k} differs at ${i}: before ${JSON.stringify(a.slice(Math.max(0, i - 80), i + 120))} after ${JSON.stringify(b.slice(Math.max(0, i - 80), i + 120))}`);  }  if (differs.length || changed.length || opened < plantedBy.size - 2) fail("the owner does not read all");  say("OPEN TABLES proven: the server reads none, the owner reads all");}main().catch((error) => {  console.error(`[open-tables] ${error instanceof Error ? error.message : String(error)}`);  process.exit(1);});