Cotton code
1265 lines · 92.4 KB · TypeScriptRaw
/** * The 15-minute unlock window on the Worker (src/window.ts, sealing plan §3), * on a synthetic sealed table: no kit table is sealed * yet. Every key is made here or is seal-core's vector; every row is * synthetic. */import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test";import { beforeAll, describe, expect, it } from "vitest";import vector from "../../../crates/cotton-conformance/vectors/seal/grant.json";import tableFileVector from "../../../crates/cotton-conformance/vectors/seal/table_file.json";import { sealF1 } from "../src/arrival_file.ts";import { bucketKey } from "../src/media.ts";import { openF1, personFileKey, tableFileRoot } from "../src/table_files.ts";import type { Business } from "../src/business.ts";import { bucket, blindKey, bodyAad, dekAad, exactToken, tableKey, textTokens } from "../src/seal.ts";import { toBase64Url, fromBase64Url } from "../src/vault.ts";import { openGrant, STANDING_ENDS, unlockStatement, verifyGrant, Windows } from "../src/window.ts";import { ADMIN, DATABASE_ID, http, mint, openTables, OWNER_PHONE, personalObject, publishPersonKey, put, PERSONAL_TABLES, PERSONAL_TOOLS, tool, windowsOnly, 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)));/** The synthetic sealed table: the date and the bin clear; body, mood and external id sealed, the body by word tokens. */const DIARY = {  format_version: 1,  id: "sealed_diary",  name: "Sealed diary",  plural: "Sealed diaries",  title: "body",  date: "written_at",  columns: [    { key: "written_at", type: "date" },    { key: "body", type: "longtext", required: true },    { key: "mood", type: "text" },    { key: "external_id", type: "text" },    { key: "trashed_at", type: "date" },  ],  seal: { clear: ["written_at", "trashed_at"], blind: ["body"], blind_exact: ["external_id"] },};/** Words no place the object keeps text may hold: rows, the change log, the act log. */const SECRET_WORDS = ["zanzibar", "quokka", "marmalade", "ext-4410", "pelican"];// ── the device's half, mirrored from seal-core for the test (grant.rs, wrap.rs, row.rs) ──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!) };}/** `vault::wrap::wrap_with`. */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);}interface Grant {  tables: string[];  minutes: number;  wrapped: string;  signer: string;  sig: string;}/** `seal::grant::build_grant_with`: TK for every version up to each table's seal_v and BK, wrapped to worker_pub, signed by the person key. */async function buildGrant(o: { dk: Uint8Array; requestId: string; tokenId: string; tables: [string, number][]; minutes: number; workerPub: Uint8Array; personSeed: Uint8Array; ephemeral?: Uint8Array; nonce?: Uint8Array; noFiles?: boolean }): Promise<Grant> {  const keys: Record<string, Record<string, string>> = {};  const blind: Record<string, string> = {};  for (const [t, v] of o.tables) {    keys[t] = {};    for (let n = 1; n <= v; n++) keys[t]![String(n)] = toBase64Url(await tableKey(o.dk, DATABASE_ID, t, n));    blind[t] = toBase64Url(await blindKey(o.dk, DATABASE_ID, t));  }  // grant.rs: a window over messages carries the message table's files root (a kept chat picture opens in it).  // AVATAR SEAL (27 Nov 2026): a window over person carries person's files root too (a face opens in it).  const opening = ["message", "person"].filter((t) => keys[t]);  const files = opening.length && !o.noFiles ? { files: Object.fromEntries(await Promise.all(opening.map(async (t) => [t, toBase64Url(await tableFileRoot(o.dk, DATABASE_ID, t))]))) } : {};  const bundle = canonical({ request_id: o.requestId, token_id: o.tokenId, keys, blind, ...files });  const wrapped = await wrapWith(o.ephemeral ?? crypto.getRandomValues(new Uint8Array(32)), o.nonce ?? crypto.getRandomValues(new Uint8Array(12)), o.workerPub, utf8.encode(bundle));  const tables = o.tables.map(([t]) => t).sort();  const person = await okp(ED25519_PKCS8, o.personSeed, "Ed25519", ["sign"]);  const statement = await unlockStatement(DATABASE_ID, o.requestId, o.tokenId, tables, o.minutes, wrapped);  const sig = toBase64Url(new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, person.key, utf8.encode(statement))));  return { tables, minutes: o.minutes, 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);}/** A row sealed as a phone seals it (`seal::row`): every sealed column in one padded blob under a fresh DEK, the DEK under TK(t, v). */async function sealRow(dk: Uint8Array, id: string, v: number, sealed: Record<string, unknown>, table = DIARY.id): 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,  };}async function tokensOf(dk: Uint8Array, sealed: { body: string; external_id?: string }): Promise<string[]> {  const bk = await blindKey(dk, DATABASE_ID, DIARY.id);  const out = new Set(await textTokens(bk, "body", sealed.body));  if (sealed.external_id) out.add((await exactToken(bk, "external_id", sealed.external_id))!);  return [...out];}// ── the object ─────────────────────────────────────────────────────────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}` });}/** A personal object with the synthetic sealed table and the vector's person key; answers the owner phone's credential and an owner token. */async function object(slug: string, tables: Record<string, unknown>[] = [...PERSONAL_TABLES, DIARY]): Promise<{ credential: string; owner: string }> {  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);  // The windows' own rules: this object is kept off Your Claude's standing grant (test/agent.test.ts tests the grant).  await windowsOnly(slug);  const defs = await http(slug, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables, flavour: { flavour: "personal" } }, ADMIN);  expect(defs.status, JSON.stringify(defs.body)).toBe(200);  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" });  expect(signed.status, JSON.stringify(signed.body)).toBe(200);  await publishPersonKey(slug, signed.body.credential, vector.person_public_key);  return { credential: signed.body.credential, owner: await mint(slug, signed.body.credential, "Claude (claude.ai)", ["owner"]) };}/** Every text the object keeps of rows, the change log and the act log. */async function kept(slug: string): Promise<string> {  return runInDurableObject(stub(slug), (_i, state) => JSON.stringify([state.storage.sql.exec("SELECT data FROM rows").toArray(), state.storage.sql.exec("SELECT before, after FROM change").toArray(), state.storage.sql.exec("SELECT args, outcome FROM acts").toArray()]));}async function rowOf(slug: string, table: string, id: string): Promise<Record<string, unknown>> {  return runInDurableObject(stub(slug), (_i, state) => JSON.parse(state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = ? AND id = ?", table, id).one().data) as Record<string, unknown>);}async function sqlCount(slug: string, sql: string, ...args: unknown[]): Promise<number> {  return runInDurableObject(stub(slug), (_i, state) => Number(state.storage.sql.exec<{ n: number }>(sql, ...args).one().n));}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>;}function code(r: ToolResult): unknown {  expect(r.isError, r.content[0]?.text).toBe(true);  return r.structuredContent?.code;}// ── tests ──────────────────────────────────────────────────────────────/** RULE (plan §3.1, seal-core grant vector): the statement, the wrap and the signature are seal-core's to the byte, and the Worker opens and verifies them. */describe("a kept chat picture against seal-core's vector", () => {  const v = tableFileVector;  const bytes = (h: string) => Uint8Array.from(h.match(/../g)!.map((b) => parseInt(b, 16)));  it("makes TFR and FK as the core does and opens its f1 files, across a part's edge", async () => {    const root = await tableFileRoot(bytes(v.dk_hex), v.database_id, v.table);    expect(toBase64Url(root)).toBe(toBase64Url(bytes(v.root_hex)));    const fk = await personFileKey(root, v.object_key);    expect(toBase64Url(fk)).toBe(v.fk);    const plain = await openF1(fk, v.object_key, bytes(v.sealed_hex));    expect(plain?.length).toBe(v.plain_len);    const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", plain!));    expect([...digest].map((b) => b.toString(16).padStart(2, "0")).join("")).toBe(v.plain_sha256);    expect(new TextDecoder().decode((await openF1(fk, v.object_key, bytes(v.small_sealed_hex)))!)).toBe(v.small_plain);    // Another key, another object key, or a cut file opens nothing.    expect(await openF1(await personFileKey(root, `${v.object_key}x`), v.object_key, bytes(v.small_sealed_hex))).toBeNull();    expect(await openF1(fk, `${v.object_key}x`, bytes(v.small_sealed_hex))).toBeNull();    expect(await openF1(fk, v.object_key, bytes(v.sealed_hex).subarray(0, 4 + 7 + 65_552))).toBeNull();  });});describe("the grant against seal-core's vector", () => {  const dk = hex(vector.dk_hex);  const tables = vector.tables.map((t) => [t.table, t.seal_v] as [string, number]);  it("builds the vector's wrap, statement and signature from its fixed keys", async () => {    const grant = await buildGrant({ dk, requestId: vector.request_id, tokenId: vector.token_id, tables, minutes: vector.minutes, workerPub: fromBase64Url(vector.worker_pub), personSeed: hex(vector.person_seed_hex), ephemeral: hex(vector.ephemeral_hex), nonce: hex(vector.nonce_hex) });    expect(grant.wrapped).toBe(vector.wrapped);    expect(grant.sig).toBe(vector.sig);    expect(grant.signer).toBe(vector.signer);    expect(grant.tables).toEqual(vector.granted_tables);    expect(await unlockStatement(vector.database_id, vector.request_id, vector.token_id, vector.granted_tables, vector.minutes, vector.wrapped)).toBe(vector.statement);  });  it("verifies the vector's signature and opens its wrap to the bundle, and refuses each change", async () => {    const grant = { tables: vector.granted_tables, minutes: vector.minutes, wrapped: vector.wrapped, signer: vector.signer, sig: vector.sig };    expect(await verifyGrant(vector.person_public_key, vector.database_id, vector.request_id, vector.token_id, grant)).toBe(true);    expect(await verifyGrant(vector.person_public_key, vector.database_id, vector.request_id, vector.token_id, { ...grant, minutes: 14 })).toBe(false);    expect(await verifyGrant(vector.person_public_key, vector.database_id, vector.request_id, "tok-2", grant)).toBe(false);    expect(await verifyGrant(vector.person_public_key, vector.database_id, vector.request_id, vector.token_id, { ...grant, signer: "AAAAAAAA" })).toBe(false);    const secret = hex(vector.worker_secret_hex);    const pub = fromBase64Url(vector.worker_pub);    const opened = await openGrant(secret, pub, vector.request_id, vector.token_id, vector.granted_tables, vector.wrapped);    expect(opened?.text).toBe(vector.bundle);    expect(toBase64Url(opened!.bundle.keys.get("message")!.get(3)!)).toBe(toBase64Url(await tableKey(dk, vector.database_id, "message", 3)));    // A window over messages carries the message table's files root, and only it.    expect([...opened!.bundle.files.keys()]).toEqual(["message"]);    expect(toBase64Url(opened!.bundle.files.get("message")!)).toBe(toBase64Url(await tableFileRoot(dk, vector.database_id, "message")));    // The wrong request, token or tables open nothing.    expect(await openGrant(secret, pub, "req-2", vector.token_id, vector.granted_tables, vector.wrapped)).toBeNull();    expect(await openGrant(secret, pub, vector.request_id, "tok-2", vector.granted_tables, vector.wrapped)).toBeNull();    expect(await openGrant(secret, pub, vector.request_id, vector.token_id, ["note"], vector.wrapped)).toBeNull();    expect(await openGrant(crypto.getRandomValues(new Uint8Array(32)), pub, vector.request_id, vector.token_id, vector.granted_tables, vector.wrapped)).toBeNull();  });});/** RULE (plan §3.2, §3.3): a sealed table reads only in a window the owner allowed on the phone, for the one owner token that asked, until the object's own clock ends it; nothing plaintext lands in rows, change or acts. */describe("the unlock window on the object", () => {  const slug = "window-worker";  const dk = crypto.getRandomValues(new Uint8Array(32));  const personSeed = hex(vector.person_seed_hex);  let credential = "";  let owner = "";  let other = "";  let lane = "";  let coordinator = "";  const ids: Record<string, string> = {};  /** One sealed diary row at version v, made by the phone through the act path. */  async function sealed(name: string, v: number, written: string, values: { body: string; mood?: string; external_id?: string }): Promise<void> {    const id = crypto.randomUUID();    const made = await act(slug, credential, "create", { table: DIARY.id, id, data: { written_at: written, ...(await sealRow(dk, id, v, values)) }, blind: await tokensOf(dk, values) });    expect(made.status, JSON.stringify(made.body)).toBe(200);    ids[name] = id;  }  /** The owner allows the request on the phone: TK up to `v` for the diary, signed by the vector's person key. */  async function allow(requestId: string, over: Partial<{ minutes: number; v: number; tokenId: string; seed: Uint8Array; signer: string }> = {}): Promise<{ status: number; body: Record<string, unknown> }> {    const request = await rowOf(slug, "unlock_request", requestId);    const grant = await buildGrant({ dk, requestId, tokenId: over.tokenId ?? String(request.token_id), tables: [[DIARY.id, over.v ?? 2]], minutes: over.minutes ?? 15, workerPub: fromBase64Url(String(request.worker_pub)), personSeed: over.seed ?? personSeed });    return act(slug, credential, "unlock_allow", { request_id: requestId, ...grant, ...(over.signer ? { signer: over.signer } : {}) });  }  /** Requests made earlier in the run are moved two hours back, so the hourly limit counts only what a test makes. */  async function ageRequests(): Promise<void> {    await runInDurableObject(stub(slug), (_i, state) => {      state.storage.sql.exec("UPDATE rows SET data = json_set(data, '$.requested_at', ?) WHERE table_id = 'unlock_request'", new Date(Date.now() - 2 * 3_600_000).toISOString());    });  }  beforeAll(async () => {    ({ credential, owner } = await object(slug));    other = await mint(slug, credential, "Another assistant", ["owner"]);    lane = await mint(slug, credential, "lane widgets", ["read", "lane:widgets"], 7, "mac-c");    coordinator = await mint(slug, credential, "coordinator", ["coordinator"]);    await sealed("first", 1, "2026-11-01", { body: "Zanzibar spice market at dawn", mood: "marmalade", external_id: "ext-4410" });    await sealed("second", 2, "2026-11-02", { body: "A quokka smiled at the ferry", mood: "calm" });    // A row sealed under a version no grant below holds: it is answered parked, never blank.    await sealed("later", 3, "2026-11-03", { body: "pelican beyond the window" });  }, 120_000);  let requestId = "";  it("answers a read of a sealed table with window_needed and one request, asked once; a lane and the coordinator ask like any assistant", async () => {    const first = await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: ids.first! });    expect(code(first)).toBe("window_needed");    requestId = String(first.structuredContent!.request_id);    // The ask says the card stands in any Cotton app, from the kit's own line, and says no window was opened for this assistant.    expect(first.content[0]!.text).toContain("the owner has not opened a window for this assistant");    expect(first.content[0]!.text).toContain("The owner must allow this on their phone, in any Cotton app they open");    const request = await rowOf(slug, "unlock_request", requestId);    expect(request).toMatchObject({ state: "waiting", tables: [DIARY.id], minutes: 15, client: "Claude (claude.ai)" });    expect(fromBase64Url(String(request.worker_pub)).length).toBe(32);    expect(Date.parse(String(request.expires_at)) - Date.parse(String(request.requested_at))).toBe(10 * 60_000);    // A read files no reason of its own: the card shows the person no tool's name ("get_record_by_table on Diary entries").    expect(request.reason ?? "").toBe("");    // A repeat ask, by a read or by the tool, answers the same request.    expect((await tool(slug, owner, "list_records", { table: DIARY.id })).structuredContent!.request_id).toBe(requestId);    // The same tables (absent would ask for every sealed table, and the kit seals more than the diary).    expect(parsed(await tool(slug, owner, "request_unlock", { tables: [DIARY.id], reason: "To read last week's diary" }))).toMatchObject({ state: "waiting", request_id: requestId });    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM rows WHERE table_id = 'unlock_request'")).toBe(1);    // A lane token and the coordinator ask too (plan Q8 lifted): each its own request, nothing opened.    for (const token of [lane, coordinator]) {      expect(code(await tool(slug, token, "get_record_by_table", { table: DIARY.id, id: ids.first! }))).toBe("window_needed");    }    const laneAsk = parsed(await tool(slug, lane, "request_unlock", { tables: [DIARY.id], reason: "x" }));    expect(laneAsk.state).toBe("waiting");    // What asks, for the card's plain words (owner, 23 Nov 2026: the lane's own name told him nothing): a minted    // token is code, on the machine its mint named; the request never needs the token's own name to say it.    expect(await rowOf(slug, "unlock_request", String(laneAsk.request_id))).toMatchObject({ asker: "code", machine: "mac-c" });    const badMachine = await http<{ code?: string }>(slug, "POST", "/v1/act", { act: "mint_token", args: { name: "x", scopes: ["read"], machine: "mac c; rm" } }, { authorization: `Bearer ${credential}` });    expect(badMachine.status).toBe(400);    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM rows WHERE table_id = 'unlock_request'")).toBe(3);    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM window_request_key")).toBe(3);  });  it("refuses a forged signature, a grant for another token, a token's own allow, and every direct write of the unlock tables", async () => {    const stranger = await allow(requestId, { seed: crypto.getRandomValues(new Uint8Array(32)) });    expect([stranger.status, stranger.body.code]).toEqual([409, "no_person_key"]);    // Another key's signature said under the person key's fingerprint.    const forged = await allow(requestId, { seed: crypto.getRandomValues(new Uint8Array(32)), signer: vector.signer });    expect([forged.status, forged.body.code]).toEqual([403, "bad_signature"]);    // Signed by the person key, but over a statement for another token: the object signs nothing it did not ask.    const otherToken = await allow(requestId, { tokenId: "someone-else" });    expect([otherToken.status, otherToken.body.code]).toEqual([403, "bad_signature"]);    const tooLong = await allow(requestId, { minutes: 16 });    expect(tooLong.status).toBe(400);    const byToken = await tool(slug, owner, "run_act", { act: "unlock_allow", args: { request_id: requestId } });    // A grant is an access act: refused to every key at the one gate (ADMIN KEYS 1b).    expect(code(byToken)).toBe("access_act");    expect((await act(slug, credential, "create", { table: "unlock_grant", data: { request_id: requestId } })).body).toMatchObject({ code: "unlock_only" });    expect((await act(slug, credential, "update", { table: "unlock_request", id: requestId, data: { state: "granted" } })).body).toMatchObject({ code: "unlock_only" });    expect((await tool(slug, owner, "create_record", { table: "unlock_grant", data: { request_id: requestId } })).isError).toBe(true);    expect((await rowOf(slug, "unlock_request", requestId)).state).toBe("waiting");  });  let grantId = "";  let endsAt = "";  it("opens the window on a grant the person key signed, deletes the request's key, stamps ends_at on its own clock and folds it into the alarm; a replay opens nothing", async () => {    const before = Date.now();    const res = await allow(requestId);    expect(res.status, JSON.stringify(res.body)).toBe(200);    grantId = String(res.body.grant);    endsAt = String(res.body.ends_at);    expect(Date.parse(endsAt) - before).toBeGreaterThanOrEqual(15 * 60_000 - 1000);    expect(Date.parse(endsAt) - Date.now()).toBeLessThanOrEqual(15 * 60_000);    expect((await rowOf(slug, "unlock_request", requestId)).state).toBe("granted");    const grant = await rowOf(slug, "unlock_grant", grantId);    expect(grant).toMatchObject({ request_id: requestId, tables: [DIARY.id], minutes: 15, standing: false, client: "Claude (claude.ai)", signer: vector.signer, ends_at: endsAt });    expect(grant.wrapped).toBeUndefined();    expect(String(grant.wrapped_sha256)).toMatch(/^[0-9a-f]{64}$/);    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM window_request_key WHERE request_id = ?", requestId)).toBe(0);    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM window_secret")).toBe(1);    // The kept keys are sealed under WINDOW_KEY: no table key is in the clear there.    const tk = toBase64Url(await tableKey(dk, DATABASE_ID, DIARY.id, 1));    const secret = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify(state.storage.sql.exec("SELECT * FROM window_secret").toArray()));    expect(secret).not.toContain(tk);    // The act log keeps that a wrap was said, never the wrap.    const acts = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify(state.storage.sql.exec("SELECT args FROM acts WHERE act = 'unlock_allow'").toArray()));    expect(acts).toContain("‹wrap›");    expect(acts).not.toContain("w1:");    const alarm = await runInDurableObject(stub(slug), (_i, state) => state.storage.getAlarm());    expect(alarm).not.toBeNull();    expect(alarm!).toBeLessThanOrEqual(Date.parse(endsAt));    const replay = await allow(requestId);    expect([replay.status, replay.body.code]).toEqual([409, "request_answered"]);  });  it("opens rows in the window for the token that asked: each version with its own key, a version it was not given parked by name, search by blind tokens", async () => {    const got = parsed(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: ids.first! }));    expect(got.data).toEqual({ written_at: "2026-11-01", body: "Zanzibar spice market at dawn", mood: "marmalade", external_id: "ext-4410" });    expect(got.window).toEqual({ table: DIARY.id, ends_at: endsAt });    const listed = parsed(await tool(slug, owner, "list_records", { table: DIARY.id }));    const records = listed.records as { id: string; data: Record<string, unknown>; sealed?: string }[];    expect(records.map((r) => r.id)).toEqual([ids.later, ids.second, ids.first]);    expect(records[1]!.data.body).toBe("A quokka smiled at the ferry");    expect(records[0]).toMatchObject({ sealed: "seal_key_missing", data: { written_at: "2026-11-03" } });    // Search: the query's words by their tokens, held to the plaintext.    const found = parsed(await tool(slug, owner, "search_records", { q: "quokka", table: DIARY.id }));    expect(found.hits).toEqual([expect.objectContaining({ id: ids.second, column: "body", excerpt: "A quokka smiled at the ferry" })]);    const prefix = parsed(await tool(slug, owner, "list_records", { table: DIARY.id, query: "spice mark" }));    expect((prefix.records as { id: string }[]).map((r) => r.id)).toEqual([ids.first]);    expect((parsed(await tool(slug, owner, "list_records", { table: DIARY.id, query: "walrus" })).records as unknown[]).length).toBe(0);    // The change log opens in the window too.    const log = parsed(await tool(slug, owner, "list_changes", { table: DIARY.id, id: ids.second! }));    expect(JSON.stringify(log.changes)).toContain("quokka");    // Another owner token holds no window: it is asked for its own.    expect(code(await tool(slug, other, "get_record_by_table", { table: DIARY.id, id: ids.first! }))).toBe("window_needed");    expect(code(await tool(slug, lane, "list_records", { table: DIARY.id }))).toBe("window_needed");  });  it("reads its keys back after the object loses its memory, and ends a window whose keys WINDOW_KEY no longer opens (key_lost)", async () => {    await runInDurableObject(stub(slug), (instance: Business) => {      (instance as unknown as { unlocks: Windows }).unlocks = new Windows();    });    expect(parsed(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: ids.second! })).data).toMatchObject({ body: "A quokka smiled at the ferry" });    // The blob no longer opens (as under a rotated WINDOW_KEY): the window ends by name, and nothing is answered in the clear.    await runInDurableObject(stub(slug), (instance: Business, state) => {      (instance as unknown as { unlocks: Windows }).unlocks = new Windows();      state.storage.sql.exec("UPDATE window_secret SET blob = ? WHERE grant_id = ?", toBase64Url(crypto.getRandomValues(new Uint8Array(80))), grantId);    });    expect(code(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: ids.second! }))).toBe("window_needed");    expect(await rowOf(slug, "unlock_grant", grantId)).toMatchObject({ ended_by: "key_lost" });    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM window_secret WHERE grant_id = ?", grantId)).toBe(0);  });  it("holds the guard with no alarm: past ends_at a read is refused, whatever the alarm did; the alarm then ends it by the timer", async () => {    const asked = await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: ids.first! });    const next = String(asked.structuredContent!.request_id);    const res = await allow(next, { minutes: 15 });    expect(res.status, JSON.stringify(res.body)).toBe(200);    const grant = String(res.body.grant);    expect(Date.parse(String(res.body.ends_at)) - Date.now()).toBeLessThanOrEqual(15 * 60_000);    expect(parsed(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: ids.first! })).data).toMatchObject({ mood: "marmalade" });    // Time passes (the kept end moves back); no alarm runs.    const past = new Date(Date.now() - 1000).toISOString();    await runInDurableObject(stub(slug), (_i, state) => {      state.storage.sql.exec("UPDATE window_secret SET ends_at = ? WHERE grant_id = ?", past, grant);      state.storage.sql.exec("UPDATE rows SET data = json_set(data, '$.ends_at', ?) WHERE table_id = 'unlock_grant' AND id = ?", past, grant);    });    expect(code(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: ids.first! }))).toBe("window_needed");    // That call met the end and cleaned it up; the alarm finds nothing left and stays harmless.    await runDurableObjectAlarm(stub(slug));    expect(await rowOf(slug, "unlock_grant", grant)).toMatchObject({ ended_by: "timer", ended_at: past });    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM window_secret")).toBe(0);  });  it("refuses a request that expired, and the alarm expires it and drops its key", async () => {    const asked = await tool(slug, owner, "list_records", { table: DIARY.id });    const next = String(asked.structuredContent!.request_id);    await runInDurableObject(stub(slug), (_i, state) => {      state.storage.sql.exec("UPDATE rows SET data = json_set(data, '$.expires_at', ?) WHERE table_id = 'unlock_request' AND id = ?", new Date(Date.now() - 1000).toISOString(), next);    });    const late = await allow(next);    expect([late.status, late.body.code]).toEqual([410, "request_expired"]);    await runDurableObjectAlarm(stub(slug));    expect((await rowOf(slug, "unlock_request", next)).state).toBe("expired");    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM window_request_key WHERE request_id = ?", next)).toBe(0);  });  it("ends a window from the phone, by the assistant, and when the token is revoked", async () => {    await ageRequests();    const open = async (token: string): Promise<string> => {      const asked = await tool(slug, token, "request_unlock", { tables: [DIARY.id], reason: "Read the diary", minutes: 60 });      const res = await allow(String(parsed(asked).request_id), { minutes: 60 });      expect(res.status, JSON.stringify(res.body)).toBe(200);      expect(parsed(await tool(slug, token, "request_unlock", { tables: [DIARY.id], reason: "again" }))).toMatchObject({ state: "open" });      return String(res.body.grant);    };    const byPhone = await open(owner);    expect((await act(slug, credential, "unlock_end", { grant_id: byPhone })).status).toBe(200);    expect(await rowOf(slug, "unlock_grant", byPhone)).toMatchObject({ ended_by: "phone" });    expect(code(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: ids.first! }))).toBe("window_needed");    const byAssistant = await open(owner);    expect(parsed(await tool(slug, owner, "end_unlock"))).toEqual({ ended: 1 });    expect(await rowOf(slug, "unlock_grant", byAssistant)).toMatchObject({ ended_by: "assistant" });    const revoked = await open(other);    const tokenId = String((await rowOf(slug, "unlock_grant", revoked)).token_id);    expect((await act(slug, credential, "revoke_token", { id: tokenId })).status).toBe(200);    expect(await rowOf(slug, "unlock_grant", revoked)).toMatchObject({ ended_by: "token_revoked" });    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM window_secret")).toBe(0);  });  it("declines a request from the phone, dropping its key", async () => {    await ageRequests();    const asked = await tool(slug, owner, "request_unlock", { tables: [DIARY.id], reason: "Read the diary once more" });    const next = String(parsed(asked).request_id);    expect((await act(slug, credential, "unlock_decline", { request_id: next })).status).toBe(200);    expect((await rowOf(slug, "unlock_request", next)).state).toBe("declined");    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM window_request_key WHERE request_id = ?", next)).toBe(0);    expect([(await allow(next)).body.code]).toEqual(["request_answered"]);    // While the Not now stands (until the request's expires_at), the asker hears it, by the tool and by a read, and nothing new is asked.    const before = await sqlCount(slug, "SELECT COUNT(*) AS n FROM rows WHERE table_id = 'unlock_request'");    const again = parsed(await tool(slug, owner, "request_unlock", { tables: [DIARY.id], reason: "Please, the diary" }));    expect(again).toMatchObject({ state: "declined", request_id: next, tables: [DIARY.id] });    expect(String(again.sentence)).toContain("The owner chose Not now for");    expect(String(again.sentence)).toContain(String(again.expires_at));    const read = await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: ids.first! });    expect(code(read)).toBe("window_declined");    expect(read.structuredContent).toMatchObject({ request_id: next, expires_at: again.expires_at });    expect(read.content[0]!.text).toBe(again.sentence);    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM rows WHERE table_id = 'unlock_request'")).toBe(before);    // Another token is not held to this token's decline.    const fresh = await mint(slug, credential, "A third assistant", ["owner"]);    expect(parsed(await tool(slug, fresh, "request_unlock", { reason: "r" })).state).toBe("waiting");    // Once the request has passed its expires_at, asking makes a new request.    await runInDurableObject(stub(slug), (_i, state) => {      state.storage.sql.exec("UPDATE rows SET data = json_set(data, '$.expires_at', ?) WHERE id = ?", new Date(Date.now() - 1000).toISOString(), next);    });    const later = parsed(await tool(slug, owner, "request_unlock", { tables: [DIARY.id], reason: "Read the diary once more" }));    expect(later.state).toBe("waiting");    expect(later.request_id).not.toBe(next);  });  it("never lets a sealed column's plaintext reach rows, change or acts (the guard)", async () => {    const all = (await kept(slug)).toLowerCase();    for (const w of SECRET_WORDS) expect(holdsWord(all, w), w).toBe(false);  });});/** RULE (plan §3.3): at most six requests an hour per object, one waiting per token. */describe("unlock request limits", () => {  it("refuses the seventh request in an hour", async () => {    const slug = "window-limits";    const { credential } = await object(slug);    for (let i = 0; i < 6; i++) {      const token = await mint(slug, credential, `assistant ${i}`, ["owner"]);      expect(parsed(await tool(slug, token, "request_unlock", { reason: "r" })).state).toBe("waiting");    }    const seventh = await mint(slug, credential, "assistant 7", ["owner"]);    expect(code(await tool(slug, seventh, "request_unlock", { reason: "r" }))).toBe("too_many_requests");  }, 60_000);});// ── ruling R4: how long, who, the log, writes, brief ──/** One device's grant for a request on `slug`, by the person key of the vector, for `minutes`, posted by `credential` (or another bearer). */async function allowOn(slug: string, bearer: string, dk: Uint8Array, requestId: string, minutes: number, table = DIARY.id, v = 1, noFiles = false): Promise<{ status: number; body: Record<string, unknown> }> {  const request = await rowOf(slug, "unlock_request", requestId);  const grant = await buildGrant({ dk, requestId, tokenId: String(request.token_id), tables: [[table, v]], minutes, workerPub: fromBase64Url(String(request.worker_pub)), personSeed: hex(vector.person_seed_hex), noFiles });  return act(slug, bearer, "unlock_allow", { request_id: requestId, ...grant });}async function ageAll(slug: string): Promise<void> {  await runInDurableObject(stub(slug), (_i, state) => {    state.storage.sql.exec("UPDATE rows SET data = json_set(data, '$.requested_at', ?) WHERE table_id = 'unlock_request'", new Date(Date.now() - 2 * 3_600_000).toISOString());  });}async function askOn(slug: string, token: string, minutes?: number): Promise<string> {  await ageAll(slug);  const asked = parsed(await tool(slug, token, "request_unlock", { tables: [DIARY.id], reason: "Read the diary", ...(minutes === undefined ? {} : { minutes }) }));  expect(asked.state).toBe("waiting");  return String(asked.request_id);}// OAuth, as claude.ai connects (test/oauth.test.ts walks each step).const REDIRECT = "https://claude.ai/api/mcp/auth_callback";async function form(url: string, body: Record<string, string>): Promise<Response> {  return SELF.fetch(url, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body).toString() });}function hidden(html: string): Record<string, string> {  const out: Record<string, string> = {};  for (const m of html.matchAll(/<input type="hidden" name="([^"]+)" value="([^"]*)">/g)) out[m[1]!] = m[2]!.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");  return out;}/** A connection made by the OAuth flow: its client id and first token pair. */async function connect(slug: string, name: string): Promise<{ clientId: string; access: string; refresh: string }> {  const base = `https://example.test/b/${slug}`;  const reg = await SELF.fetch(`${base}/oauth/register`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: name, redirect_uris: [REDIRECT] }) });  expect(reg.status).toBe(201);  const clientId = ((await reg.json()) as { client_id: string }).client_id;  const v = toBase64Url(crypto.getRandomValues(new Uint8Array(40)));  const challenge = toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", utf8.encode(v))));  const q = new URLSearchParams({ client_id: clientId, redirect_uri: REDIRECT, response_type: "code", code_challenge: challenge, code_challenge_method: "S256", state: "s", scope: "owner", resource: `${base}/mcp` });  const start = await SELF.fetch(`${base}/oauth/authorize?${q}`, { redirect: "manual" });  const sent = await form(`${base}/oauth/authorize`, { ...hidden(await start.text()), phone: OWNER_PHONE });  const done = await form(`${base}/oauth/authorize`, { ...hidden(await sent.text()), code: "123456" });  expect(done.status).toBe(302);  const code = new URL(done.headers.get("location")!).searchParams.get("code")!;  const res = await form(`${base}/oauth/token`, { grant_type: "authorization_code", client_id: clientId, code, code_verifier: v, redirect_uri: REDIRECT, resource: `${base}/mcp` });  expect(res.status).toBe(200);  const pair = (await res.json()) as { access_token: string; refresh_token: string };  return { clientId, access: pair.access_token, refresh: pair.refresh_token };}async function refreshOn(slug: string, clientId: string, refresh: string): Promise<{ access: string; refresh: string }> {  const res = await form(`https://example.test/b/${slug}/oauth/token`, { grant_type: "refresh_token", client_id: clientId, refresh_token: refresh });  expect(res.status).toBe(200);  const pair = (await res.json()) as { access_token: string; refresh_token: string };  return { access: pair.access_token, refresh: pair.refresh_token };}/** RULE (R4): the person picks how long when allowing (15 minutes, 1 hour, 1 day, until they turn it off) and their pick wins; the object stamps and holds it. */describe("R4 how long: the four durations", () => {  const slug = "window-durations";  const dk = crypto.getRandomValues(new Uint8Array(32));  let credential = "";  let owner = "";  let id = "";  beforeAll(async () => {    ({ credential, owner } = await object(slug));    id = crypto.randomUUID();    const values = { body: "A walrus by the jetty", mood: "glad" };    expect((await act(slug, credential, "create", { table: DIARY.id, id, data: { written_at: "2026-11-05", ...(await sealRow(dk, id, 1, values)) }, blind: await tokensOf(dk, values) })).status).toBe(200);  }, 120_000);  it("refuses anything but the four, and lets the person's pick win over what the request suggested", async () => {    expect((await tool(slug, owner, "request_unlock", { tables: [DIARY.id], reason: "r", minutes: 30 })).isError).toBe(true);    const requestId = await askOn(slug, owner, 15);    for (const m of [5, 16, 30, 1441, -1]) expect((await allowOn(slug, credential, dk, requestId, m)).status, String(m)).toBe(400);    const before = Date.now();    const day = await allowOn(slug, credential, dk, requestId, 1440);    expect(day.status, JSON.stringify(day.body)).toBe(200);    expect(Date.parse(String(day.body.ends_at)) - before).toBeGreaterThanOrEqual(1440 * 60_000 - 1000);    expect(Date.parse(String(day.body.ends_at)) - Date.now()).toBeLessThanOrEqual(1440 * 60_000);    expect(await rowOf(slug, "unlock_grant", String(day.body.grant))).toMatchObject({ minutes: 1440, standing: false });    expect((await act(slug, credential, "unlock_end", { grant_id: String(day.body.grant) })).status).toBe(200);    const hour = await allowOn(slug, credential, dk, await askOn(slug, owner, 0), 60);    expect(Date.parse(String(hour.body.ends_at)) - Date.now()).toBeLessThanOrEqual(60 * 60_000);    expect(Date.parse(String(hour.body.ends_at)) - Date.now()).toBeGreaterThan(59 * 60_000);    expect((await act(slug, credential, "unlock_end", { grant_id: String(hour.body.grant) })).status).toBe(200);  });  it("holds a standing grant until it is turned off: no timer, no alarm ends it, and End on the phone does", async () => {    const res = await allowOn(slug, credential, dk, await askOn(slug, owner), 0);    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body).toMatchObject({ ends_at: STANDING_ENDS, standing: true });    const grant = String(res.body.grant);    expect(await rowOf(slug, "unlock_grant", grant)).toMatchObject({ minutes: 0, standing: true, ends_at: STANDING_ENDS, client: "Claude (claude.ai)" });    const got = parsed(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id }));    expect(got.data).toMatchObject({ body: "A walrus by the jetty" });    expect(got.window).toEqual({ table: DIARY.id, standing: true });    expect(parsed(await tool(slug, owner, "request_unlock", { tables: [DIARY.id], reason: "again" }))).toEqual({ state: "open", tables: [DIARY.id], standing: true });    // The alarm sets nothing for it, and running one leaves it open.    const alarm = await runInDurableObject(stub(slug), (_i, state) => state.storage.getAlarm());    expect(alarm === null || alarm < Date.parse("9000-01-01")).toBe(true);    await runDurableObjectAlarm(stub(slug));    expect(parsed(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id })).data).toMatchObject({ mood: "glad" });    expect((await act(slug, credential, "unlock_end", { grant_id: grant })).status).toBe(200);    expect(await rowOf(slug, "unlock_grant", grant)).toMatchObject({ ended_by: "phone" });    expect(code(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id }))).toBe("window_needed");  });  it("ends a standing grant when its keys no longer open (key loss)", async () => {    const res = await allowOn(slug, credential, dk, await askOn(slug, owner), 0);    const grant = String(res.body.grant);    await runInDurableObject(stub(slug), (instance: Business, state) => {      (instance as unknown as { unlocks: Windows }).unlocks = new Windows();      state.storage.sql.exec("UPDATE window_secret SET blob = ? WHERE grant_id = ?", toBase64Url(crypto.getRandomValues(new Uint8Array(80))), grant);    });    expect(code(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id }))).toBe("window_needed");    expect(await rowOf(slug, "unlock_grant", grant)).toMatchObject({ ended_by: "key_lost" });  });  it("logs every window's reads where the owner sees them: assistant, tables, tool, rows, when; never a value", async () => {    const res = await allowOn(slug, credential, dk, await askOn(slug, owner), 15);    const grant = String(res.body.grant);    const listed = parsed(await tool(slug, owner, "list_records", { table: DIARY.id }));    expect((listed.records as unknown[]).length).toBe(1);    const log = await runInDurableObject(stub(slug), (_i, state) =>      state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'assistant_read'").toArray().map((r) => JSON.parse(r.data) as Record<string, unknown>),    );    const mine = log.filter((r) => r.grant_id === grant);    expect(mine).toEqual([expect.objectContaining({ client: "Claude (claude.ai)", tables: [DIARY.id], tool: "list_records", rows: 1, wrote: false })]);    expect(Date.parse(String(mine[0]!.read_at))).toBeGreaterThan(Date.now() - 60_000);    // Earlier windows' reads are there too, each under its own window.    expect(log.filter((r) => r.tool === "get_record_by_table").length).toBeGreaterThanOrEqual(2);    expect(JSON.stringify(log).toLowerCase()).not.toContain("walrus");    // Only the object writes it.    expect((await act(slug, credential, "create", { table: "assistant_read", data: { grant_id: grant } })).body).toMatchObject({ code: "unlock_only" });    expect((await tool(slug, owner, "create_record", { table: "assistant_read", data: { grant_id: grant } })).isError).toBe(true);    expect((await act(slug, credential, "unlock_end", { grant_id: grant })).status).toBe(200);  });  it("seals an assistant's writes with the window's keys, logged as writes; outside a window a write is window_needed", async () => {    expect(code(await tool(slug, owner, "create_record", { table: DIARY.id, data: { written_at: "2026-11-07", body: "An otter with a pebble" } }))).toBe("window_needed");    const res = await allowOn(slug, credential, dk, await askOn(slug, owner), 15);    const grant = String(res.body.grant);    const made = parsed(await tool(slug, owner, "create_record", { table: DIARY.id, data: { written_at: "2026-11-07", body: "An otter with a pebble", mood: "curious" } }));    const madeId = String((made.record as { id: string }).id);    expect((made.record as { data: Record<string, unknown> }).data).toMatchObject({ body: "An otter with a pebble", mood: "curious" });    const stored = await rowOf(slug, DIARY.id, madeId);    expect(stored.written_at).toBe("2026-11-07");    expect(String(stored.sealed_enc)).toMatch(/^s1:/);    expect(stored.seal_v).toBe(1);    expect(JSON.stringify(stored).toLowerCase()).not.toContain("otter");    // The phone opens it with its own key: the object sealed it as a phone would.    const { openRow } = await import("../src/seal.ts");    expect(await openRow(await tableKey(dk, DATABASE_ID, DIARY.id, 1), DATABASE_ID, DIARY.id, madeId, stored)).toMatchObject({ body: "An otter with a pebble", mood: "curious" });    // Its blind tokens are kept: a search in the window finds it.    const found = parsed(await tool(slug, owner, "search_records", { q: "otter", table: DIARY.id }));    expect((found.hits as { id: string }[]).map((h) => h.id)).toEqual([madeId]);    // An update opens, lays the patch over, and seals again.    const updated = parsed(await tool(slug, owner, "update_record", { table: DIARY.id, id: madeId, patch: { mood: "sleepy" } }));    expect((updated.record as { data: Record<string, unknown> }).data).toMatchObject({ body: "An otter with a pebble", mood: "sleepy" });    const again = await rowOf(slug, DIARY.id, madeId);    expect(again.sealed_enc).not.toBe(stored.sealed_enc);    expect(JSON.stringify(again).toLowerCase()).not.toContain("sleepy");    const log = await runInDurableObject(stub(slug), (_i, state) =>      state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'assistant_read'").toArray().map((r) => JSON.parse(r.data) as Record<string, unknown>),    );    expect(log.filter((r) => r.grant_id === grant && r.wrote === true).map((r) => r.tool).sort()).toEqual(["create_record", "update_record"]);    expect((await act(slug, credential, "unlock_end", { grant_id: grant })).status).toBe(200);    expect(code(await tool(slug, owner, "update_record", { table: DIARY.id, id: madeId, patch: { mood: "x" } }))).toBe("window_needed");    const all = (await kept(slug)).toLowerCase();    for (const w of ["otter", "pebble", "curious", "sleepy", "walrus"]) expect(holdsWord(all, w), w).toBe(false);  });});/** RULE (R4 who): any assistant connection may ask, a lane's and the coordinator's too; only the person's own device allows, never a token and never the admin. */describe("R4 who: anyone asks, only the person's device allows", () => {  const slug = "window-who";  const dk = crypto.getRandomValues(new Uint8Array(32));  let credential = "";  beforeAll(async () => {    ({ credential } = await object(slug));  }, 120_000);  it("lets a lane token and the coordinator ask and, once the person allows on the phone, read", async () => {    const id = crypto.randomUUID();    const values = { body: "Heron on the pier" };    expect((await act(slug, credential, "create", { table: DIARY.id, id, data: { written_at: "2026-11-06", ...(await sealRow(dk, id, 1, values)) }, blind: await tokensOf(dk, values) })).status).toBe(200);    for (const [name, scopes, days] of [["lane widgets", ["read", "lane:widgets"], 7], ["coordinator", ["coordinator"], undefined]] as const) {      const token = await mint(slug, credential, name, [...scopes], days);      const res = await allowOn(slug, credential, dk, await askOn(slug, token), 15);      expect(res.status, JSON.stringify(res.body)).toBe(200);      expect(parsed(await tool(slug, token, "get_record_by_table", { table: DIARY.id, id })).data).toMatchObject({ body: "Heron on the pier" });      expect(parsed(await tool(slug, token, "end_unlock"))).toEqual({ ended: 1 });    }  });  it("never lets the admin token open a window: not by allowing, not by planting a person key", async () => {    const token = await mint(slug, credential, "An assistant", ["owner"]);    const requestId = await askOn(slug, token);    // A grant the person key truly signed, posted by the admin: refused, and the request still waits.    const byAdmin = await allowOn(slug, ADMIN.authorization.slice("Bearer ".length), dk, requestId, 15);    expect([byAdmin.status, byAdmin.body.code]).toEqual([403, "owner_only"]);    for (const [name, args] of [["unlock_decline", { request_id: requestId }], ["unlock_end", { grant_id: "x" }]] as const) {      expect((await http(slug, "POST", "/v1/act", { act: name, args }, ADMIN)).status, name).toBe(403);    }    expect((await http(slug, "POST", "/v1/act", { act: "create", args: { table: "unlock_grant", data: { request_id: requestId } } }, ADMIN)).body).toMatchObject({ code: "unlock_only" });    // A token cannot allow either, the asking one included.    expect((await allowOn(slug, token, dk, requestId, 15)).status).toBe(403);    expect((await rowOf(slug, "unlock_request", requestId)).state).toBe("waiting");    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM window_secret")).toBe(0);    // On a database with no person key yet, the admin cannot plant one to sign with.    const fresh = "window-who-fresh";    expect((await http(fresh, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: OWNER_PHONE, database_id: DATABASE_ID, timezone: "Asia/Kolkata" }, ADMIN)).status).toBe(200);    expect((await http(fresh, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables: [...PERSONAL_TABLES, DIARY], flavour: { flavour: "personal" } }, ADMIN)).status).toBe(200);    const planted = await http(fresh, "POST", "/v1/act", { act: "create", args: { table: "person_key", id: vector.person_public_key.slice(0, 8), data: { public_key: vector.person_public_key, sealed_private_enc: "x", vmk_version: 1 } } }, ADMIN);    expect([planted.status, planted.body.code]).toEqual([403, "owner_only"]);  });});/** RULE (R4): a standing grant binds to the assistant's connection, not its access token: it survives an OAuth refresh of that connection, never reaches another, and ends when the connection is revoked. */describe("R4 the connection: a standing grant across a token refresh", () => {  const slug = "window-refresh";  const dk = crypto.getRandomValues(new Uint8Array(32));  let credential = "";  let id = "";  beforeAll(async () => {    ({ credential } = await object(slug));    id = crypto.randomUUID();    const values = { body: "Kingfisher over the canal" };    expect((await act(slug, credential, "create", { table: DIARY.id, id, data: { written_at: "2026-11-08", ...(await sealRow(dk, id, 1, values)) }, blind: await tokensOf(dk, values) })).status).toBe(200);  }, 120_000);  it("keeps the window across refreshes, never for another connection, and ends it when the connection is revoked", async () => {    const claude = await connect(slug, "Claude");    const other = await connect(slug, "Another client");    const res = await allowOn(slug, credential, dk, await askOn(slug, claude.access), 0);    expect(res.status, JSON.stringify(res.body)).toBe(200);    const grant = String(res.body.grant);    expect(parsed(await tool(slug, claude.access, "get_record_by_table", { table: DIARY.id, id })).data).toMatchObject({ body: "Kingfisher over the canal" });    // Refresh twice: each new access token reads; the old one is revoked and reads nothing.    const once = await refreshOn(slug, claude.clientId, claude.refresh);    expect(parsed(await tool(slug, once.access, "get_record_by_table", { table: DIARY.id, id })).data).toMatchObject({ body: "Kingfisher over the canal" });    const twice = await refreshOn(slug, claude.clientId, once.refresh);    expect(parsed(await tool(slug, twice.access, "list_records", { table: DIARY.id })).records).toHaveLength(1);    expect((await http(slug, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "get_record_by_table", arguments: { table: DIARY.id, id } } }, { authorization: `Bearer ${claude.access}` })).status).toBe(401);    expect(await rowOf(slug, "unlock_grant", grant)).not.toHaveProperty("ended_at");    // Another connection holds nothing of it.    expect(code(await tool(slug, other.access, "get_record_by_table", { table: DIARY.id, id }))).toBe("window_needed");    // Revoking the connection's token ends the standing grant at once.    const tokenId = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'mcp_token' AND json_extract(data, '$.revoked_at') IS NULL AND json_extract(data, '$.name') = 'Claude'").one().id);    expect((await act(slug, credential, "revoke_token", { id: tokenId })).status).toBe(200);    expect(await rowOf(slug, "unlock_grant", grant)).toMatchObject({ ended_by: "token_revoked" });    expect(await sqlCount(slug, "SELECT COUNT(*) AS n FROM window_secret")).toBe(0);  });  it("ends the connection's windows when a spent refresh token is replayed", async () => {    const claude = await connect(slug, "Claude again");    const res = await allowOn(slug, credential, dk, await askOn(slug, claude.access), 0);    const grant = String(res.body.grant);    await refreshOn(slug, claude.clientId, claude.refresh);    const replay = await form(`https://example.test/b/${slug}/oauth/token`, { grant_type: "refresh_token", client_id: claude.clientId, refresh_token: claude.refresh });    expect(replay.status).toBe(400);    expect(await rowOf(slug, "unlock_grant", grant)).toMatchObject({ ended_by: "token_revoked" });  });});/** RULE (R4 briefing): when memory is sealed and no window stands, brief says so in words and files the request; in a window it briefs the opened entries. */describe("R4 brief over sealed memory", () => {  const slug = "window-brief";  const dk = crypto.getRandomValues(new Uint8Array(32));  const MEMORY = { ...(PERSONAL_TABLES.find((t) => t.id === "memory") as Record<string, unknown>), seal: { clear: ["status", "visibility", "origin_kind", "machine", "archived_at", "created_at", "superseded_by"] } };  let credential = "";  let owner = "";  beforeAll(async () => {    ({ credential, owner } = await object(slug, [...PERSONAL_TABLES.filter((t) => t.id !== "memory"), MEMORY, DIARY]));    // The kit lays its own memory definition at sign-in: the sealed one goes on after it.    expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [MEMORY] }, ADMIN)).status).toBe(200);    const id = crypto.randomUUID();    const sealed = await sealRow(dk, id, 1, { slug: "otters-hold-hands", title: "Otters hold hands while they sleep" }, "memory");    const made = await act(slug, credential, "create", { table: "memory", id, data: { status: "active", visibility: "private", origin_kind: "user", ...sealed } });    expect(made.status, JSON.stringify(made.body)).toBe(200);  }, 120_000);  it("answers in words with no window, files the request, and briefs the opened entries once the owner allows", async () => {    const r = parsed(await tool(slug, owner, "brief", { machine: "box" }));    expect(r.code).toBe("window_needed");    expect(String(r.briefing)).toContain("Cotton memory is sealed, and the owner has not opened a window for Claude (claude.ai)");    expect(String(r.briefing)).toContain("call brief again");    expect(String(r.briefing).toLowerCase()).not.toContain("otter");    const request = await rowOf(slug, "unlock_request", String(r.request_id));    // Procedure notes are sealed too the brief asks for both.    expect(request).toMatchObject({ state: "waiting", tables: ["memory", "note"] });    const grant = await buildGrant({ dk, requestId: String(r.request_id), tokenId: String(request.token_id), tables: [["memory", 1], ["note", 1]], minutes: 15, workerPub: fromBase64Url(String(request.worker_pub)), personSeed: hex(vector.person_seed_hex) });    expect((await act(slug, credential, "unlock_allow", { request_id: String(r.request_id), ...grant })).status).toBe(200);    const opened = parsed(await tool(slug, owner, "brief", { machine: "box" }));    expect(opened.code).toBeUndefined();    expect(String(opened.briefing)).toContain("[otters-hold-hands] Otters hold hands while they sleep");  });});/** RULE (owner, 16 Nov 2026: memory stays open): where memory is open, the sealed procedure notes never make a brief refuse or ask the phone. */describe("brief over open memory with sealed notes", () => {  const slug = "window-brief-open";  let credential = "";  let owner = "";  beforeAll(async () => {    ({ credential, owner } = await object(slug, [...PERSONAL_TABLES, DIARY]));    // Memory is sealed by the rule since LAUNCH.md (22 Nov 2026): this database keeps it open, the case this rule is for.    await openTables(slug, ["memory"]);    const made = await act(slug, credential, "create", { table: "memory", id: crypto.randomUUID(), data: { status: "active", visibility: "private", origin_kind: "user", slug: "herons-stand-still", title: "Herons stand still to fish" } });    expect(made.status, JSON.stringify(made.body)).toBe(200);  }, 120_000);  it("briefs the memory at once, with no window and no request", async () => {    const r = parsed(await tool(slug, owner, "brief", { machine: "box" }));    expect(r.code).toBeUndefined();    expect(r.request_id).toBeUndefined();    expect(String(r.briefing)).toContain("[herons-stand-still] Herons stand still to fish");  });});describe("update_todo on a to-do the phone sealed", () => {  // On the emulator (22 Nov 2026) the assistant's update_todo was refused sealed_in_clear on every to-do a phone had  // sealed: it wrote title, notes and completed_at in the clear, as it did before todos were sealed. In a window it  // now opens the row, lays the change over it and seals it again, as update_record does.  const slug = "window-update-todo";  const dk = crypto.getRandomValues(new Uint8Array(32));  let credential = "";  let owner = "";  const id = crypto.randomUUID();  beforeAll(async () => {    ({ credential, owner } = await object(slug));    const values = { title: "Water the balcony plants", notes: "- [ ] the fern", priority: 0 };    const made = await act(slug, credential, "create", { table: "todo", id, data: { status: "open", ...(await sealRow(dk, id, 1, values, "todo")) } });    expect(made.status, JSON.stringify(made.body)).toBe(200);  }, 120_000);  it("changes the title, notes and done in a window, sealed again; outside one it asks for a window", async () => {    expect(code(await tool(slug, owner, "update_todo", { id, title: "Water the plants" }))).toBe("window_needed");    expect(code(await tool(slug, owner, "list_todos", {}))).toBe("window_needed"); // it holds a sealed row    await ageAll(slug);    const asked = parsed(await tool(slug, owner, "request_unlock", { tables: ["todo"], reason: "Keep the to-dos" }));    const allowed = await allowOn(slug, credential, dk, String(asked.request_id), 15, "todo");    expect(allowed.status, JSON.stringify(allowed.body)).toBe(200);    // list_todos opens what it lists: the title the phone sealed, not null.    const listed = parsed(await tool(slug, owner, "list_todos", {}));    expect(listed.todos).toEqual([expect.objectContaining({ id, title: "Water the balcony plants", notes: "- [ ] the fern", status: "open" })]);    const changed = parsed(await tool(slug, owner, "update_todo", { id, title: "Water the plants, changed while you were away", notes: "- [ ] the fern\n- [ ] the basil" }));    expect(changed).toMatchObject({ id, title: "Water the plants, changed while you were away", notes: "- [ ] the fern\n- [ ] the basil", status: "open" });    const stored = await rowOf(slug, "todo", id);    expect(String(stored.sealed_enc)).toMatch(/^s1:/);    expect(JSON.stringify(stored).toLowerCase()).not.toContain("basil");    const { openRow } = await import("../src/seal.ts");    expect(await openRow(await tableKey(dk, DATABASE_ID, "todo", 1), DATABASE_ID, "todo", id, stored)).toMatchObject({ title: "Water the plants, changed while you were away", notes: "- [ ] the fern\n- [ ] the basil" });    const done = parsed(await tool(slug, owner, "update_todo", { id, status: "done" }));    expect(done).toMatchObject({ id, status: "done", title: "Water the plants, changed while you were away" });    expect(done.completed_at).toEqual(expect.any(String));    const after = await rowOf(slug, "todo", id);    expect(after.status).toBe("done");    expect(await openRow(await tableKey(dk, DATABASE_ID, "todo", 1), DATABASE_ID, "todo", id, after)).toMatchObject({ completed_at: expect.any(String) });  });});/** * RULE (owner, live, 22 Nov 2026): a picture sent from the phone is kept in its message's media, and the message is * sealed; get_media opens the message in the assistant's window, as get_record does, and reads its pictures. With no * index (a client whose copy of the tool predates it) it gives the first and says so. Before a window it asks for one. */describe("get_media on a sealed message in a standing window", () => {  const slug = "sealedchatpicture";  const dk = crypto.getRandomValues(new Uint8Array(32));  /** A real 32×24 PNG, so the resizer has an image to read. */  const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAIAAAAUMWhjAAAAJElEQVR4nGM4EaBBU8QwasGoBaMWjFowasGoBaMWjFowNCwAAOj5wC7/fbJHAAAAAElFTkSuQmCC"), (c) => c.charCodeAt(0));  it("reads the message's kept pictures once the window is open, the first when no index is named", async () => {    const { credential, owner } = await object(slug);    const thread = crypto.randomUUID();    const message = crypto.randomUUID();    expect((await act(slug, credential, "create", { table: "thread", id: thread, data: { kind: "group", ...(await sealRow(dk, thread, 1, { title: "Invented group" }, "thread")) } })).status).toBe(200);    const keys = [`${DATABASE_ID}/messages/${thread}/${"a1".repeat(32)}.png`, `${DATABASE_ID}/messages/${thread}/${"b2".repeat(32)}.png`];    for (const key of keys) {      const put = await SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}`, { method: "PUT", headers: { authorization: `Bearer ${credential}`, "content-type": "image/png", "content-length": String(png.length) }, body: png });      expect(put.status, await put.clone().text()).toBe(201);    }    // The shape the owner's row has: media and meta.cotton.pictures, as chat_files::keep leaves them.    const media = keys.map((key, i) => ({ contentType: "image/png", cottonKept: true, height: 24, width: 32, key, kind: "photo", name: `IMG_${i}.png`, sizeBytes: png.length }));    const pictures = keys.map((key, i) => ({ bytes: png.length + 28, file: `${i}`.repeat(32), height: 24, kept: key, key: "k".repeat(43), kind: "photo", mime: "image/png", name: `IMG_${i}.png`, sha256: key.split("/").pop()!.slice(0, 64), width: 32 }));    const sealed = { body: "", media, meta: { cotton: { pictures } }, direction: "out", origin: "live", send_state: "delivered" };    const made = await act(slug, credential, "create", { table: "message", id: message, data: { thread_id: thread, channel: "cotton", sent_at: "2026-11-22T03:00:00.000Z", ...(await sealRow(dk, message, 1, sealed, "message")) } });    expect(made.status, JSON.stringify(made.body)).toBe(200);    // No window yet: it asks for one, as any read of a sealed table does.    expect(code(await tool(slug, owner, "get_media", { table: "message", id: message, width: 300 }))).toBe("window_needed");    await ageAll(slug);    const asked = parsed(await tool(slug, owner, "request_unlock", { tables: ["message"], reason: "Look at the pictures" }));    const allowed = await allowOn(slug, credential, dk, String(asked.request_id), 0, "message");    expect(allowed.body).toMatchObject({ standing: true });    // The owner's call, index dropped by the client: the first picture, said so.    const first = await tool(slug, owner, "get_media", { table: "message", id: message, width: 300 });    expect(first.isError, first.content[0]?.text).toBe(false);    expect(JSON.parse(first.content[0]!.text)).toMatchObject({ table: "message", id: message, column: "media", key: keys[0], content_type: "image/png", index: 0, files: 2, note: "the first of 2 files; ask with index 1 for the other", drawn: { width: 300, content_type: "image/webp" } });    const second = await tool(slug, owner, "get_media", { table: "message", id: message, index: 1 });    expect(JSON.parse(second.content[0]!.text)).toMatchObject({ key: keys[1], index: 1, files: 2 });    expect(JSON.parse(second.content[0]!.text)).not.toHaveProperty("note");    expect((second.content[1] as { type: string }).type).toBe("image");  }, 180_000);  // Owner's decision, 22 Nov 2026: a kept chat picture is sealed on the phone (f1 under TFR(message)); a window over messages opens it.  it("opens a sealed kept picture inside the window, says plainly when an older app's window cannot, and never lets plain bytes replace it", async () => {    const at = `${slug}sealed`;    const { credential, owner } = await object(at);    const thread = crypto.randomUUID();    const message = crypto.randomUUID();    expect((await act(at, credential, "create", { table: "thread", id: thread, data: { kind: "group", ...(await sealRow(dk, thread, 1, { title: "Invented group" }, "thread")) } })).status).toBe(200);    const key = `${DATABASE_ID}/messages/${thread}/${"c3".repeat(32)}.png`;    const parts = await sealF1(await personFileKey(await tableFileRoot(dk, DATABASE_ID, "message"), key), crypto.getRandomValues(new Uint8Array(7)), key, png);    const sealedFile = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));    parts.reduce((o, p) => (sealedFile.set(p, o), o + p.length), 0);    const put = (body: Uint8Array, type: string) => SELF.fetch(`https://example.test/b/${at}/v1/media/${key}`, { method: "PUT", headers: { authorization: `Bearer ${credential}`, "content-type": type, "content-length": String(body.length) }, body });    expect((await put(sealedFile, "application/vnd.cotton.f1")).status).toBe(201);    // An app from before sends the plain bytes: the sealed file stands.    const plainAgain = await put(png, "image/png");    expect(await plainAgain.json()).toMatchObject({ stored: false });    const media = [{ contentType: "image/png", cottonKept: true, height: 24, width: 32, key, kind: "photo", name: "IMG_9.png", sizeBytes: png.length }];    const made = await act(at, credential, "create", { table: "message", id: message, data: { thread_id: thread, channel: "cotton", sent_at: "2026-11-22T03:00:00.000Z", ...(await sealRow(dk, message, 1, { body: "", media, direction: "out" }, "message")) } });    expect(made.status, JSON.stringify(made.body)).toBe(200);    // A window allowed by an app from before carries no files root: said so, by step.    await ageAll(at);    const old = parsed(await tool(at, owner, "request_unlock", { tables: ["message"], reason: "Look at the picture" }));    expect((await allowOn(at, credential, dk, String(old.request_id), 0, "message", 1, true)).status).toBe(200);    const refused = await tool(at, owner, "get_media", { table: "message", id: message });    expect(refused.isError).toBe(true);    expect(refused.content[0]!.text).toMatch(/too old to open it.*\[get_media r3, step sealed file\]/s);    await tool(at, owner, "end_unlock", {});    // The window from this app opens it: whole, and drawn at a size.    await ageAll(at);    const asked = parsed(await tool(at, owner, "request_unlock", { tables: ["message"], reason: "Look at the picture" }));    expect((await allowOn(at, credential, dk, String(asked.request_id), 0, "message")).status).toBe(200);    const whole = await tool(at, owner, "get_media", { table: "message", id: message });    expect(whole.isError, whole.content[0]?.text).toBe(false);    expect(JSON.parse(whole.content[0]!.text)).toMatchObject({ key, content_type: "image/png", bytes: png.length, sealed: true });    expect((whole.content[1] as unknown as { data: string }).data).toBe(btoa(String.fromCharCode(...png)));    const drawn = await tool(at, owner, "get_media", { table: "message", id: message, width: 16 });    expect(JSON.parse(drawn.content[0]!.text)).toMatchObject({ sealed: true, drawn: { width: 16, content_type: "image/webp" } });    // The phone's pass finds no plain kept picture left here.    const listed = await SELF.fetch(`https://example.test/b/${at}/v1/media-plain?kind=messages`, { headers: { authorization: `Bearer ${credential}` } });    expect(await listed.json()).toEqual({ files: [], next: null });  }, 180_000);});// AVATAR SEAL (MEDIA SEAL FINDINGS (1), 27 Nov 2026): a face is sealed on the device (f1 under TFR(person)); a window over// person opens it, and a face still held plain from before is read only in such a window too: no window, no face.describe("get_media on a person's face", () => {  const dk = crypto.getRandomValues(new Uint8Array(32));  const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAIAAAAUMWhjAAAAJElEQVR4nGM4EaBBU8QwasGoBaMWjFowasGoBaMWjFowNCwAAOj5wC7/fbJHAAAAAElFTkSuQmCC"), (c) => c.charCodeAt(0));  it("opens a sealed face in a window over person, reads an old plain face only in one, and lists the plain faces for the reseal", async () => {    const at = "windowfaces";    const { credential, owner } = await object(at);    const person = crypto.randomUUID();    const before = crypto.randomUUID();    const sealedKey = `${DATABASE_ID}/people/${person}/${"5a".repeat(32)}.png`;    const plainKey = `${DATABASE_ID}/people/${before}/whatsapp/${"6b".repeat(32)}.png`;    const parts = await sealF1(await personFileKey(await tableFileRoot(dk, DATABASE_ID, "person"), sealedKey), crypto.getRandomValues(new Uint8Array(7)), sealedKey, png);    const sealedFile = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));    parts.reduce((o, p) => (sealedFile.set(p, o), o + p.length), 0);    const put = (key: string, body: Uint8Array, type: string) => SELF.fetch(`https://example.test/b/${at}/v1/media/${key}`, { method: "PUT", headers: { authorization: `Bearer ${credential}`, "content-type": type, "content-length": String(body.length) }, body });    expect((await put(sealedKey, sealedFile, "application/vnd.cotton.f1")).status).toBe(201);    expect((await put(plainKey, png, "image/png")).status).toBe(201);    // An app from before sends the face plain again: the sealed one stands.    expect(await (await put(sealedKey, png, "image/png")).json()).toMatchObject({ stored: false });    for (const [id, key, name] of [[person, sealedKey, "Invented Face"], [before, plainKey, "Invented Before"]] as const) {      const made = await act(at, credential, "create", { table: "person", id, data: { avatar_key: key, ...(await sealRow(dk, id, 1, { full_name: name }, "person")) } });      expect(made.status, JSON.stringify(made.body)).toBe(200);    }    // No window: neither face, sealed nor plain.    expect(code(await tool(at, owner, "get_media", { table: "person", id: person }))).toBe("window_needed");    expect(code(await tool(at, owner, "get_media", { table: "person", id: before }))).toBe("window_needed");    // AVATAR SEAL 2 (1): nor on the plain media route, by the assistant's owner-scope token; the owner's device as before.    const raw = (key: string, bearer: string, method = "GET") => SELF.fetch(`https://example.test/b/${at}/v1/media/${key}`, { method, headers: { authorization: `Bearer ${bearer}` } });    for (const key of [plainKey, sealedKey]) {      for (const method of ["GET", "HEAD"]) {        const refused = await raw(key, owner, method);        expect(refused.status, key).toBe(403);        if (method === "GET") expect(await refused.json()).toMatchObject({ code: "window_needed" });      }      expect((await raw(key, credential)).status).toBe(200);    }    const streamed = await SELF.fetch(`https://example.test/b/${at}/v1/media/stream`, { method: "POST", headers: { authorization: `Bearer ${owner}`, "content-type": "application/json" }, body: JSON.stringify({ key: plainKey }) });    expect(streamed.status).toBe(403);    // A window allowed by an app from before carries no files root: the sealed face is refused by step, the plain one read.    await ageAll(at);    const old = parsed(await tool(at, owner, "request_unlock", { tables: ["person"], reason: "Look at a face" }));    expect((await allowOn(at, credential, dk, String(old.request_id), 0, "person", 1, true)).status).toBe(200);    const refused = await tool(at, owner, "get_media", { table: "person", id: person });    expect(refused.isError).toBe(true);    expect(refused.content[0]!.text).toMatch(/too old to open it.*\[get_media r3, step sealed file\]/s);    await tool(at, owner, "end_unlock", {});    // This app's window opens the sealed face, and reads the plain one from before.    await ageAll(at);    const asked = parsed(await tool(at, owner, "request_unlock", { tables: ["person"], reason: "Look at a face" }));    expect((await allowOn(at, credential, dk, String(asked.request_id), 0, "person")).status).toBe(200);    const face = await tool(at, owner, "get_media", { table: "person", id: person });    expect(face.isError, face.content[0]?.text).toBe(false);    expect(JSON.parse(face.content[0]!.text)).toMatchObject({ table: "person", column: "avatar_key", key: sealedKey, content_type: "image/png", bytes: png.length, sealed: true });    expect((face.content[1] as unknown as { data: string }).data).toBe(btoa(String.fromCharCode(...png)));    const plain = await tool(at, owner, "get_media", { table: "person", id: before });    expect(plain.isError, plain.content[0]?.text).toBe(false);    expect(JSON.parse(plain.content[0]!.text)).toMatchObject({ key: plainKey, content_type: "image/png" });    // Inside the window the plain route answers the token too.    expect((await raw(plainKey, owner)).status).toBe(200);    // The reseal's list names the plain face only, to the owner's devices.    const listed = await SELF.fetch(`https://example.test/b/${at}/v1/media-plain?kind=people`, { headers: { authorization: `Bearer ${credential}` } });    expect(await listed.json()).toEqual({ files: [{ key: plainKey, bytes: png.length }], next: null });  }, 240_000);});// AVATAR SEAL 4 (4, 5): a read inside an open window by a tool other than get_media. export_open_bundle reads files// through ctx.media, as get_media does; its ZIP is a plain document that outlives the window, so a file of any sealed// kind is left out of it, inside a window over that kind or not, and the answer counts what was left out.describe("an open bundle inside a window over person", () => {  it("leaves a person's face out of the ZIP that the window would let get_media read", async () => {    const at = "windowfacebundle";    const dk = crypto.getRandomValues(new Uint8Array(32));    const { credential, owner } = await object(at);    // The books kit reads books and their highlights and keeps its ZIP as a document: all opened, so the window asked    // is over person alone.    await openTables(at, ["book", "highlight", "document"]);    const person = crypto.randomUUID();    const faceKey = `${DATABASE_ID}/people/${person}/${"7c".repeat(32)}.png`;    const face = utf8.encode("\x89PNG an invented face from before");    const laid = await SELF.fetch(`https://example.test/b/${at}/v1/media/${faceKey}`, { method: "PUT", headers: { authorization: `Bearer ${credential}`, "content-type": "image/png", "content-length": String(face.length) }, body: face });    expect(laid.status).toBe(201);    const made = await act(at, credential, "create", { table: "person", id: person, data: { avatar_key: faceKey, ...(await sealRow(dk, person, 1, { full_name: "Invented Face" }, "person")) } });    expect(made.status, JSON.stringify(made.body)).toBe(200);    await put(at, [{ table: "book", data: { title: "A cover pointed at a face", status: "want_to_read", cover: faceKey } }]);    await ageAll(at);    const asked = parsed(await tool(at, owner, "request_unlock", { tables: ["person"], reason: "Look at a face" }));    expect((await allowOn(at, credential, dk, String(asked.request_id), 0, "person")).status).toBe(200);    // The window is open: get_media reads the face.    expect(parsed(await tool(at, owner, "get_media", { table: "person", id: person }))).toMatchObject({ key: faceKey });    // The bundle, in the same window, lays the book and leaves the face out.    const bundle = parsed(await tool(at, owner, "export_open_bundle", { kit: "books" }));    expect(bundle.sealed_left_out).toBe(1);    expect(bundle.missing_media).toEqual([]);    const document = await runInDurableObject(stub(at), (_i, state) => JSON.parse(state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'document' AND id = ?", String(bundle.document)).one().data) as { storage_path: string });    const zip = new Uint8Array(await (await env.MEDIA.get(bucketKey(document.storage_path, DATABASE_ID, at)))!.arrayBuffer());    const needle = new TextDecoder("latin1").decode(face);    expect(new TextDecoder("latin1").decode(zip).includes(needle), "the face's bytes are in no entry").toBe(false);  }, 240_000);});describe("the plain kept pictures a phone's pass seals", () => {  it("lists only this database's plain files of the kind, a page at a time, to the owner's devices alone", async () => {    const slug = "plainkept";    const { credential, owner } = await object(slug);    const put = (key: string, body: Uint8Array, type: string) => SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}`, { method: "PUT", headers: { authorization: `Bearer ${credential}`, "content-type": type, "content-length": String(body.length) }, body });    const keys = ["a", "b", "c"].map((n) => `${DATABASE_ID}/messages/t-1/${n.repeat(64)}.png`);    for (const key of keys) expect((await put(key, utf8.encode(`plain ${key}`), "image/png")).status).toBe(201);    expect((await put(`${DATABASE_ID}/messages/t-2/${"d".repeat(64)}.png`, utf8.encode("CTF1sealed bytes"), "application/vnd.cotton.f1")).status).toBe(201);    expect((await put(`${DATABASE_ID}/photos/${"e".repeat(64)}.png`, utf8.encode("a photo"), "image/png")).status).toBe(201);    const list = (q: string, bearer = credential) => SELF.fetch(`https://example.test/b/${slug}/v1/media-plain?${q}`, { headers: { authorization: `Bearer ${bearer}` } });    const first = (await (await list("kind=messages&limit=2")).json()) as { files: { key: string; bytes: number }[]; next: string | null };    expect(first.files.map((f) => f.key)).toEqual(keys.slice(0, 2));    expect(first.next).toBe(keys[1]);    const rest = (await (await list(`kind=messages&limit=2&after=${encodeURIComponent(first.next!)}`)).json()) as typeof first;    expect(rest).toEqual({ files: [{ key: keys[2], bytes: utf8.encode(`plain ${keys[2]}`).length }], next: null });    expect((await list("kind=photos")).status).toBe(400);    expect((await list("kind=messages", owner)).status).toBe(403);  }, 120_000);});/** * Memory as it would be sealed: the seal block taken out again (owner, 16 Nov 2026: memory stays open; coordinator, * 22 Nov 2026). These tests lay it themselves, so the sealing path stays held and the switch is one small change later * (crates/cotton-core/src/seal/rule_tests.rs memory_stays_open_until_the_owner_approves_sealing guards the rule). */const MEMORY_SEALED = {  ...(PERSONAL_TABLES.find((t) => t.id === "memory") as Record<string, unknown>),  seal: { clear: ["status", "visibility", "origin_kind", "machine", "reviewed_at", "archived_at", "created_at", "superseded_by"], blind: ["title"], blind_exact: ["slug"] },};/** Lays the sealed memory definition over the kit's open one (the kit lays its own at sign-in). */async function sealMemory(slug: string): Promise<void> {  expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [MEMORY_SEALED] }, ADMIN)).status).toBe(200);}/** * RULE (e2e rulings R1, R4), WHEN MEMORY IS SEALED (it is not: owner, 16 Nov 2026): the memory table sealed. Every memory tool reads it * only inside the owner's window for the assistant and answers window_needed without one, never an entry; in a window it * reads the opened entries, at the owner's size, and what it writes is sealed with the table's key, so the object keeps * no sentence in the clear and the next read in the window opens it. An entry a phone has not swept yet (still clear) * reads as it is and is sealed whole by its next change. */describe("memory sealed: every memory tool inside the window", () => {  const slug = "window-memory-tools";  const dk = crypto.getRandomValues(new Uint8Array(32));  // The owner's memory holds 341 entries and 1,220 links (22 Nov 2026): this is a little more.  const SIZE = 400;  const pad = (n: number) => String(n).padStart(12, "0");  const idOf = (i: number) => `00000000-0000-4000-8000-${pad(i)}`;  // Spread over 13 projects, as the owner's are; the Owner section (no project) keeps one entry.  const PROJECTS = 13;  const projectId = (p: number) => `00000000-0000-4000-8000-ffffffffff${String(p).padStart(2, "0")}`;  const clear = "00000000-0000-4000-8000-eeeeeeeeeeee";  let credential = "";  let owner = "";  beforeAll(async () => {    ({ credential, owner } = await object(slug, [...PERSONAL_TABLES.filter((t) => t.id !== "memory"), MEMORY_SEALED, DIARY]));    await sealMemory(slug);    const at = (i: number) => new Date(Date.UTC(2026, 9, 1) + i * 60_000).toISOString();    const rows: Record<string, unknown>[] = Array.from({ length: PROJECTS }, (_, p) => ({ verb: "put", table: "project", id: projectId(p), data: { slug: p ? `invented-project-${p}` : "invented-garden", name: p ? `Invented project ${p}` : "Invented garden", repos: [], status: "active" } }));    for (let i = 0; i < SIZE; i++) {      const id = idOf(i);      const words = i === 7 ? { slug: "otters-hold-hands", title: "Otters hold hands while they sleep" } : { slug: `invented-entry-${i}`, title: `Invented entry ${i} about ${i % 2 ? "tulips" : "ferns"}` };      rows.push({ verb: "put", table: "memory", id, data: { status: "active", visibility: "private", origin_kind: "user", ...(await sealRow(dk, id, 1, { ...words, body: "" }, "memory")) }, created_at: at(i), updated_at: at(i) });      rows.push({ verb: "put", table: "project_link", id: `00000000-0000-4000-9000-${pad(i)}`, data: { project: projectId(i % PROJECTS), record_kind: "memory", record_id: id, applied_by: "user", pinned: false, position: i } });    }    // One entry no phone has swept yet: written while memory was open.    rows.push({ verb: "put", table: "memory", id: clear, data: { status: "active", visibility: "private", origin_kind: "user", slug: "herons-stand-still", title: "Herons stand still to fish", body: "" }, created_at: at(SIZE), updated_at: at(SIZE) });    for (let i = 0; i < rows.length; i += 200) await put(slug, rows.slice(i, i + 200));  }, 600_000);  it("answers window_needed with no window, and no entry", async () => {    for (const [name, args] of [["recall", { q: "otters" }], ["remember", { title: "Invented: kingfishers dive", decision: { action: "add" } }], ["memory_archive", { slug: "otters-hold-hands" }], ["get_record", { kind: "memory", id: idOf(7) }]] as const) {      const r = await tool(slug, owner, name, args);      expect(code(r), name).toBe("window_needed");      expect(r.content[0]!.text.toLowerCase(), name).not.toContain("otter");    }  });  it("in the window reads the opened entries at size, and seals what it writes", async () => {    const asked = await tool(slug, owner, "recall", {});    const requestId = String(asked.structuredContent?.request_id);    const request = await rowOf(slug, "unlock_request", requestId);    const grant = await buildGrant({ dk, requestId, tokenId: String(request.token_id), tables: [["memory", 1]], minutes: 15, workerPub: fromBase64Url(String(request.worker_pub)), personSeed: hex(vector.person_seed_hex) });    expect((await act(slug, credential, "unlock_allow", { request_id: requestId, ...grant })).status).toBe(200);    let started = Date.now();    const newest = parsed(await tool(slug, owner, "recall", { limit: 5 })) as { memories: { slug: string }[] };    const recallMs = Date.now() - started;    expect(newest.memories.map((m) => m.slug)).toEqual(["herons-stand-still", "invented-entry-399", "invented-entry-398", "invented-entry-397", "invented-entry-396"]);    const found = parsed(await tool(slug, owner, "recall", { q: "otters" })) as { memories: { slug: string; title: string }[] };    expect(found.memories.map((m) => m.title)).toEqual(["Otters hold hands while they sleep"]);    const inProject = parsed(await tool(slug, owner, "recall", { project: "invented-garden", limit: 300 })) as { memories: unknown[] };    expect(inProject.memories.length).toBe(Math.ceil(SIZE / PROJECTS));    started = Date.now();    const made = parsed(await tool(slug, owner, "remember", { title: "Invented: kingfishers dive for minnows at dawn", project: "invented-garden", decision: { action: "add" } }));    const rememberMs = Date.now() - started;    const slugMade = String(made.slug);    const stored = (await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'memory' AND json_extract(data, '$.status') = 'active' ORDER BY created_at DESC LIMIT 1").one().data)) as string;    expect(JSON.parse(stored)).toMatchObject({ seal_v: 1, status: "active", origin_kind: "agent" });    expect(JSON.parse(stored).title, "the sentence is sealed").toBeUndefined();    expect((parsed(await tool(slug, owner, "recall", { q: "kingfishers" })) as { memories: { slug: string }[] }).memories.map((m) => m.slug)).toEqual([slugMade]);    // A change re-seals the whole entry; a clear entry is sealed whole by its first change.    expect(parsed(await tool(slug, owner, "memory_update", { slug: slugMade, title: "Invented: kingfishers dive for minnows at first light" })).updated).toBe(true);    expect(parsed(await tool(slug, owner, "memory_update", { slug: "herons-stand-still", title: "Herons stand very still to fish" })).updated).toBe(true);    expect(await rowOf(slug, "memory", clear)).toMatchObject({ seal_v: 1 });    expect((await rowOf(slug, "memory", clear)).title).toBeUndefined();    const brief = parsed(await tool(slug, owner, "get_record", { kind: "memory", id: clear }));    expect(brief.title).toBe("Herons stand very still to fish");    // Archive and a link's restore change clear columns alone.    expect(parsed(await tool(slug, owner, "memory_archive", { slug: "otters-hold-hands" })).archived).toBe(true);    expect(await rowOf(slug, "memory", idOf(7))).toMatchObject({ status: "archived" });    const linked = parsed(await tool(slug, owner, "link_to_project", { project: "invented-garden", records: [{ kind: "memory", id: idOf(7) }] })) as { records: { title: string; restored?: boolean }[] };    expect(linked.records[0]).toMatchObject({ title: "Otters hold hands while they sleep", restored: true });    // Nothing the object keeps (rows, the change log, the act log) says a sentence the assistant wrote.    const all = (await kept(slug)).toLowerCase();    for (const word of ["kingfishers", "minnows", "very still"]) expect(holdsWord(all, word), word).toBe(false);    console.log(`memory sealed at size: ${SIZE + 1} entries, recall ${recallMs} ms, remember ${rememberMs} ms`);  }, 300_000);});/** * RULE, WHEN MEMORY IS SEALED (it is not: owner, 16 Nov 2026): the day the rule seals memory, the owner's entries are still clear on the object * until a phone's next pass seals them (and hands Your Claude's grant the key in the same pass). Meanwhile every memory * tool reads them as the object holds them, for every connected assistant, and asks nobody for a window: reading a * clear row opens nothing. What an assistant writes then is sealed at arrival to the owner's key (R2), never kept clear; * once an entry is sealed, a connection with no key is asked for the window as with any sealed table. */describe("memory sealed by the rule, before any device has sealed an entry", () => {  const slug = "window-memory-presweep";  let owner = "";  beforeAll(async () => {    ({ owner } = await personalObject(slug, { arrival: true }));    await sealMemory(slug);    await put(slug, [      { verb: "put", table: "memory", id: crypto.randomUUID(), data: { slug: "herons-stand-still", title: "Herons stand still to fish", body: "", status: "active", visibility: "private", origin_kind: "user" } },      { verb: "put", table: "memory", id: crypto.randomUUID(), data: { slug: "owls-turn-their-heads", title: "Owls turn their heads three quarters round", body: "", status: "active", visibility: "private", origin_kind: "user" } },    ]);  }, 120_000);  it("briefs and recalls the clear entries with no window and no request; a remembered entry is sealed at arrival", async () => {    const briefed = parsed(await tool(slug, owner, "brief", { machine: "box" }));    expect(briefed.code).toBeUndefined();    expect(String(briefed.briefing)).toContain("[herons-stand-still] Herons stand still to fish");    const found = parsed(await tool(slug, owner, "recall", { q: "owls" })) as { memories: { slug: string }[] };    expect(found.memories.map((m) => m.slug)).toEqual(["owls-turn-their-heads"]);    expect(await sqlCount(slug, "SELECT count(*) AS n FROM rows WHERE table_id = 'unlock_request'"), "nobody was asked").toBe(0);    const made = parsed(await tool(slug, owner, "remember", { title: "Invented: kingfishers dive for minnows at dawn", decision: { action: "add" } }));    expect(made.action).toBe("add");    const kept = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'memory' AND json_extract(data, '$.seal_v') IS NOT NULL").toArray().map((r) => JSON.parse(r.data) as Record<string, unknown>));    expect(kept.length, "the new entry is sealed at arrival").toBe(1);    expect(kept[0]!.title).toBeUndefined();    // Now an entry is sealed and this connection holds no key: the brief asks for the window in words, as for any sealed table.    const asked = parsed(await tool(slug, owner, "brief", { machine: "box" }));    expect(["window_needed", "window_declined"]).toContain(asked.code);    expect(String(asked.briefing).toLowerCase()).not.toContain("herons");  }, 300_000);});