Cotton code
386 lines · 30.0 KB · TypeScriptRaw
/** * OPEN TABLES LOCK AT THE OWNER'S SIZE (a copy of open_tables_lock.test.ts with the owner's counts, each call through a * token timed, and the sweep in a phone's batches of seal_stage and seal_commit). `BIG_OBJECT=1 npx vitest run * open_tables_lock_owner_size --disableConsoleIntercept` prints the times (OWNER SIZE lines). * OPEN TABLES LOCK (owner via the coordinator, 24 Nov 2026; assets/design/shared/OPEN-TABLES.md §2, * src/open_tables_lock.ts). The memory lock widened to the session tables and projects, on one invented account: * off by default; gate 1 refusing a token with no grant and filing its card; the owner's Allow; on, gate 2 holding every * seal until the phone hands the tables' keys; the sweep; and then the same brief, list_sessions (with search and a * machine), get_session and log_session through the hook's token and a lane minted from it, with no word of any * session in the clear on the object. An ungranted token is answered window_needed. Every key and row is invented. */import { env, runInDurableObject } from "cloudflare:test";import { beforeAll, describe, expect, it } from "vitest";import vector from "../../../crates/cotton-conformance/vectors/seal/agent_grant.json";import { agentStatement, policy } from "../src/agent.ts";import { GRANTED, SEALS, TABLES } from "../src/open_tables_lock.ts";import { arrivalPub } from "./arrival_keys.ts";import { BIG } from "./big_object.ts";import { blindKey, bodyAad, bucket, dekAad, parseSeal, rowTokens, tableKey } from "../src/seal.ts";import { tableFileRoot } from "../src/table_files.ts";import { fromBase64Url, toBase64Url } from "../src/vault.ts";import { ADMIN, DATABASE_ID, http, mint, OWNER_PHONE, PERSONAL_TABLES, PERSONAL_TOOLS, publishPersonKey, put, tool, type ToolResult } from "./personal.ts";import { holdsWord } from "./clear-word.ts";const utf8 = new TextEncoder();const hex = (h: string): Uint8Array => Uint8Array.from(h.match(/../g)!.map((b) => parseInt(b, 16)));const PERSON_SEED = new Uint8Array(32).fill(7);const X25519_PKCS8 = hex("302e020100300506032b656e04220420");const ED25519_PKCS8 = hex("302e020100300506032b657004220420");async function okp(prefix: Uint8Array, secret: Uint8Array, name: "X25519" | "Ed25519", uses: string[]): Promise<{ key: CryptoKey; 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 JsonWebKey;  return { key, pub: fromBase64Url(jwk.x!) };}async function wrapWith(ephemeral: Uint8Array, nonce: Uint8Array, recipientPub: Uint8Array, plain: Uint8Array): Promise<string> {  const eph = await okp(X25519_PKCS8, ephemeral, "X25519", ["deriveBits"]);  const peer = await crypto.subtle.importKey("raw", recipientPub, { name: "X25519" }, false, []);  const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: peer } as unknown as SubtleCryptoDeriveKeyAlgorithm, 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);}/** The keys of `tables` (every version up to each one's), as the bundle names them for a member. */async function bundleOf(dk: Uint8Array, 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, DATABASE_ID, t, n));    blind[t] = toBase64Url(await blindKey(dk, DATABASE_ID, t));  }  // grant.rs: a bundle naming message carries the message table's files root (a kept chat picture opens with it).  const files = keys.message ? { files: { message: toBase64Url(await tableFileRoot(dk, DATABASE_ID, "message")) } } : {};  return canonical({ request_id: memberId, token_id: memberId, keys, blind, ...files });}/** `seal::agent::build_agent_grant`: wrapped to the member key, the policy signed. */async function agentGrant(o: { dk: Uint8Array; memberId: string; memberPub: string; tables: [string, number][]; withheld?: string[]; seed?: Uint8Array; ephemeral?: Uint8Array; nonce?: Uint8Array }): Promise<{ tables: string[]; withheld: string[]; wrapped: string; signer: string; sig: string }> {  const withheld = policy(o.withheld ?? []);  const wrapped = await wrapWith(o.ephemeral ?? crypto.getRandomValues(new Uint8Array(32)), o.nonce ?? crypto.getRandomValues(new Uint8Array(12)), fromBase64Url(o.memberPub), utf8.encode(await bundleOf(o.dk, o.memberId, o.tables)));  const person = await okp(ED25519_PKCS8, o.seed ?? PERSON_SEED, "Ed25519", ["sign"]);  const statement = await agentStatement(DATABASE_ID, o.memberId, o.memberPub, withheld, wrapped);  const sig = toBase64Url(new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, person.key, utf8.encode(statement))));  return { tables: o.tables.map(([t]) => t).sort(), withheld, wrapped, signer: toBase64Url(person.pub).slice(0, 8), sig };}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 sealRow(dk: Uint8Array, id: string, v: number, sealed: Record<string, unknown>, table = "memory"): Promise<Record<string, unknown>> {  const text = canonical(sealed);  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(DATABASE_ID, table, id))}`,    dek_enc: `d1:${await gcm(await tableKey(dk, DATABASE_ID, table, v), dek, dekAad(DATABASE_ID, table, id, v))}`,    seal_v: v,  };}const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));async function act(slug: string, credential: string, name: string, args: Record<string, unknown>): Promise<{ status: number; body: Record<string, unknown> }> {  return http(slug, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${credential}` });}function parsed(r: ToolResult): Record<string, unknown> {  expect(r.isError, r.content[0]?.text).toBe(false);  return JSON.parse(r.content[0]!.text) as Record<string, unknown>;}// ── the invented account ──────────────────────────────────────────────const PROJECTS = 13;// The owner's size (24 Nov 2026: 13 projects, 3,257 sessions, 45,801 prompts, 905 tasks, 3,390 messages).const SESSIONS = 3257;const TURNS = 14;const REPO = "https://git.example.test/invented/garden";const pad = (n: number) => String(n).padStart(12, "0");const uuid = (kind: number, i: number) => `00000000-0000-4000-8${kind}00-${pad(i)}`;const projectSlug = (p: number) => `invented-project-${p}`;/** Within the last days: the object keeps prompts 30 days (erase.ts keepPrompts), and these must stay. */const BASE = Math.floor(Date.now() / 60_000) * 60_000 - 3 * 86_400_000;// Ten seconds a step, so every prompt of 3,257 sessions falls inside the object's 30 days of prompts.const at = (i: number) => new Date(BASE + i * 10_000).toISOString();async function lockOf(slug: string, excuse?: string[]) {  return http<{ lock: unknown; ready: boolean; state: string; readers: { token_id: string; name: string; verdict: string; says: string }[]; open_rows: Record<string, number>; sealed_rows: Record<string, number> }>(slug, "GET", `/v1/admin/open-tables-lock${excuse ? `?excuse=${excuse.join(",")}` : ""}`, undefined, ADMIN);}/** The phone's sweep over the locked tables: each open row sealed with the data key, its blind tokens beside it. */async function sweep(slug: string, credential: string, dk: Uint8Array, tables: readonly string[] = TABLES, most = Infinity): Promise<{ sealed: number; refused: Record<string, number> }> {  const refused: Record<string, number> = {};  let sealed = 0;  for (const table of tables) {    const seal = SEALS[table]!;    const raw = { ...PERSONAL_TABLES.find((t) => t.id === table)!, seal };    const spec = parseSeal(raw as Record<string, unknown>)!;    const bk = await blindKey(dk, DATABASE_ID, table);    const rows = (await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string; version: number; data: string }>("SELECT id, version, data FROM rows WHERE table_id = ? AND deleted = 0 AND json_extract(data, '$.sealed_enc') IS NULL", table).toArray())).slice(0, most);    // As a phone sweeps (seal_stage, then seal_commit), 500 rows a batch: the twins staged, then put in place.    // At most 500 rows and 2,000 blind tokens a call (BLIND_PER_CALL), as the phone cuts it.    for (let i = 0; i < rows.length; ) {      const batch = [];      let tokens = 0;      for (; i < rows.length && batch.length < 500; i++) {        const r = rows[i]!;        const d = JSON.parse(r.data) as Record<string, unknown>;        const inside: Record<string, unknown> = {};        const clear: Record<string, unknown> = {};        for (const [k, v] of Object.entries(d)) (seal.clear.includes(k) ? clear : inside)[k] = v;        const blind = await rowTokens(bk, raw as Record<string, unknown>, spec, d);        const n = blind.length;        if (batch.length && tokens + n > 2000) break;        tokens += n;        batch.push({ id: r.id, expect_version: r.version, data: { ...clear, ...(await sealRow(dk, r.id, 1, inside, table)) }, blind });      }      const staged = await act(slug, credential, "seal_stage", { table, rows: batch });      if (staged.status !== 200) {        refused[String(staged.body.code)] = (refused[String(staged.body.code)] ?? 0) + batch.length;        continue;      }      const reply = (staged.body.reply ?? staged.body) as { staged: { id: string; twin: string }[]; left: { code: string }[] };      for (const l of reply.left) refused[l.code] = (refused[l.code] ?? 0) + 1;      const committed = await act(slug, credential, "seal_commit", { table, twins: reply.staged.map((x) => x.twin) });      const done = (committed.body.reply ?? committed.body) as { sealed?: string[]; left?: { code: string }[] };      sealed += done.sealed?.length ?? 0;      for (const l of done.left ?? []) refused[l.code] = (refused[l.code] ?? 0) + 1;      if (committed.status !== 200) refused[String(committed.body.code)] = (refused[String(committed.body.code)] ?? 0) + reply.staged.length;    }  }  return { sealed, refused };}const words = (s: number, t: number) => (s === 7 && t === 3 ? "the otters hold hands while they sleep, so they do not drift apart" : `invented turn ${t} of session ${s} about ${s % 2 ? "tulips" : "ferns"}`);// Only at full size (`BIG_OBJECT=1`, about 45 minutes on the Linux box): open_tables_lock.test.ts is the same proof, small.describe.skipIf(!BIG)("the open tables lock on an invented account of the owner's size", () => {  const slug = "open-tables-lock-owner-size";  // Each tool call through a token, timed: the hook gives a call 3 seconds.  const slowest: Record<string, number> = {};  const timed = async <T,>(what: string, call: () => Promise<T>): Promise<T> => {    const started = Date.now();    const out = await call();    slowest[what] = Math.max(slowest[what] ?? 0, Date.now() - started);    return out;  };  const dk = crypto.getRandomValues(new Uint8Array(32));  let credential = "";  let hook = "";  let before: Record<string, string> = {};  const answers = async (token: string): Promise<Record<string, string>> => ({    brief: String(parsed(await timed("brief", () => tool(slug, token, "brief", { repoUrl: REPO, machine: "invented-mac" }))).briefing),    list: JSON.stringify(parsed(await timed("list", () => tool(slug, token, "list_sessions", { limit: 50 })))),    project: JSON.stringify(parsed(await timed("project", () => tool(slug, token, "list_sessions", { project: projectSlug(2), limit: 50 })))),    machine: JSON.stringify(parsed(await timed("machine", () => tool(slug, token, "list_sessions", { machine: "invented-mini", limit: 50 })))),    search: JSON.stringify(parsed(await timed("search", () => tool(slug, token, "list_sessions", { q: "otters hold", limit: 10 })))),    get: JSON.stringify(parsed(await timed("get", () => tool(slug, token, "get_session", { sessionId: uuid(2, 7) })))),    projects: JSON.stringify(parsed(await timed("projects", () => tool(slug, token, "list_projects", {})))),  });  const secrets = async (): Promise<string> => JSON.stringify(parsed(await tool(slug, hook, "list_secrets", {})));  beforeAll(async () => {    expect((await http(slug, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: OWNER_PHONE, database_id: DATABASE_ID, timezone: "Asia/Kolkata" }, ADMIN)).status).toBe(200);    const defs = await http(slug, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables: PERSONAL_TABLES, flavour: { flavour: "personal" } }, ADMIN);    expect(defs.status, JSON.stringify(defs.body)).toBe(200);    for (const t of TABLES) expect(PERSONAL_TABLES.find((x) => x.id === t)!.seal, `${t} is open in the kit`).toBeUndefined();    const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: "phone" });    const signed = await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "phone" });    credential = signed.body.credential;    await publishPersonKey(slug, credential, vector.person_public_key);    // The phone hands its arrival key at sign-in: what the object seals its own writes to.    const handed = await http(slug, "POST", "/v1/act", { act: "create", args: { table: "seal_key", id: "arrival", data: { pub: await arrivalPub() } } }, { authorization: `Bearer ${credential}` });    expect(handed.status, JSON.stringify(handed.body)).toBe(200);    await runInDurableObject(stub(slug), (instance) => (instance as unknown as { store: { setMeta(k: string, v: string): void } }).store.setMeta("agent_grant", "on"));    hook = await mint(slug, credential, "invented-mac hook", ["owner"]);    const rows: Record<string, unknown>[] = [];    for (let p = 0; p < PROJECTS; p++) rows.push({ verb: "put", table: "project", id: uuid(1, p), data: { slug: projectSlug(p), name: `Invented project ${p}`, repos: p === 0 ? [REPO] : [], status: "active" } });    for (let s = 0; s < SESSIONS; s++) {      rows.push({ verb: "put", table: "session", id: uuid(2, s), data: { tool: "claude-code", external_id: `invented-session-${s}`, machine: s % 3 ? "invented-mac" : "invented-mini", project: uuid(1, s % PROJECTS), repo_url: REPO, branch: "main", cwd: "/invented/garden", title: `Invented session ${s}`, summary: `Invented summary ${s}`, started_at: at(s * 20), last_active_at: at(s * 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, s * 100 + t), data: { session: uuid(2, s), project: uuid(1, s % PROJECTS), seq: t, ts: at(s * 20 + t), role: t % 2 ? "assistant" : "user", text: words(s, t) } });      if (s % 18 < 5) rows.push({ verb: "put", table: "session_task", id: uuid(4, s), data: { session: uuid(2, s), seq: 0, text: `Invented task of session ${s}`, state: s % 2 ? "done" : "open" } });      rows.push({ verb: "put", table: "session_message", id: uuid(5, s), data: { to_kind: "session", to_session: uuid(2, s), from_kind: "owner", kind: "answer", status: "delivered", body: `Invented reply to session ${s}` } });    }    for (let i = 0; i < rows.length; i += 200) await put(slug, rows.slice(i, i + 200));    // Two invented passwords as a phone saves them, and an API key saved over MCP (its value under the Worker's key).    await put(slug, [      { 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 } },      { 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 } },    ]);    expect(parsed(await tool(slug, hook, "create_secret", { name: "Invented weather key", kind: "api_key", service: "invented-weather", value: "invented-key-0000-1111" })).hint).toBe("1111");  }, 3_000_000);  it("is off by default: every tool answers as it always has, and devices read the tables open", async () => {    const r = await lockOf(slug);    expect(r.status, JSON.stringify(r.body)).toBe(200);    expect(r.body).toMatchObject({ lock: null, state: "off" });    expect(r.body.open_rows).toMatchObject({ project: PROJECTS, session: SESSIONS, prompt: SESSIONS * TURNS });    before = await answers(hook);    console.log(`OWNER SIZE open, before the lock (ms): ${JSON.stringify(slowest)}`);    for (const k of Object.keys(slowest)) delete slowest[k];    expect(before.search).toContain("otters hold hands");    expect(before.machine).toContain("invented-mini");    const served = await http<{ tables: { id: string; seal?: unknown }[] }>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` });    for (const t of TABLES) expect(served.body.tables.find((x) => x.id === t)!.seal, t).toBeUndefined();    const listed = await secrets();    for (const w of ["Invented Garden Club", "garden.example.test", "mira.invented", "Invented weather key"]) expect(listed, w).toContain(w);    // The passwords saved over MCP stay where they are until the lock is on.    expect((await http(slug, "GET", "/v1/secret/rewrap", undefined, { authorization: `Bearer ${credential}` })).body).toEqual({ rows: [], unopened: 0, left: 0 });  }, 3_000_000);  it("gate 1 refuses while the hook's token holds no grant and files its card; the owner's Allow makes it ready", async () => {    const gate = await lockOf(slug);    expect(gate.body.readers.find((r) => r.name === "invented-mac hook")).toMatchObject({ verdict: "needs_allow" });    const on = await http(slug, "POST", "/v1/admin/open-tables-lock", { on: true }, ADMIN);    expect(on.status).toBe(409);    expect(on.body.code).toBe("open_tables_lock_not_ready");    expect(String(on.body.message ?? on.body.error)).toContain("Its card is on the owner's phone to Allow");    const card = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string; data: string }>("SELECT id, data FROM rows WHERE table_id = 'unlock_request' AND json_extract(data, '$.state') = 'waiting'").one());    const d = JSON.parse(card.data) as Record<string, string>;    const g = await agentGrant({ dk, memberId: d.member_id!, memberPub: d.member_pub!, tables: [["note", 1]] });    const allowed = await act(slug, credential, "assistant_allow", { request_id: card.id, ...g });    expect(allowed.status, JSON.stringify(allowed.body)).toBe(200);    expect((await lockOf(slug)).body.readers.find((r) => r.name === "invented-mac hook")!.verdict).toBe("ready");    expect((await lockOf(slug)).body.ready).toBe(true);  }, 3_000_000);  it("on: devices read the tables sealed; the object keeps them open and refuses every seal until the keys are handed", async () => {    const on = await http<{ state: string }>(slug, "POST", "/v1/admin/open-tables-lock", { on: true }, ADMIN);    expect(on.status, JSON.stringify(on.body)).toBe(200);    expect(on.body.state).toBe("handing");    const served = await http<{ tables: { id: string; seal?: { clear: string[] } }[] }>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` });    for (const t of TABLES) expect(served.body.tables.find((x) => x.id === t)!.seal!.clear, t).toEqual(SEALS[t]!.clear);    expect(await sweep(slug, credential, dk, ["session"], 5)).toEqual({ sealed: 0, refused: { grant_not_handed: 5 } });    expect(await answers(hook)).toEqual(before);  }, 3_000_000);  it("the phone hands the keys, the sweep seals every row, and every tool answers the same with no word in the clear", async () => {    const grant = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string; data: string }>("SELECT id, data FROM rows WHERE table_id = 'unlock_grant' AND json_extract(data, '$.account') = 1").one());    const memberId = String((JSON.parse(grant.data) as Record<string, unknown>).member_id);    const pub = String((JSON.parse(grant.data) as Record<string, unknown>).member_pub ?? "") || (await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ pub: string }>("SELECT pub FROM agent_member WHERE id = ?", memberId).one().pub));    // The phone hands every locked table but the passwords, which no grant ever carries.    const add = await wrapWith(crypto.getRandomValues(new Uint8Array(32)), crypto.getRandomValues(new Uint8Array(12)), fromBase64Url(pub), utf8.encode(await bundleOf(dk, memberId, GRANTED.map((t) => [t, 1]))));    expect((await act(slug, credential, "assistant_add", { grant_id: grant.id, tables: [...GRANTED], wrapped: add })).status).toBe(200);    expect((await lockOf(slug)).body.state).toBe("sealing");    expect((await http(slug, "POST", "/v1/admin/open-tables-lock", { on: false }, ADMIN)).body.code).toBe("open_tables_lock_sealing");    const sweptFrom = Date.now();    const swept = await sweep(slug, credential, dk);    console.log(`OWNER SIZE sweep: ${JSON.stringify(swept)} in ${Math.round((Date.now() - sweptFrom) / 1000)} s`);    expect(swept.refused).toEqual({});    const left = await lockOf(slug);    for (const t of TABLES) expect(left.body.open_rows[t], t).toBe(0);    expect(left.body.state).toBe("sealed");    const all = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify(state.storage.sql.exec(`SELECT data FROM rows WHERE table_id IN (${TABLES.map(() => "?").join(",")})`, ...TABLES).toArray()));    for (const w of ["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"]) expect(holdsWord(all, w), w).toBe(false);    // The passwords list says what stays clear, and no name; the key saved over MCP is still found by its service.    const listed = JSON.parse(await secrets()) as { secrets: Record<string, unknown>[] };    expect(listed.secrets).toHaveLength(3);    for (const one of listed.secrets) for (const k of ["name", "site", "username", "hint"]) expect(one[k], k).toBeUndefined();    expect(listed.secrets.every((one) => one.isSet === true)).toBe(true);    const found = parsed(await tool(slug, hook, "list_secrets", { q: "invented-weather" })) as { secrets: { service: string }[] };    expect(found.secrets.map((x) => x.service)).toEqual(["invented-weather"]);    const lane = await mint(slug, hook, "lane invented", ["read", "lane:invented"], 7);    for (const token of [hook, lane]) {      const started = Date.now();      const now = await answers(token);      console.log(`open tables lock: every answer over ${SESSIONS} sealed sessions in ${Date.now() - started} ms`);      expect(now).toEqual(before);      console.log(`OWNER SIZE slowest call through a token after the sweep (ms): ${JSON.stringify(slowest)}`);      // Measured, not asserted here: this box's load sets the times (the report compares them with the open ones).    }  }, 4_800_000);  it("log_session writes sealed through the hook, and reads back the same", async () => {    const logged = parsed(await timed("log_session", () => tool(slug, hook, "log_session", { tool: "claude-code", externalId: "invented-session-7", machine: "invented-mac", lastActiveAt: at(5000), title: "Invented herons at dawn", prompts: [{ seq: TURNS, ts: at(5000), role: "user", text: "herons stand still to fish" }], tasks: [{ seq: 0, text: "Invented: watch the herons", state: "open" }] })));    expect(logged).toMatchObject({ sessionId: uuid(2, 7), inserted: 1 });    console.log(`OWNER SIZE log_session (ms): ${slowest.log_session}`);    const made = parsed(await tool(slug, hook, "log_session", { tool: "claude-code", externalId: "invented-new-session", machine: "invented-mac", repoUrl: REPO, lastActiveAt: at(5001), title: "Invented kingfishers", prompts: [{ seq: 0, ts: at(5001), role: "user", text: "kingfishers dive straight down" }] }));    expect(made.inserted).toBe(1);    const all = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify(state.storage.sql.exec(`SELECT data FROM rows WHERE table_id IN (${TABLES.map(() => "?").join(",")})`, ...TABLES).toArray()));    for (const w of ["herons", "kingfishers", "Invented: watch"]) expect(holdsWord(all, w), w).toBe(false);    // A password saved over MCP once the passwords are sealed: its name and hint sealed on arrival.    const saved = parsed(await tool(slug, hook, "create_secret", { name: "Invented heron feeder", kind: "api_key", service: "invented-heron", value: "invented-key-2222-3333" }));    expect(saved.name).toBe("Invented heron feeder");    const stored = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'secret' AND id = ?", String(saved.id)).one().data);    for (const w of ["Invented heron feeder", "3333", "invented-key"]) expect(holdsWord(stored, w), w).toBe(false);    expect(JSON.parse(stored)).toMatchObject({ kind: "api_key", service: "invented-heron" });    const got = parsed(await tool(slug, hook, "get_session", { sessionId: uuid(2, 7) })) as { title: string; prompts: { text: string }[]; tasks: { text: string }[] };    expect(got.title).toBe("Invented herons at dawn");    expect(got.prompts.at(-1)!.text).toBe("herons stand still to fish");    expect(got.tasks.map((t) => t.text)).toEqual(["Invented: watch the herons"]);    const found = parsed(await tool(slug, hook, "list_sessions", { q: "kingfishers", limit: 5 })) as { sessions: { title: string; project: string }[] };    expect(found.sessions.map((s) => [s.title, s.project])).toEqual([["Invented kingfishers", projectSlug(0)]]);  }, 3_000_000);  it("the passwords saved over MCP move under the vault key: opened to the owner's device alone, then nothing under VAULT_KEY is left", async () => {    const owner = { authorization: `Bearer ${credential}` };    // A token never reaches it: the front door admits tokens to /v1/act alone.    expect((await http(slug, "GET", "/v1/secret/rewrap", undefined, { authorization: `Bearer ${hook}` })).status).toBe(403);    const asked = await http<{ rows: { id: string; version: number; payload: string }[]; unopened: number; left: number }>(slug, "GET", "/v1/secret/rewrap", undefined, owner);    expect(asked.status, JSON.stringify(asked.body)).toBe(200);    const payloads = Object.fromEntries(asked.body.rows.map((r) => [r.id, JSON.parse(r.payload) as { kind: string; key: string }]));    expect(Object.values(payloads).map((p) => p.key).sort()).toEqual(["invented-key-0000-1111", "invented-key-2222-3333"]);    expect(asked.body).toMatchObject({ unopened: 0, left: 0 });    // The phone seals each under the vault key (invented here: the Worker never opens a v2 value) and hands it back.    const rows = asked.body.rows.map((r, i) => ({ id: r.id, version: r.version, value_enc: `v2:invented-sealed-by-the-phone-${i}`, vmk_version: 1 }));    // A row read before another change is left as it is.    const stale = { ...rows[0]!, version: rows[0]!.version - 1 };    expect((await http(slug, "POST", "/v1/secret/rewrap", { rows: [stale] }, owner)).body).toEqual({ moved: 0, skipped: 1 });    expect((await http(slug, "POST", "/v1/secret/rewrap", { rows }, owner)).body).toEqual({ moved: 2, skipped: 0 });    expect((await http(slug, "GET", "/v1/secret/rewrap", undefined, owner)).body).toMatchObject({ rows: [], left: 0 });    const kept = await runInDurableObject(stub(slug), (_i, state) => ({      rows: state.storage.sql.exec<{ id: string; data: string }>("SELECT id, data FROM rows WHERE table_id = 'secret'").toArray(),      changes: JSON.stringify(state.storage.sql.exec("SELECT before, after FROM change WHERE table_id = 'secret'").toArray()),    }));    for (const r of rows) {      const data = JSON.parse(kept.rows.find((k) => k.id === r.id)!.data) as Record<string, unknown>;      expect(data.value_enc).toBe(r.value_enc);      expect(data.sealed ?? null).toBeNull();    }    expect(kept.rows.every((k) => !k.data.includes("k1:")), "no password under VAULT_KEY").toBe(true);    expect(kept.changes).not.toContain("k1:");    const listed = parsed(await tool(slug, hook, "list_secrets", {})) as { secrets: { isSet: boolean }[] };    expect(listed.secrets.every((x) => x.isSet)).toBe(true);  }, 3_000_000);  it("a token with no grant is answered window_needed, and no session is said", async () => {    const stranger = await mint(slug, credential, "invented unknown machine", ["read"]);    const r = await tool(slug, stranger, "list_sessions", { limit: 5 });    expect(r.isError).toBe(true);    expect(JSON.stringify(r)).toContain("window_needed");    expect(JSON.stringify(r)).not.toContain("Invented session");  }, 3_000_000);});