Cotton code
268 lines · 13.6 KB · TypeScriptRaw
/** * MEMORY LOCK (coordinator, 23 Nov 2026, owner-approved; plan assets/design/shared/MEMORY-LOCK.md). * * The assistant's memory is the one personal table the rule leaves open (crates/cotton-core/src/seal/default.json, * `pending.memory`): every session on every machine is briefed from it. This switch seals it for ONE object, off by * default, so nothing changes on deploy. Three states, held in the meta `memory_lock`: * *   off      no meta. Memory reads and writes as it always has. *   handing  the switch is on. The definitions every device reads carry memory's seal block (Store.definitions lays *            it), so each phone hands memory's key to every Your Claude grant at its next pass (assistants::top_up). *            The object itself still treats memory as open (`objectSeal`): what an assistant writes stays clear, and *            a device's seal of a memory row is refused `grant_not_handed` (gate 2), so no entry is sealed while any *            granted assistant could not open it. Phones' sweeps leave the row and try again next pass. *   sealing  every live grant that covers memory holds its key: the object treats memory as sealed, the phones' *            sweep seals each entry (the migration), and a memory tool reads inside the grant. Noted once *            (`sealing_at`) and never left: once an entry may be sealed, the object must never read memory as open. * * Gate 1 (`readiness`): the switch turns on only when every live token used in the last 14 days holds a grant that * covers memory; a token never seen calling a memory tool (`memory_reader`) may be excused by name. Turning it off * is refused once sealing has begun: no device can yet unseal a table (risk 5). */import type { StoredRow } from "./store.ts";/** The meta the switch is held in: `{ on_at, by, sealing_at? }`, absent when off. */export const META = "memory_lock";/** The table. */export const MEMORY = "memory";/** How far back a token counts as in use (gate 1). */export const IN_USE_DAYS = 14;/** * Memory's seal block (held since 22 Nov 2026 in test/window.test.ts MEMORY_SEALED). Clear: what the object sorts, * files and archives by, and who wrote it; sealed: the sentence, its slug, its source and the assistant's name. * The title is blind-indexed (recall by words) and the slug exact (recall and memory_update by slug). */export const MEMORY_SEAL = {  clear: ["status", "visibility", "origin_kind", "machine", "reviewed_at", "archived_at", "created_at", "superseded_by"],  blind: ["title"],  blind_exact: ["slug"],} as const;/** Which tools read memory: a token seen calling one cannot be excused from gate 1. */export const MEMORY_TOOLS: ReadonlySet<string> = new Set(["brief", "recall", "remember", "memory_update", "memory_archive"]);/** Does this call read memory (the memory tools, or a record tool named at memory)? */export function readsMemory(tool: string, args: Record<string, unknown>): boolean {  if (MEMORY_TOOLS.has(tool)) return true;  return args.kind === MEMORY || args.table === MEMORY || args.record_kind === MEMORY;}export const SCHEMA = `CREATE TABLE IF NOT EXISTS memory_reader (token_id TEXT PRIMARY KEY, last_at TEXT NOT NULL);`;export interface Lock {  on_at: string;  by: string;  sealing_at?: string;}/** * Off; handing (on, a grant still waits for memory's key); sealing (every grant holds it: the sweep seals what is * open, and off is refused for good); sealed (sealing, and no entry is left open: the lock's work is done). */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;  }}/** Memory's definition as a device reads it while the switch is on: the seal block laid, whatever the kit says. */export function locked(doc: Record<string, unknown>): Record<string, unknown> {  return { ...doc, seal: { clear: [...MEMORY_SEAL.clear], blind: [...MEMORY_SEAL.blind], blind_exact: [...MEMORY_SEAL.blind_exact] } };}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 memory: neither withheld by its signed policy nor narrowed to off or ask since? */export function covers(grant: StoredRow | null, access: "on" | "ask" | "off"): boolean {  if (!grant || access !== "on") return false;  return ![...list(grant, "withheld"), ...list(grant, "off"), ...list(grant, "ask")].includes(MEMORY);}/** Has this grant been handed memory's key (an `assistant_allow` or `assistant_add` naming memory)? */export function handed(grant: StoredRow): boolean {  return list(grant, "tables").includes(MEMORY);}/** The live grants that cover memory and still wait for its key (gate 2): none means sealing may begin. */export function waiting(grants: readonly StoredRow[], access: "on" | "ask" | "off"): StoredRow[] {  return grants.filter((g) => covers(g, access) && !handed(g));}/** 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 memory tool, since the object began noting it; null when never seen. */  read_memory_at: string | null;  /** A Your Claude member: its token carries a member key. */  member: boolean;  /** Its member holds a live standing grant that covers memory. */  granted: boolean;  excused: boolean;  verdict: "ready" | "excused" | "needs_allow" | "needs_new_token";  /** What to do, in words. */  says: string;}export interface TokenSeen {  id: string;  name: string;  last_used_at: string | null;  created_at: string | null;  expires_at: string | null;  revoked_at: string | null;  member: string | null;}/** Is this token live and in use: unrevoked, unexpired, and used (or made) in the last IN_USE_DAYS days? */export function inUse(t: TokenSeen, nowMs: number): boolean {  if (t.revoked_at) return false;  if (t.expires_at && Date.parse(t.expires_at) <= nowMs) return false;  const since = nowMs - IN_USE_DAYS * 86_400_000;  const at = t.last_used_at ?? t.created_at;  return !!at && Date.parse(at) >= since;}/** Gate 1's verdict on one token. */export function readerOf(t: TokenSeen, readAt: string | null, grant: StoredRow | null, access: "on" | "ask" | "off", excuse: ReadonlySet<string>): Reader {  const member = t.member !== null;  const granted = member && covers(grant, access);  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 memory in it"      : verdict === "excused"        ? "excused: never seen reading memory"        : verdict === "needs_allow"          ? access !== "on" || (grant && !covers(grant, access))            ? "memory is left out of Your Claude's grant: turn it 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_memory_at: readAt, member, granted, excused, verdict, says };}/** * WHY AN ENTRY IS STILL OPEN (coordinator, 24 Nov 2026: the owner's lock stood at 21 open, 320 sealed for an hour). A * phone seals an entry from its own copy (crates/cotton-client/src/seal/sweep.rs), and its copy's memory table keeps * the kit's rules (crates/cotton-core/kits/personal/tables/memory.json, `cotton_memories`), which the object never * checks. An open entry that breaks one never lands in the copy: the fold parks it, the sweep finds it "gone from this * copy" on every pass, and it stays open. Counts only: no entry's words, slug or id. */export interface OpenWhy {  /** Open entries the copy's rules refuse: no phone ever seals these. */  breaks_copy: number;  /** Their ids (never their words), for the one act that seals each: a granted assistant's memory_update of its own title. */  breaks_copy_ids: string[];  /** Every open entry's id (never its words), at most OPEN_IDS: what the one safe act is done on, entry by entry. */  open_ids: string[];  /** Each rule, by how many open entries break it (an entry may break more than one). */  rules: Record<string, number>;  /** The rest, for ruling a case out: none of these stops a sweep by itself. */  archived: number;  superseded: number;  by_assistant: number;  made_since_on: number;  changed_since_sealing: number;  /** The open entries' shape, never a value: each key they carry, by how many; each clear time column's form, by how many. */  shape: { keys: Record<string, number>; forms: Record<string, Record<string, number>> };}/** How many open entries' ids the gate says. */export const OPEN_IDS = 200;const TIMES = ["archived_at", "reviewed_at", "created_at"] as const;/** A time value's form, never the value: `iso` as the object writes one, or what else it is. */export function formOf(v: unknown): string {  if (v === undefined) return "absent";  if (v === null) return "null";  if (typeof v !== "string") return typeof v;  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(v)) return "iso";  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})$/.test(v)) return "iso_other_precision_or_zone";  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(v)) return "no_zone";  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}/.test(v)) return "space_separated";  if (/^\d{4}-\d{2}-\d{2}$/.test(v)) return "date_only";  if (/^\d+$/.test(v)) return "digits";  return v === "" ? "empty" : "other";}const RULES = ["slug", "slug_twice", "title", "body", "status", "archived_at_with_status", "superseded_while_active", "machine", "origin_kind", "origin_label", "visibility", "source_external_id_twice"] as const;const str = (v: unknown): string | null => (typeof v === "string" ? v : null);const chars = (s: string): number => Array.from(s).length;/** The copy's rules an open entry's data breaks (the CHECKs and unique indexes of `cotton_memories`). */export function brokenRules(d: Record<string, unknown>, twice: { slug: boolean; external: boolean }): string[] {  const out: string[] = [];  const slug = str(d.slug);  if (slug === null || chars(slug) < 1 || chars(slug) > 64 || !/^[a-z0-9][a-z0-9-]*$/.test(slug)) out.push("slug");  if (twice.slug) out.push("slug_twice");  const title = str(d.title);  if (title === null || !title.trim() || chars(title) > 280) out.push("title");  if (chars(str(d.body) ?? "") > 4000) out.push("body");  // A column the object holds nothing in lands as its declared default (status 'active', visibility 'private').  const status = d.status == null ? "active" : d.status;  if (status !== "active" && status !== "archived") out.push("status");  if ((status === "archived") !== (d.archived_at != null)) out.push("archived_at_with_status");  if (d.superseded_by != null && status !== "archived") out.push("superseded_while_active");  if (d.machine != null && !(typeof d.machine === "string" && d.machine.trim())) out.push("machine");  if (d.origin_kind !== "user" && d.origin_kind !== "agent") out.push("origin_kind");  else if ((d.origin_kind === "agent") !== (d.origin_label != null)) out.push("origin_label");  const visibility = d.visibility == null ? "private" : d.visibility;  if (visibility !== "private" && visibility !== "shared" && visibility !== "public") out.push("visibility");  if (twice.external) out.push("source_external_id_twice");  return out;}/** The open entries, counted by why (`rows`: every live memory row, open or sealed). */export function openWhy(rows: readonly { id: string; data: Record<string, unknown>; created_at: string; updated_at: string }[], lock: Lock | null): OpenWhy {  const open = rows.filter((r) => r.data.sealed_enc == null);  // A sealed entry's slug and source id are inside its seal: a clash with one is not seen here, only among the open.  const tally = (key: string) => {    const n = new Map<string, number>();    for (const r of open) {      const v = str(r.data[key]);      if (v !== null) n.set(v, (n.get(v) ?? 0) + 1);    }    return n;  };  const slugs = tally("slug");  const externals = tally("source_external_id");  const why: OpenWhy = { shape: { keys: {}, forms: Object.fromEntries(TIMES.map((t) => [t, {}])) }, breaks_copy: 0, breaks_copy_ids: [], open_ids: open.slice(0, OPEN_IDS).map((r) => r.id), rules: Object.fromEntries(RULES.map((r) => [r, 0])), archived: 0, superseded: 0, by_assistant: 0, made_since_on: 0, changed_since_sealing: 0 };  for (const r of open) {    const d = r.data;    const broken = brokenRules(d, { slug: (slugs.get(str(d.slug) ?? "") ?? 0) > 1, external: (externals.get(str(d.source_external_id) ?? "") ?? 0) > 1 });    if (broken.length) {      why.breaks_copy++;      why.breaks_copy_ids.push(r.id);    }    for (const rule of broken) why.rules[rule]!++;    for (const k of Object.keys(d)) why.shape.keys[k] = (why.shape.keys[k] ?? 0) + 1;    for (const t of TIMES) {      const f = formOf(d[t]);      why.shape.forms[t]![f] = (why.shape.forms[t]![f] ?? 0) + 1;    }    if (d.status === "archived") why.archived++;    if (d.superseded_by != null) why.superseded++;    if (d.origin_kind === "agent") why.by_assistant++;    if (lock && r.created_at >= lock.on_at) why.made_since_on++;    if (lock?.sealing_at && r.updated_at >= lock.sealing_at) why.changed_since_sealing++;  }  return why;}