/** * 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). */importtype { StoredRow } from"./store.ts";/** The meta the switch is held in: `{ on_at, by, sealing_at? }`, absent when off. */exportconst META = "memory_lock";/** The table. */exportconst MEMORY = "memory";/** How far back a token counts as in use (gate 1). */exportconst 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). */exportconst MEMORY_SEAL = { clear: ["status", "visibility", "origin_kind", "machine", "reviewed_at", "archived_at", "created_at", "superseded_by"], blind: ["title"], blind_exact: ["slug"],} asconst;/** Which tools read memory: a token seen calling one cannot be excused from gate 1. */exportconst MEMORY_TOOLS: ReadonlySet<string> = newSet(["brief", "recall", "remember", "memory_update", "memory_archive"]);/** Does this call read memory (the memory tools, or a record tool named at memory)? */exportfunction readsMemory(tool: string, args: Record<string, unknown>): boolean {if (MEMORY_TOOLS.has(tool)) returntrue;return args.kind === MEMORY || args.table === MEMORY || args.record_kind === MEMORY;}exportconst SCHEMA = `CREATE TABLE IF NOT EXISTS memory_reader (token_id TEXT PRIMARY KEY, last_at TEXT NOT NULL);`;exportinterfaceLock { 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). */exporttypeState = "off" | "handing" | "sealing" | "sealed";exportfunction readLock(text: string | null): Lock | null {if (!text) returnnull;try {const v = JSON.parse(text) asLock;return v && typeof v.on_at === "string" ? v : null; } catch {returnnull; }}/** Memory's definition as a device reads it while the switch is on: the seal block laid, whatever the kit says. */exportfunction 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];returnArray.isArray(v) ? (v as string[]) : [];};/** Does this live grant cover memory: neither withheld by its signed policy nor narrowed to off or ask since? */exportfunction covers(grant: StoredRow | null, access: "on" | "ask" | "off"): boolean {if (!grant || access !== "on") returnfalse;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)? */exportfunction 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. */exportfunction waiting(grants: readonlyStoredRow[], access: "on" | "ask" | "off"): StoredRow[] {return grants.filter((g) => covers(g, access) && !handed(g));}/** One token as gate 1 reads it. */exportinterfaceReader { 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;}exportinterfaceTokenSeen { 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? */exportfunction inUse(t: TokenSeen, nowMs: number): boolean {if (t.revoked_at) returnfalse;if (t.expires_at && Date.parse(t.expires_at) <= nowMs) returnfalse;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. */exportfunction 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. */exportinterfaceOpenWhy {/** 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. */exportconst OPEN_IDS = 200;const TIMES = ["archived_at", "reviewed_at", "created_at"] asconst;/** A time value's form, never the value: `iso` as the object writes one, or what else it is. */exportfunction formOf(v: unknown): string {if (v === undefined) return"absent";if (v === null) return"null";if (typeof v !== "string") returntypeof 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"] asconst;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`). */exportfunction 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");elseif ((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). */exportfunction 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 = newMap<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 ofObject.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;}