404 lines · 30.8 KB · TypeScriptRaw
/** * MEMORY LOCK (coordinator, 23 Nov 2026, owner-approved; assets/design/shared/MEMORY-LOCK.md, src/memory_lock.ts). * One invented account, as large as the owner's memory (341 entries on 22 Nov; 350 here over About you and three * projects): the switch off by default, gate 1 refusing a token with no grant in plain words and filing its card, * the owner's Allow, the switch on, gate 2 holding every seal until the phone hands memory's key, the sweep, and then * the same briefing text, byte for byte, through the hook's token and a lane minted from it. An ungranted token is * refused cleanly. Every key is made here; every row is invented. */import { env, runInDurableObject } from "cloudflare:test";import { beforeAll, describe, expect, it } from "vitest";import vector from "../../../crates/cotton-conformance/vectors/seal/agent_grant.json";import { agentStatement, policy } from "../src/agent.ts";import { blindKey, bodyAad, bucket, dekAad, exactToken, tableKey, textTokens } from "../src/seal.ts";import { tableFileRoot } from "../src/table_files.ts";import { fromBase64Url, toBase64Url } from "../src/vault.ts";import { ADMIN, DATABASE_ID, http, mint, OWNER_PHONE, PERSONAL_TABLES, PERSONAL_TOOLS, publishPersonKey, put, tool, type ToolResult } from "./personal.ts";import { holdsWord } from "./clear-word.ts";const utf8 = new TextEncoder();const hex = (h: string): Uint8Array => Uint8Array.from(h.match(/../g)!.map((b) => parseInt(b, 16)));const PERSON_SEED = new Uint8Array(32).fill(7);const X25519_PKCS8 = hex("302e020100300506032b656e04220420");const ED25519_PKCS8 = hex("302e020100300506032b657004220420");async function okp(prefix: Uint8Array, secret: Uint8Array, name: "X25519" | "Ed25519", uses: string[]): Promise<{ key: CryptoKey; pub: Uint8Array }> { const pkcs8 = new Uint8Array(48); pkcs8.set(prefix); pkcs8.set(secret, 16); const key = await crypto.subtle.importKey("pkcs8", pkcs8, { name }, true, uses as Parameters<typeof crypto.subtle.importKey>[4]); const jwk = (await crypto.subtle.exportKey("jwk", key)) as JsonWebKey; return { key, pub: fromBase64Url(jwk.x!) };}async function wrapWith(ephemeral: Uint8Array, nonce: Uint8Array, recipientPub: Uint8Array, plain: Uint8Array): Promise<string> { const eph = await okp(X25519_PKCS8, ephemeral, "X25519", ["deriveBits"]); const peer = await crypto.subtle.importKey("raw", recipientPub, { name: "X25519" }, false, []); const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: peer } as unknown as SubtleCryptoDeriveKeyAlgorithm, eph.key, 256)); const salt = new Uint8Array(64); salt.set(eph.pub); salt.set(recipientPub, 32); const ikm = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]); const k = await crypto.subtle.importKey("raw", await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: utf8.encode("cotton-vault-wrap-v1") }, ikm, 256), "AES-GCM", false, ["encrypt"]); const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: recipientPub }, k, plain)); const out = new Uint8Array(32 + 12 + body.length); out.set(eph.pub); out.set(nonce, 32); out.set(body, 44); return `w1:${toBase64Url(out)}`;}function canonical(v: unknown): string { if (v && typeof v === "object" && !Array.isArray(v)) { const o = v as Record<string, unknown>; return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`).join(",")}}`; } return JSON.stringify(v);}/** The keys of `tables` (every version up to each one's), as the bundle names them for a member. */async function bundleOf(dk: Uint8Array, memberId: string, tables: [string, number][]): Promise<string> { const keys: Record<string, Record<string, string>> = {}; const blind: Record<string, string> = {}; for (const [t, v] of tables) { keys[t] = {}; for (let n = 1; n <= v; n++) keys[t]![String(n)] = toBase64Url(await tableKey(dk, DATABASE_ID, t, n)); blind[t] = toBase64Url(await blindKey(dk, DATABASE_ID, t)); } // grant.rs: a bundle naming message carries the message table's files root (a kept chat picture opens with it). const files = keys.message ? { files: { message: toBase64Url(await tableFileRoot(dk, DATABASE_ID, "message")) } } : {}; return canonical({ request_id: memberId, token_id: memberId, keys, blind, ...files });}/** `seal::agent::build_agent_grant`: wrapped to the member key, the policy signed. */async function agentGrant(o: { dk: Uint8Array; memberId: string; memberPub: string; tables: [string, number][]; withheld?: string[]; seed?: Uint8Array; ephemeral?: Uint8Array; nonce?: Uint8Array }): Promise<{ tables: string[]; withheld: string[]; wrapped: string; signer: string; sig: string }> { const withheld = policy(o.withheld ?? []); const wrapped = await wrapWith(o.ephemeral ?? crypto.getRandomValues(new Uint8Array(32)), o.nonce ?? crypto.getRandomValues(new Uint8Array(12)), fromBase64Url(o.memberPub), utf8.encode(await bundleOf(o.dk, o.memberId, o.tables))); const person = await okp(ED25519_PKCS8, o.seed ?? PERSON_SEED, "Ed25519", ["sign"]); const statement = await agentStatement(DATABASE_ID, o.memberId, o.memberPub, withheld, wrapped); const sig = toBase64Url(new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, person.key, utf8.encode(statement)))); return { tables: o.tables.map(([t]) => t).sort(), withheld, wrapped, signer: toBase64Url(person.pub).slice(0, 8), sig };}async function gcm(key: Uint8Array, plain: Uint8Array, aad: string): Promise<string> { const nonce = crypto.getRandomValues(new Uint8Array(12)); const k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]); const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: utf8.encode(aad) }, k, plain)); const out = new Uint8Array(12 + body.length); out.set(nonce); out.set(body, 12); return toBase64Url(out);}async function sealRow(dk: Uint8Array, id: string, v: number, sealed: Record<string, unknown>, table = "memory"): Promise<Record<string, unknown>> { const text = canonical(sealed); const padded = text + " ".repeat(bucket(utf8.encode(text).length) - utf8.encode(text).length); const dek = crypto.getRandomValues(new Uint8Array(32)); return { sealed_enc: `s1:${await gcm(dek, utf8.encode(padded), bodyAad(DATABASE_ID, table, id))}`, dek_enc: `d1:${await gcm(await tableKey(dk, DATABASE_ID, table, v), dek, dekAad(DATABASE_ID, table, id, v))}`, seal_v: v, };}// ── 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}` });}async function count(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>;}// ── the invented account ──────────────────────────────────────────────const SIZE = 350;/** Entries an assistant wrote and archived before the lock. */const ARCHIVED = 21;const PROJECTS = ["invented-garden", "invented-kiln", "invented-boat"];const REPO = "https://git.example.test/invented/garden";const pad = (n: number) => String(n).padStart(12, "0");const memoryId = (i: number) => `00000000-0000-4000-8000-${pad(i)}`;const projectId = (p: number) => `00000000-0000-4000-8000-ffffffffff${String(p).padStart(2, "0")}`;const words = (i: number) => i === 3 ? { slug: "otters-hold-hands", title: "Otters hold hands while they sleep", body: "So they do not drift apart on the current." } : { slug: `invented-entry-${i}`, title: `Invented entry ${i} about ${i % 2 ? "tulips" : "ferns"}`, body: "" };async function lockOf(slug: string, auth = ADMIN, excuse?: string[]) { return http<{ lock: unknown; ready: boolean; state: string; readers: { token_id: string; name: string; verdict: string; says: string; read_memory_at: string | null }[]; open_entries: number; sealed_entries: number }>(slug, "GET", `/v1/admin/memory-lock${excuse ? `?excuse=${excuse.join(",")}` : ""}`, undefined, auth);}async function sweep(slug: string, credential: string, dk: Uint8Array, most = Infinity): Promise<{ sealed: number; refused: Record<string, number> }> { const all = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string; version: number; data: string }>("SELECT id, version, data FROM rows WHERE table_id = 'memory' AND deleted = 0 AND json_extract(data, '$.sealed_enc') IS NULL").toArray()); const rows = all.slice(0, most); const bk = await blindKey(dk, DATABASE_ID, "memory"); const refused: Record<string, number> = {}; let sealed = 0; for (const r of rows) { const d = JSON.parse(r.data) as Record<string, unknown>; const inside: Record<string, unknown> = {}; const clear: Record<string, unknown> = {}; for (const [k, v] of Object.entries(d)) (["status", "visibility", "origin_kind", "machine", "reviewed_at", "archived_at", "created_at", "superseded_by"].includes(k) ? clear : inside)[k] = v; const blind = [...(await textTokens(bk, "title", String(inside.title ?? "")))]; const exact = await exactToken(bk, "slug", String(inside.slug ?? "")); if (exact) blind.push(exact); const res = await act(slug, credential, "seal", { table: "memory", id: r.id, expect_version: r.version, data: { ...clear, ...(await sealRow(dk, r.id, 1, inside)) }, blind }); if (res.status === 200) sealed++; else refused[String(res.body.code)] = (refused[String(res.body.code)] ?? 0) + 1; } return { sealed, refused };}const briefing = (r: ToolResult): string => String(parsed(r).briefing);const sansUpdated = (text: string): string => text.replace(/"updatedAt":"[^"]*"/g, "");describe("the memory lock on an invented account", () => { const slug = "memory-lock"; const dk = crypto.getRandomValues(new Uint8Array(32)); let credential = ""; let hook = ""; let importer = ""; let before = { brief: "", project: "", recall: "", recallBody: "", tulips: "" }; beforeAll(async () => { expect((await http(slug, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: OWNER_PHONE, database_id: DATABASE_ID, timezone: "Asia/Kolkata" }, ADMIN)).status).toBe(200); // The kit's memory as the rule leaves it: open (pending). const defs = await http(slug, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables: PERSONAL_TABLES, flavour: { flavour: "personal" } }, ADMIN); expect(defs.status, JSON.stringify(defs.body)).toBe(200); expect(PERSONAL_TABLES.find((t) => t.id === "memory")!.seal, "memory is open in the kit").toBeUndefined(); const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: "phone" }); const signed = await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "phone" }); credential = signed.body.credential; await publishPersonKey(slug, credential, vector.person_public_key); await runInDurableObject(stub(slug), (instance) => (instance as unknown as { store: { setMeta(k: string, v: string): void } }).store.setMeta("agent_grant", "on")); // The SessionStart hook's pasted token (memory-mirror.json) and a Mac importer's, which never reads memory. hook = await mint(slug, credential, "invented-mac hook", ["owner"]); importer = await mint(slug, credential, "invented-mac mail importer", ["write"]); const at = (i: number) => new Date(Date.UTC(2026, 9, 1) + i * 60_000).toISOString(); const rows: Record<string, unknown>[] = PROJECTS.map((p, n) => ({ verb: "put", table: "project", id: projectId(n), data: { slug: p, name: p.replace("invented-", "Invented "), repos: n === 0 ? [REPO] : [], status: "active" } })); for (let i = 0; i < SIZE; i++) { rows.push({ verb: "put", table: "memory", id: memoryId(i), data: { status: "active", visibility: "private", origin_kind: "user", ...words(i) }, created_at: at(i), updated_at: at(i) }); // A tenth are About you (no project); the rest over the three projects. if (i % 10) rows.push({ verb: "put", table: "project_link", id: `00000000-0000-4000-9000-${pad(i)}`, data: { project: projectId(i % 3), record_kind: "memory", record_id: memoryId(i), applied_by: "user", pinned: i < 4, position: i } }); } for (let i = 0; i < rows.length; i += 200) await put(slug, rows.slice(i, i + 200)); // As on the owner's account (24 Nov 2026): entries an assistant wrote (remember) and later archived (memory_archive), // in the shape those two tools leave. const archived: Record<string, unknown>[] = []; for (let k = 0; k < ARCHIVED; k++) { const made = at(SIZE + k); archived.push({ verb: "put", table: "memory", id: memoryId(500 + k), data: { slug: `invented-assistant-note-${k}`, title: `Invented assistant note ${k} about herons nesting`, body: "", status: "archived", machine: null, visibility: "private", origin_kind: "agent", origin_label: "invented-mac hook", source: null, source_external_id: null, superseded_by: null, archived_at: at(SIZE + 100 + k) }, created_at: made, updated_at: at(SIZE + 100 + k) }); } await put(slug, archived); }, 600_000); it("is off by default: memory reads as it always has, and devices read it open", async () => { const r = await lockOf(slug); expect(r.status).toBe(200); expect(r.body).toMatchObject({ lock: null, state: "off", open_entries: SIZE + ARCHIVED, sealed_entries: 0 }); before = { brief: briefing(await tool(slug, hook, "brief", { repoUrl: REPO, machine: "invented-mac" })), project: briefing(await tool(slug, hook, "brief", { projects: ["invented-kiln", "invented-boat"], machine: "invented-mac" })), recall: JSON.stringify(parsed(await tool(slug, hook, "recall", { q: "otters" }))), recallBody: JSON.stringify(parsed(await tool(slug, hook, "recall", { project: "invented-garden", limit: 200 }))), tulips: JSON.stringify(parsed(await tool(slug, hook, "recall", { q: "tulips", limit: 200 }))), }; expect(before.brief).toContain("[otters-hold-hands] Otters hold hands while they sleep"); const served = await http<{ tables: { id: string; seal?: unknown }[] }>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` }); expect(served.body.tables.find((t) => t.id === "memory")!.seal).toBeUndefined(); }, 120_000); it("gate 1 refuses the switch in plain words while the hook's token holds no grant, and files its card", async () => { const gate = await lockOf(slug); const mine = gate.body.readers.find((r) => r.name === "invented-mac hook")!; expect(mine).toMatchObject({ verdict: "needs_allow" }); expect(mine.read_memory_at, "the hook's brief was noted as a memory read").not.toBeNull(); expect(gate.body.ready).toBe(false); const on = await http(slug, "POST", "/v1/admin/memory-lock", { on: true }, ADMIN); expect(on.status).toBe(409); expect(on.body.code).toBe("memory_lock_not_ready"); expect(String(on.body.message ?? on.body.error)).toContain("invented-mac hook (no grant yet: Allow its card on the phone (Account › Assistants))"); expect(String(on.body.message ?? on.body.error)).toContain("Its card is on the owner's phone to Allow"); expect(await count(slug, "SELECT COUNT(*) AS n FROM rows WHERE table_id = 'unlock_request' AND json_extract(data, '$.account') = 1 AND json_extract(data, '$.state') = 'waiting'")).toBe(1); // Nothing changed for memory. expect(briefing(await tool(slug, hook, "brief", { repoUrl: REPO, machine: "invented-mac" }))).toBe(before.brief); }); it("the owner's Allow makes the hook ready; a token never seen reading memory may be excused, one seen reading it may not", async () => { const card = await runInDurableObject(stub(slug), (_i, state) => JSON.parse(state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'unlock_request' AND json_extract(data, '$.state') = 'waiting'").one().data) as Record<string, string>); const requestId = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'unlock_request' AND json_extract(data, '$.state') = 'waiting'").one().id); // The phone hands the tables sealed today (none of the kit's here but the vault's own); memory follows once it is sealed. const g = await agentGrant({ dk, memberId: card.member_id!, memberPub: card.member_pub!, tables: [["note", 1]] }); const allowed = await act(slug, credential, "assistant_allow", { request_id: requestId, ...g }); expect(allowed.status, JSON.stringify(allowed.body)).toBe(200); // The importer has called nothing; it would block the switch unless excused. await tool(slug, importer, "list_records", { table: "note" }); const gate = await lockOf(slug); expect(gate.body.readers.find((r) => r.name === "invented-mac hook")!.verdict).toBe("ready"); expect(gate.body.readers.find((r) => r.name === "invented-mac mail importer")!.verdict).toBe("needs_allow"); const importerId = gate.body.readers.find((r) => r.name === "invented-mac mail importer")!.token_id; const hookId = gate.body.readers.find((r) => r.name === "invented-mac hook")!.token_id; expect((await lockOf(slug, ADMIN, [importerId])).body.ready).toBe(true); // A lane minted from the granted hook token is granted from birth. const lane = await mint(slug, hook, "lane invented", ["read", "lane:invented"], 7, undefined, null); expect(briefing(await tool(slug, lane, "brief", { repoUrl: REPO, machine: "invented-mac" }))).toBe(before.brief); expect((await lockOf(slug, ADMIN, [importerId])).body.readers.find((r) => r.name === "lane invented")!.verdict).toBe("ready"); // Excusing a token seen reading memory does nothing: a stranger's pasted token that briefed once. const stranger = await mint(slug, credential, "invented stranger", ["read"]); await tool(slug, stranger, "brief", { machine: "nowhere" }); const strangerId = (await lockOf(slug)).body.readers.find((r) => r.name === "invented stranger")!.token_id; const gate2 = await lockOf(slug, ADMIN, [importerId, strangerId]); expect(gate2.body.ready).toBe(false); expect(gate2.body.readers.find((r) => r.token_id === strangerId)!.verdict).toBe("needs_allow"); expect(hookId).toBeTruthy(); // It is revoked: the owner never meant to give it memory. expect((await act(slug, credential, "revoke_token", { id: strangerId })).status).toBe(200); }, 120_000); it("on: devices read memory sealed, the object keeps it open and refuses every seal until the phone hands memory's key", async () => { const importerId = (await lockOf(slug)).body.readers.find((r) => r.name === "invented-mac mail importer")!.token_id; const on = await http<{ state: string }>(slug, "POST", "/v1/admin/memory-lock", { on: true, excuse: [importerId] }, ADMIN); expect(on.status, JSON.stringify(on.body)).toBe(200); expect(on.body.state).toBe("handing"); const served = await http<{ tables: { id: string; seal?: { clear: string[] } }[] }>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` }); expect(served.body.tables.find((t) => t.id === "memory")!.seal!.clear).toContain("status"); // Gate 2: the phone's sweep is refused, by name, and nothing is sealed. // Each seal is refused alike; forty stand for the sweep (a full one is the next test's). const swept = await sweep(slug, credential, dk, 40); expect(swept).toEqual({ sealed: 0, refused: { grant_not_handed: 40 } }); // Meanwhile every brief answers as before, and what an assistant remembers stays clear for the sweep. expect(briefing(await tool(slug, hook, "brief", { repoUrl: REPO, machine: "invented-mac" }))).toBe(before.brief); const made = parsed(await tool(slug, hook, "remember", { title: "Invented: herons stand still to fish", project: "invented-garden", decision: { action: "add" } })); expect(made.action).toBe("add"); const kept = await runInDurableObject(stub(slug), (_i, state) => JSON.parse(state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'memory' AND json_extract(data, '$.slug') = ?", String(made.slug)).one().data) as Record<string, unknown>); expect(kept.title).toBe("Invented: herons stand still to fish"); expect(kept.sealed_enc).toBeUndefined(); // Off is still allowed: nothing is sealed yet. expect((await lockOf(slug)).body.state).toBe("handing"); }, 600_000); it("the phone hands memory's key, the sweep seals every entry, and every brief and recall answers the same", async () => { const grant = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string; data: string }>("SELECT id, data FROM rows WHERE table_id = 'unlock_grant' AND json_extract(data, '$.account') = 1").one()); const memberPub = String((JSON.parse(grant.data) as Record<string, unknown>).member_pub ?? ""); const memberId = String((JSON.parse(grant.data) as Record<string, unknown>).member_id); const pub = memberPub || (await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ pub: string }>("SELECT pub FROM agent_member WHERE id = ?", memberId).one().pub)); const add = await wrapWith(crypto.getRandomValues(new Uint8Array(32)), crypto.getRandomValues(new Uint8Array(12)), fromBase64Url(pub), utf8.encode(await bundleOf(dk, memberId, [["memory", 1]]))); expect((await act(slug, credential, "assistant_add", { grant_id: grant.id, tables: ["memory"], wrapped: add })).status).toBe(200); expect((await lockOf(slug)).body.state).toBe("sealing"); // Off is refused from here on. expect((await http(slug, "POST", "/v1/admin/memory-lock", { on: false }, ADMIN)).body.code).toBe("memory_lock_sealing"); // THE MIGRATION: the phone's sweep seals every entry (the herons one the assistant remembered too). const swept = await sweep(slug, credential, dk); expect(swept).toEqual({ sealed: SIZE + 1 + ARCHIVED, refused: {} }); const left = await lockOf(slug); // Every entry sealed: the lock says so (it said "sealing" for good before, open 0 or not: coordinator, 24 Nov 2026). expect(left.body).toMatchObject({ state: "sealed", open_entries: 0, sealed_entries: SIZE + 1 + ARCHIVED }); const check = await http<{ tables: { table: string }[] }>(slug, "GET", "/v1/admin/seal-check", undefined, ADMIN); expect(JSON.stringify(check.body.tables.find((t) => t.table === "memory"))).toBeTruthy(); // Nothing the object keeps says an entry's words in the clear. const all = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify(state.storage.sql.exec("SELECT data FROM rows WHERE table_id = 'memory'").toArray())); for (const w of ["Otters hold hands", "drift apart", "herons stand still", "Invented entry 12 about"]) expect(holdsWord(all, w), w).toBe(false); // The same answers, byte for byte, through the hook's token and a lane minted from it. const lane = await mint(slug, hook, "lane invented after", ["read", "lane:invented-after"], 7, undefined, null); for (const token of [hook, lane]) { const started = Date.now(); const now = briefing(await tool(slug, token, "brief", { repoUrl: REPO, machine: "invented-mac" })); console.log(`memory lock: brief over ${SIZE + 1} sealed entries ${Date.now() - started} ms`); expect(now.replace(/\n.*herons stand still.*$/m, "")).toBe(before.brief); expect(briefing(await tool(slug, token, "brief", { projects: ["invented-kiln", "invented-boat"], machine: "invented-mac" }))).toBe(before.project); // The same entries, in the same order, word for word; each one's updatedAt is the moment the sweep sealed it. expect(sansUpdated(JSON.stringify(parsed(await tool(slug, token, "recall", { q: "otters" }))))).toBe(sansUpdated(before.recall)); const garden = parsed(await tool(slug, token, "recall", { project: "invented-garden", limit: 200 })) as { memories: { title: string }[] }; garden.memories = garden.memories.filter((m) => !m.title.includes("herons stand still")); expect(sansUpdated(JSON.stringify(garden))).toBe(sansUpdated(before.recallBody)); } // recall by a title word finds the same entries in the same order (recall reads titles only, open or sealed). expect(sansUpdated(JSON.stringify(parsed(await tool(slug, hook, "recall", { q: "tulips", limit: 200 }))))).toBe(sansUpdated(before.tulips)); }, 1_200_000); it("a token with no grant is refused cleanly, in plain words, and no entry is said", async () => { const stranger = await mint(slug, credential, "invented unknown machine", ["read"]); const r = parsed(await tool(slug, stranger, "brief", { repoUrl: REPO, machine: "invented-elsewhere" })); // The brief answers a code and words that hold no entry; the hook stops the session on it (cotton-brief.test.ts). expect(r.code).toBe("window_needed"); const said = String(r.briefing); expect(said).toContain("holds none of their entries"); expect(said.toLowerCase()).not.toContain("otter"); console.log(`memory lock: an ungranted token's brief says: ${said}`); expect(said.length).toBeGreaterThan(20); }); it("a kit keep or a definitions write cannot open memory again while the lock is on", async () => { const memory = PERSONAL_TABLES.find((t) => t.id === "memory")!; expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [memory] }, ADMIN)).status).toBe(200); const served = await http<{ tables: { id: string; seal?: unknown }[] }>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` }); expect(served.body.tables.find((t) => t.id === "memory")!.seal).toBeTruthy(); expect(briefing(await tool(slug, hook, "brief", { repoUrl: REPO, machine: "invented-mac" }))).toContain("[otters-hold-hands] Otters hold hands while they sleep"); }); // RULE (coordinator, 24 Nov 2026: the owner's lock stood at 21 open for an hour): an open entry the phone's copy // refuses is never swept; the lock's gate counts such entries by rule, and a granted assistant's memory_update of // the entry's own words seals it, its brief unchanged. it("an entry the phone's copy refuses is counted by rule, and the hook's memory_update of its own words seals it", async () => { const legacy = memoryId(777); const refused = await http<Record<string, unknown>>(slug, "POST", "/v1/admin/import", { rows: [{ verb: "put", table: "memory", id: legacy, data: { slug: "Invented_Legacy", title: "Invented legacy entry about kites", status: "active", visibility: "private", origin_kind: "agent", superseded_by: memoryId(5) } }] }, ADMIN); if (refused.status !== 200) { // The import keeps a sealed table sealed: the legacy row is laid as an older build left it. await runInDurableObject(stub(slug), (_i, state) => { const v = Number(state.storage.sql.exec<{ v: number }>("SELECT max(version) AS v FROM rows").one().v) + 1; const at = new Date().toISOString(); state.storage.sql.exec("INSERT INTO rows (table_id, id, data, version, deleted, created_at, updated_at) VALUES ('memory', ?, ?, ?, 0, ?, ?)", legacy, JSON.stringify({ slug: "Invented_Legacy", title: "Invented legacy entry about kites", status: "active", visibility: "private", origin_kind: "agent", superseded_by: memoryId(5) }), v, at, at); }); } const gate = await lockOf(slug); const why = (gate.body as unknown as { open_why: { breaks_copy: number; breaks_copy_ids: string[]; rules: Record<string, number>; by_assistant: number } }).open_why; expect(gate.body.open_entries).toBe(1); expect(why.breaks_copy).toBe(1); expect(why.breaks_copy_ids).toEqual([legacy]); expect((gate.body as unknown as { open_why: { open_ids: string[] } }).open_why.open_ids).toEqual([legacy]); expect(Object.entries(why.rules).filter(([, n]) => n > 0)).toEqual([["slug", 1], ["superseded_while_active", 1], ["origin_label", 1]]); expect(why.by_assistant).toBe(1); expect(JSON.stringify(gate.body)).not.toContain("kites"); const briefBefore = briefing(await tool(slug, hook, "brief", { repoUrl: REPO, machine: "invented-mac" })); const done = await tool(slug, hook, "memory_update", { id: legacy, title: "Invented legacy entry about kites" }); expect(done.isError, done.content[0]?.text).toBe(false); const after = await lockOf(slug); expect(after.body).toMatchObject({ open_entries: 0, sealed_entries: SIZE + 2 + ARCHIVED }); const all = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify(state.storage.sql.exec("SELECT data FROM rows WHERE table_id = 'memory'").toArray())); expect(all).not.toContain("about kites"); expect(briefing(await tool(slug, hook, "brief", { repoUrl: REPO, machine: "invented-mac" }))).toBe(briefBefore); // An archived assistant's entry left open (the owner's 21): the same act seals it, and it stays archived. const kept = memoryId(778); await runInDurableObject(stub(slug), (_i, state) => { const v = Number(state.storage.sql.exec<{ v: number }>("SELECT max(version) AS v FROM rows").one().v) + 1; const at = new Date().toISOString(); const data = { slug: "invented-archived-open", title: "Invented archived note about gulls", body: "", status: "archived", archived_at: at, machine: null, visibility: "private", origin_kind: "agent", origin_label: "invented-mac hook", source: null, source_external_id: null, superseded_by: null }; state.storage.sql.exec("INSERT INTO rows (table_id, id, data, version, deleted, created_at, updated_at) VALUES ('memory', ?, ?, ?, 0, ?, ?)", kept, JSON.stringify(data), v, at, at); }); expect((await lockOf(slug)).body).toMatchObject({ open_entries: 1 }); const archivedDone = await tool(slug, hook, "memory_update", { id: kept, title: "Invented archived note about gulls" }); expect(archivedDone.isError, archivedDone.content[0]?.text).toBe(false); expect((await lockOf(slug)).body).toMatchObject({ open_entries: 0 }); const held = await runInDurableObject(stub(slug), (_i, state) => JSON.parse(state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'memory' AND id = ?", kept).one().data) as Record<string, unknown>); expect([held.status, typeof held.archived_at, typeof held.sealed_enc]).toEqual(["archived", "string", "string"]); expect(JSON.stringify(held)).not.toContain("gulls"); expect(briefing(await tool(slug, hook, "brief", { repoUrl: REPO, machine: "invented-mac" }))).toBe(briefBefore); }, 300_000);});