Cotton code
188 lines · 10.4 KB · TypeScriptRaw
/** * OPEN TABLES LOCK (owner via the coordinator, 24 Nov 2026: "everything else stays and must be LOCKED the way memory * was"; plan assets/design/shared/OPEN-TABLES.md §2). The memory lock (src/memory_lock.ts), widened to the session * tables and projects: the tables the seal rule leaves open (crates/cotton-core/src/seal/default.json, `pending`) that * every session on every machine reads and writes through Cotton MCP (brief, log_session, list_sessions, get_session). * * One switch per object, off by default, so nothing changes on deploy. Three states, held in the meta * `open_tables_lock`, as memory's: * *   off      nothing here applies. *   handing  the switch is on. The definitions every device reads carry each table's seal block (Store.definitions *            lays them), so each phone hands the tables' keys to every Your Claude grant at its next pass *            (assistants::top_up). The object itself still treats them as open, and a device's seal of one of their *            rows is refused `grant_not_handed` (gate 2), so no row is sealed while a grant could not open it. *   sealing  every live grant that covers them holds every key: the object treats them as sealed, the phones' sweep *            seals each row (the migration), and the session tools read inside the grant, opening only what they *            answer (src/mcp/tools/sealed_rows.ts). Noted once (`sealing_at`) and never left. * * Gate 1: every live token used in IN_USE_DAYS days is a Your Claude member whose grant covers every table; a token * never seen calling a tool that reads them (`open_reader`) may be excused by name. Turning it off is refused once * sealing has begun: no device can open a sealed row back to clear. * * WHAT STAYS READABLE, on purpose: each table's clear columns below (ids, links, times, counts, flags, choices, and * Claude's own session uuid), which the object sorts, filters, joins and erases on with no phone present. */import type { StoredRow } from "./stored_row.ts";export const META = "open_tables_lock";/** The seal block each table carries while the lock is on. Words are sealed; what the object works on stays clear. */export const SEALS: Readonly<Record<string, { clear: string[]; blind: string[]; blind_exact: string[]; blind_bytes?: Record<string, number> }>> = {  project: { clear: ["status", "summary_updated_at", "trashed_at"], blind: ["name"], blind_exact: ["slug"] },  session: {    clear: [      "tool", "external_id", "project", "project_id", "parent_session_id", "todo_id", "started_at", "last_active_at", "ended_at", "active_at", "state",      "state_at", "waiting_kind", "section", "kind", "permission_mode", "chosen_by", "turn_count", "prompt_count", "exit_code", "host_owned", "can_resume",      "device_id", "requested_device_id", "claimed_at", "listened_at", "trashed_at",    ],    blind: ["title"],    blind_exact: ["machine"],  },  session_task: { clear: ["session", "seq", "state"], blind: [], blind_exact: [] },  prompt: { clear: ["session", "session_id", "project", "project_id", "seq", "ts", "role"], blind: ["text"], blind_exact: [], blind_bytes: { text: 2048 } },  session_message: {    clear: [      "project", "project_id", "to_kind", "to_session", "to_session_id", "from_kind", "from_session", "from_session_id", "kind", "reply_to", "thought_id",      "status", "claimed_at", "claimed_by_session_id", "done_at", "created_at", "delivery",    ],    blind: [],    blind_exact: [],  },  // The owner's passwords (OPEN-TABLES.md §3): their names, sites, user names and hints sealed under the secret table's  // key, which only his phones hold (no grant ever carries it, agent.ts NEVER). What stays clear is what the object  // works with no phone: the kind, the service it finds its own Google and Spotify grants by, their sealed tokens  // (`sealed`, which it opens itself to pull), the device-sealed value and history, and the times.  secret: {    clear: ["kind", "service", "sealed", "value_enc", "history_enc", "vmk_version", "expires_at", "last_used_at", "favourite_at", "uses", "changed_at", "trashed_at", "updated_at"],    blind: [],    blind_exact: [],  },};/** The tables the lock seals, in the order a device sweeps them (parents first). */export const TABLES: readonly string[] = Object.keys(SEALS);/** * The passwords' own switch (LOCK TABLES 2, 28 Nov 2026): `secret` sealed alone, ahead of the session tables. No grant * ever carries its key (agent.ts NEVER), so neither gate waits on it: on, every device reads its seal block at once and * its sweep seals each row. Held in the meta `secret_lock` as `{ on_at, by }`. */export const SECRET = "secret";export const SECRET_META = "secret_lock";/** The tables Your Claude's grant carries, so gate 1 and gate 2 wait on them: every one but the passwords. */export const GRANTED: readonly string[] = TABLES.filter((t) => t !== "secret");/** Which tools read these tables: a token seen calling one cannot be excused from gate 1. */export const READING_TOOLS: ReadonlySet<string> = new Set([  "brief", "list_projects", "create_project", "update_project", "link_to_project", "log_session", "list_sessions", "get_session", "open_project_conversation",]);/** Does this call read the locked tables (the session and project tools, or a record tool named at one)? */export function readsTables(tool: string, args: Record<string, unknown>): boolean {  if (READING_TOOLS.has(tool)) return true;  return [args.kind, args.table, args.record_kind].some((v) => typeof v === "string" && TABLES.includes(v));}export const SCHEMA = `CREATE TABLE IF NOT EXISTS open_reader (token_id TEXT PRIMARY KEY, last_at TEXT NOT NULL);`;export interface Lock {  on_at: string;  by: string;  sealing_at?: string;}/** As memory's (src/memory_lock.ts State): sealed once sealing and no row of a locked table is left open. */export type State = "off" | "handing" | "sealing" | "sealed";export function readLock(text: string | null): Lock | null {  if (!text) return null;  try {    const v = JSON.parse(text) as Lock;    return v && typeof v.on_at === "string" ? v : null;  } catch {    return null;  }}/** A table's definition as a device reads it while the lock is on: its seal block laid, whatever the kit says. */export function locked(doc: Record<string, unknown>): Record<string, unknown> {  const seal = SEALS[String(doc.id)];  if (!seal) return doc;  return { ...doc, seal: { clear: [...seal.clear], blind: [...seal.blind], blind_exact: [...seal.blind_exact], ...(seal.blind_bytes ? { blind_bytes: { ...seal.blind_bytes } } : {}) } };}const list = (row: StoredRow | null | undefined, key: string): string[] => {  const v = row?.data[key];  return Array.isArray(v) ? (v as string[]) : [];};/** Does this live grant cover the table: neither withheld by its signed policy nor narrowed to off or ask since? */export function covers(grant: StoredRow | null, table: string, access: "on" | "ask" | "off"): boolean {  if (!grant || access !== "on") return false;  return ![...list(grant, "withheld"), ...list(grant, "off"), ...list(grant, "ask")].includes(table);}/** The live grants that cover a locked table and still wait for its key (gate 2): none means sealing may begin. */export function waiting(grants: readonly StoredRow[], access: (table: string) => "on" | "ask" | "off"): StoredRow[] {  return grants.filter((g) => missing(g, access).length > 0);}/** The locked tables a live grant covers and still lacks the key of: what gate 2 waits on for it. */export function missing(grant: StoredRow, access: (table: string) => "on" | "ask" | "off"): string[] {  return GRANTED.filter((t) => covers(grant, t, access(t)) && !list(grant, "tables").includes(t));}/** One waiting grant as the admin reads it (HANDING STUCK, 25 Nov 2026): which grant, whose, and which keys it lacks. */export interface Waiting {  grant_id: string;  member_id: string | null;  client: string | null;  granted_at: string | null;  /** Tokens of its member neither revoked nor expired: 0 means nothing can read through this grant any more. */  live_tokens: number;  missing: string[];}/** One token as gate 1 reads it. */export interface Reader {  token_id: string;  name: string;  last_used_at: string | null;  /** When it last called a tool that reads these tables, since the object began noting it; null when never seen. */  read_at: string | null;  member: boolean;  /** Its member's grant covers every locked table. */  granted: boolean;  excused: boolean;  verdict: "ready" | "excused" | "needs_allow" | "needs_new_token";  says: string;}/** Gate 1's verdict on one token (its liveness is memory_lock.ts `inUse`, the same 14 days). */export function readerOf(t: { id: string; name: string; last_used_at: string | null; member: string | null }, readAt: string | null, grant: StoredRow | null, access: (table: string) => "on" | "ask" | "off", excuse: ReadonlySet<string>, lockOn = false): Reader {  const member = t.member !== null;  const left = GRANTED.filter((table) => !covers(grant, table, access(table)));  // With the lock on, a grant that covers every table but holds no key of some is not ready yet: gate 2 skips a grant  // nothing reads through (HANDING STUCK, 25 Nov 2026), so a token that comes to such a grant later waits for the phone.  const unhanded = lockOn && grant && left.length === 0 ? missing(grant, access) : [];  const granted = member && !!grant && left.length === 0 && unhanded.length === 0;  const excused = !granted && excuse.has(t.id) && readAt === null;  const verdict: Reader["verdict"] = granted ? "ready" : excused ? "excused" : member ? "needs_allow" : "needs_new_token";  const says =    verdict === "ready"      ? "holds Your Claude's grant with every session table in it"      : verdict === "excused"        ? "excused: never seen reading the session tables"        : verdict === "needs_allow"          ? unhanded.length            ? `its grant waits for the keys of ${unhanded.join(", ")}: the owner's phone hands them on its next pass`            : grant            ? `${left.join(", ")} ${left.length === 1 ? "is" : "are"} left out of Your Claude's grant: turn ${left.length === 1 ? "it" : "them"} on in Account › Assistants on the phone`            : "no grant yet: Allow its card on the phone (Account › Assistants)"          : "carries no member key (made before Your Claude, or minted from a token that had none): replace it with a token minted from a granted one";  return { token_id: t.id, name: t.name, last_used_at: t.last_used_at, read_at: readAt, member, granted, excused, verdict, says };}