/** * The personal kit as the repository ships it, and a personal object made * the way the coordinator makes the real one: onboarded with the kit, the * owner signed in by phone and the fixed code, an owner token minted by an act. * Every MCP test starts here and speaks only through the front door. */ import { isGoneTable, isGoneTool, served } from "../src/retired.ts"; import { env, runInDurableObject, SELF } from "cloudflare:test"; import { expect } from "vitest"; import personal from "../../../crates/cotton-core/kits/personal/kit.json"; import { ruled } from "../src/seal.ts"; import { arrivalPub } from "./arrival_keys.ts"; const tables = import.meta.glob("../../../crates/cotton-core/kits/personal/tables/*.json", { eager: true, import: "default" }) as Record>; const kit = import.meta.glob("../../../crates/cotton-core/kits/personal/tools/*/manifest.json", { eager: true, import: "default" }) as Record>; const boards = import.meta.glob("../../../crates/cotton-core/kits/shell/boards/*.json", { eager: true, import: "default" }) as Record>; /** The kit's own tool: its kit.json, the object's map of its tables, in a tool file's keys. */ export const PERSONAL_TOOLS: Record[] = [ { format_version: personal.format_version, id: personal.id, name: personal.name, tables: personal.tables, instructions: personal.instructions }, ]; /** The tables the kit lists (its kit.json): what the object serves, in file order. A file the kit holds but lists not (Photos' media, which the phone's core keeps) is defined there and never served. */ /** The personal kit's tables as a personal object serves them: through the seal rule (src/seal.ts `ruled`, e2e rulings R1). */ // Never a table held as retired (src/retired.ts; TABLE DROP 1): the kit may list one until its definition leaves the tree. export const PERSONAL_TABLES = Object.values(tables).filter((t) => personal.tables.includes(String(t.id)) && !isGoneTable(String(t.id))).map(ruled); /** The kit's tool manifests, in its kit.json's order (the fan's). */ // As the object serves them: retired tools left out, and a kept tool naming a retired table served without it (TABLE DROP 1). export const KIT_MANIFESTS = served({ tables: [], tools: personal.tools.filter((id) => !isGoneTool(id)).map((id) => kit[`../../../crates/cotton-core/kits/personal/tools/${id}/manifest.json`]!) }).tools; /** The shell's boards, by file name. */ export const KIT_BOARD_FILES = Object.entries(boards).sort(([a], [b]) => a.localeCompare(b)).map(([, board]) => board); export const ADMIN = { authorization: "Bearer test-admin-token" }; export const OWNER_PHONE = "+919000000009"; export const DATABASE_ID = "11111111-1111-4111-8111-111111111111"; export async function http>(slug: string, method: string, path: string, body?: unknown, headers: Record = {}): Promise<{ status: number; body: T }> { const res = await SELF.fetch(`https://example.test/b/${slug}${path}`, { method, headers: { "content-type": "application/json", ...headers }, body: body === undefined ? undefined : JSON.stringify(body), }); const text = await res.text(); return { status: res.status, body: (text ? JSON.parse(text) : null) as T }; } /** A fresh personal object at `slug`; answers the owner's phone credential and an owner MCP token. */ /** The todo tables: tests of the record tools' mechanics (paging, search, where) read them as a table any token reads. */ export const TODOS_OPEN = ["todo", "todo_recurrence"]; /** The money tables as an open fixture (since the sealing work sealed transaction and evidence): tests of the object's own money run, which works only while money is open. */ export const MONEY_OPEN = { open: ["transaction", "evidence", "money_account", "statement", "statement_line"] }; /** The calendar's events as an open fixture (since the sealing work sealed event): tests of the pull's paging and the object's calendar engine over open rows. */ export const EVENTS_OPEN = { open: ["event", "event_attendee"] }; /** Notes as an open fixture (since the sealing work sealed note): tests that use a note as any open record, and the brief over open procedure notes. */ export const NOTES_OPEN = { open: ["note"] }; /** Memory as an open table, for the tests of the memory tools' own rules (sealed since LAUNCH.md, 22 Nov 2026; window.test.ts tests them sealed). */ export const MEMORY_OPEN = { open: ["memory"] }; /** Lists as an open fixture (since the sealing work sealed record_group and group_member): tests of a list's own mechanics over Cotton MCP. */ export const GROUPS_OPEN = { open: ["record_group", "group_member"] }; /** Books as an open fixture (since the sealing work sealed book): tests of the object's own book engines over open rows. */ export const BOOKS_OPEN = { open: ["book"] }; /** Films as an open fixture (since the sealing work sealed film, film_season and film_episode). */ export const FILMS_OPEN = { open: ["film", "film_season", "film_episode"] }; /** People as an open fixture (since the sealing work sealed person, person_handle and person_suggestion): tests of the object's people over open rows. */ export const PEOPLE_OPEN = { open: ["person", "person_handle", "person_suggestion"] }; /** The tables the old message and call import routes write, open: those routes are refused once any is sealed (ROUTES-AUDIT 11). */ export const CLEAR_IMPORT_OPEN = { open: [...PEOPLE_OPEN.open, "thread", "thread_member", "message", "message_contact", "message_contact_handle", "message_reaction", "call"] }; /** Photos as an open fixture (since the sealing work sealed photo, video, face and sighting). */ export const PHOTOS_OPEN = { open: ["photo", "video", "face", "sighting"] }; /** * Defines `open` unsealed on the object at `slug` (`seal: null`, which the * rule leaves as it is), once the kit has been laid (it lays the kit's seal * over a stored block): a fixture for the tests that use todos as an open * table, now that the rule seals them (e2e rulings R1). */ export async function openTables(slug: string, open: string[]): Promise { await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, state) => { for (const id of open) state.storage.sql.exec("UPDATE definitions SET json = json_set(json, '$.seal', json('null')) WHERE id = ?", `table:${id}`); }); } /** * This object answers sealed reads with timed windows alone, as every object * did before Your Claude's standing grant (on Worker-wide since 21 Nov 2026): * for a test of the windows' own rules. The object's `agent_grant` meta * "off" (src/business.ts agentGrantOn); no route sets it. */ export async function windowsOnly(slug: string): Promise { await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance) => (instance as unknown as { store: { setMeta(k: string, v: string): void } }).store.setMeta("agent_grant", "off")); } export async function personalObject(slug: string, o: { open?: string[]; arrival?: boolean; windows?: boolean } = {}): Promise<{ credential: string; owner: string }> { const meta = await http(slug, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: OWNER_PHONE, database_id: DATABASE_ID, timezone: "Asia/Kolkata" }, ADMIN); expect(meta.status, JSON.stringify(meta.body)).toBe(200); if (o.windows) await windowsOnly(slug); 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); // Tables opened as a fixture are open before sign-in, so what sign-in makes (the owner's person) is made as it was while they were open. if (o.open) { await http(slug, "GET", "/v1/definitions"); await openTables(slug, o.open); } const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: "coordinator" }); const signed = await http<{ credential: string; person: { role: string } }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "coordinator" }); expect(signed.body.person.role).toBe("owner"); const owner = await mint(slug, signed.body.credential, "coordinator owner", ["owner"]); if (o.open) await openTables(slug, o.open); if (o.arrival) { // As a phone holding the data key does once (e2e rulings R2): what the object seals what it fetches to. const handed = await http(slug, "POST", "/v1/act", { act: "create", args: { table: "seal_key", id: "arrival", data: { pub: await arrivalPub() } } }, { authorization: `Bearer ${signed.body.credential}` }); expect(handed.status, JSON.stringify(handed.body)).toBe(200); } return { credential: signed.body.credential, owner }; } /** * A key minted by the owner's device. `allow` is what it may do (src/key_allow.ts): "all" by default here, a key as * every key was before allows, so a test of something else holds a key as it did; a test of allows names its own, or * null for the mint's own default (the narrowest useful set). */ export async function mint(slug: string, credential: string, name: string, scopes: string[], expiresInDays?: number, machine?: string, allow: unknown = "all"): Promise { const minted = await http<{ token?: string }>(slug, "POST", "/v1/act", { act: "mint_token", args: { name, scopes, ...(expiresInDays ? { expires_in_days: expiresInDays } : {}), ...(machine ? { machine } : {}), ...(allow === null ? {} : { allow }) } }, { authorization: `Bearer ${credential}` }); expect(minted.status, JSON.stringify(minted.body)).toBe(200); expect(minted.body.token).toMatch(new RegExp(`^ctn_${DATABASE_ID}_`)); return minted.body.token!; } export interface ToolResult { isError: boolean; content: { type: string; text: string }[]; structuredContent?: Record; } /** One bare tools/call, as the hooks send it: no initialize, no session, id 1. */ export async function tool(slug: string, token: string, name: string, args: Record = {}): Promise { const res = await http<{ result?: ToolResult; error?: unknown }>(slug, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }, { authorization: `Bearer ${token}` }); expect(res.status, JSON.stringify(res.body)).toBe(200); expect(res.body.result, JSON.stringify(res.body)).toBeDefined(); return res.body.result!; } /** A tool's answer, parsed; fails the test on a refusal. */ export async function answer>(slug: string, token: string, name: string, args: Record = {}): Promise { const r = await tool(slug, token, name, args); expect(r.isError, r.content[0]?.text).toBe(false); return JSON.parse(r.content[0]!.text) as T; } /** A tool's refusal sentence; fails the test when it answered. */ export async function refusal(slug: string, token: string, name: string, args: Record = {}): Promise { const r = await tool(slug, token, name, args); expect(r.isError, r.content[0]?.text).toBe(true); return r.content[0]!.text; } /** Rows straight into the object through the admin import, for a test's starting state. */ export async function put(slug: string, rows: Record[]): Promise> { const res = await http<{ ids: Record }>(slug, "POST", "/v1/admin/import", { rows }, ADMIN); expect(res.status, JSON.stringify(res.body)).toBe(200); return res.body.ids; } /** The owner's phone publishes its person key (the kit's person_key table, id = fingerprint), as cotton-ffi's person key publish does; the sealed half is a stand-in no test opens. */ export async function publishPersonKey(slug: string, credential: string, publicKey: string): Promise { const res = await http(slug, "POST", "/v1/act", { act: "create", args: { table: "person_key", id: publicKey.slice(0, 8), data: { public_key: publicKey, sealed_private_enc: "v2:stand-in", vmk_version: 1 } } }, { authorization: `Bearer ${credential}` }); expect(res.status, JSON.stringify(res.body)).toBe(200); } /** What a write's answer says of its changes (src/changes.ts): the first change's id to undo it by, and how many when more than one. */ export function changed(count = 1): Record { return { change_id: expect.any(Number), undoable: true, ...(count > 1 ? { changes: count } : {}) }; } /** What a machine's write answers of its changes (src/changes.ts MACHINE_WRITERS: log_session, empty_bin …): logged, not undoable. */ export function loggedOnly(count = 1): Record { return { ...changed(count), undoable: false }; } /** The keys a write's answer adds for its changes, after its own. */ export function changeKeys(count = 1): string[] { return ["change_id", "undoable", ...(count > 1 ? ["changes"] : [])]; } /** * A served board as it is stored: a personal object serves Home's `tools` * part naming the tools that hold no rows (`empty`, src/fan.ts), which no * stored board holds. */ export function asStored(board: unknown): unknown { const b = board as { parts?: Record[] }; if (!Array.isArray(b.parts)) return board; return { ...b, parts: b.parts.map(({ empty: _empty, ...part }) => part) }; }