Cotton code
274 lines · 12.3 KB · TypeScriptRaw
/** * The wire between a business's object and its phones, scripts and tests. * * Pure types and the few helpers both sides need; no Workers types here so the * onboarding script and, later, the phone's generated client can import it. * * THE SHAPE (review session + coordinator, 24 Oct 2026): the object is a row * store with role filtering and the authoritative acts. Every business row is * `{ table, id, data }` with a change `version`; a phone pulls what its role * may see since a cursor (`GET /v1/sync?since=`, paged by `next`) and posts writes as acts * (`POST /v1/act`), and the object answers each act with the rows it changed. * Computed columns (lookups, rollups, formulas) are the phone renderer's, read * off its own cache of these rows; the object recomputes only what it must * decide on — capacity, pack coverage, money taken. *//** A table's visibility, as the package JSON spells it. */export type Visibility =  | { kind: "public" }  | { kind: "staff" }  | { kind: "owner" }  /** `customer` on a table: a row belongs to the person it names in `person`. */  | { kind: "customer" }  /** `mine(<column>)`: a row belongs to whoever owns the row its `<column>` links to (or to the person it names). */  | { kind: "mine"; through: string };export type Role = "public" | "member" | "staff" | "owner";/** Role order for "at least": public < member < staff < owner. */export const ROLE_RANK: Record<Role, number> = { public: 0, member: 1, staff: 2, owner: 3 };export function atLeast(role: Role, floor: Role): boolean {  return ROLE_RANK[role] >= ROLE_RANK[floor];}/** One business row on the wire. `owner` is the person id a mine() row belongs to; absent on public rows. */export interface WireRow {  table: string;  id: string;  data: Record<string, unknown>;  owner?: string | null;  version: number;  deleted?: boolean;  created_at: string;  updated_at: string;  /** A mail's only: when it landed on the server, by the server's clock (MAIL PREDICATE phase 2, rule 3). */  landed_at?: string;}/** * `GET /v1/held?tables=<table>,…[&limit=<n>]`, then `GET /v1/held?cursor=<next>` * until an answer carries no `next` (owner only): which ids the object holds * of those tables, ids only. `live` are rows it holds live; `binned` are ids * it holds as deleted (tombstones: a row deleted, or erased from a bin), * which a top-up must never send back. A table the object holds nothing of * is absent. An object older than this route answers 404 `not_found`. */export interface HeldAnswer {  held: Record<string, { live: string[]; binned: string[] }>;  next?: string;}/** * `GET /v1/blind?table=<sealed table>&tok=<token>,…[&limit=<n>][&rows=1]` (the * owner's devices only): the ids of the table's live rows holding every token, * newest first by its clear date column. A token is the decimal text of a * signed 64-bit number (sealing plan §4). With `rows=1` the hits come as the * object stores them (sealed, as a sync page carries them) for the phone to * open; the object reads no word either way. */export interface BlindAnswer {  table: string;  ids: string[];  rows?: WireRow[];}export interface SyncAnswer {  /** The change counter the phone holds once it has applied this page: pass it back as `since` next time. While `next` is present it is still the `since` asked with. */  version: number;  /** On the last page, once the database's file is at DATABASE_WARN_FRACTION of its cap or past it: its bytes, the cap, and the fraction used, so the phone can say so before writes are refused (owner, 22 Nov 2026). */  room?: { bytes: number; cap: number; used: number };  /** On the last page, once the space rules hold for the account and its photos and files use 80% of its allowance or more (SPACE.md): the bytes held, the allowance and the fraction used. */  space?: { bytes: number; allowance: number; used: number };  rows: WireRow[];  /** More rows follow: ask `GET /v1/sync?cursor=<next>` before syncing anew. */  next?: string;  /** The account's own switches, on every page (`mail_all`: Comms keeps all mail, `POST /v1/admin/mail-all`). */  features?: string[];  /** Staff and owner also see the people (members, staff) of the business, on the last page. */  people?: WirePerson[];  /** The object's clock when it answered (ISO): the phone's writes are stamped by the time it judges from this. */  server_time: string;  /** RESTORE 2 (assets/design/shared/RESTORE-2-CONTRACT.md): the history this copy is built from, on every page. A copy of another one is made again. */  generation: string;  /** RESTORE 2: when the generation came from a restore, the moment the account was put back to (ISO). */  restored_to?: string;  /** The live rows the phone holds once this pass has landed: every row its scope and windows keep at the pass's version. */  total: number;  /** The rows this pass still carries after this page (tombstones too); 0 on the last page. */  remaining: number;  /** Of `total`, the live rows the phone holds once this page has landed: the device row's `sync_rows_done`. */  done: number;  /**   * Each table this pass carries rows of: `rows` its pages carry (tombstones   * too) and `done` how many of them have come once this page has landed —   * equal on the pass's last page. The deck's counter says from these how   * far a tool's rows have come ("347 of 950 todos arriving").   */  tables: Record<string, { rows: number; done: number }>;  /** The tables this later pass carries again whole, first, as `again=` asked: said so a phone knows the object carried them. */  again?: string[];  /**   * Whole tables erased for good since the pass's `since` (src/erase.ts), each   * with the moment it went: said on a pass's first page only. The phone   * retracts every row it holds of each, stamped at that moment, before it   * folds the page's rows; a row written after it stands.   */  dropped?: Record<string, string>;  /**   * The signed-in device's own `device` row, which the object writes this   * pass's progress on (`src/sync_status.ts`): the live row of the device   * its credential was granted to, made on the first page that names the   * device (`device_name`, `platform`, `app_version` in the query) when the   * database holds none; null only for a page that names none. Absent for a   * caller that is no signed-in device.   */  device?: string | null;}export interface WirePerson {  id: string;  phone: string;  name: string | null;  role: Exclude<Role, "public">;  created_at: string;}export interface DefinitionsAnswer {  business: BusinessMeta;  /** The package tool.json documents, verbatim. */  tools: Record<string, unknown>[];  /** The package tables/*.json documents, verbatim. */  tables: Record<string, unknown>[];  /** What the flavour manifest says about this business's public views and pages. */  flavour: Record<string, unknown>;  /** The boards (Home, the tools grid…) a database keeps as data; none for a business. */  boards: Record<string, unknown>[];  /** The themes a database keeps as data, merged by id as boards are. */  themes: Record<string, unknown>[];  /** A hash of everything above; the phone refetches when it changes. */  etag: string;}export interface BusinessMeta {  slug: string;  name: string;  currency: string;  /** IANA zone the business lives in: "today" is read in it. */  timezone: string;  /** The business's own UPI id; the phone opens upi://pay with it. */  upi_id?: string | null;  /** The owner's phone: the first sign-in with it is the owner. */  owner_phone?: string | null;  /** `personal` for the owner's personal database (it serves Cotton MCP), else `business`. */  kind?: "business" | "personal";  /** The database's uuid (the personal one keeps its Rust workspace id). */  database_id?: string | null;  /** The personal database's owner as a person in People (src/owner.ts): every phone's copy takes who "you" are from here. */  owner_person_id?: string | null;  /** What the personal database's derived ids (contacts, threads, calls) are made under: its own id, unless it was made under an older file's. The Mac importer's engines make theirs under it (sealing plan L8). */  namespace?: string | null;}export interface CodeRequest {  phone: string;  device_id: string;}export interface CodeAnswer {  challenge_id: string;  expires_in: number;}export interface SignInRequest {  challenge_id: string;  code: string;  device_id: string;  /** The name a new member gives themselves; ignored for a known person. */  name?: string;}export interface SignInAnswer {  credential: string;  person: WirePerson;  version: number;}/** * The acts the object decides. Each is a POST /v1/act { act, args } with a * credential (the admin token acts as the owner with no person). * * - `book` / `order` { slot, quantity?, member? }: the slot table's reserve act; a member books for themselves. * - `cancel` { id }: a claim goes; a member only their own and never a past day. * - `record_act` { table, id, act, picked? }: an act the package defines on a row (here, take_cash, renew…); members only reserve and cancel. * - `message` { text, about?, person? }: a member to the business, or staff to a person. * - `profile` { name }: the signed-in person names themselves. * - `create` / `update` / `delete` { table, id?, data?, blind? }: staff and owner write rows directly; on a sealed table a device sends sealed columns only inside `sealed_enc` (with `dek_enc` and `seal_v`), and `blind` its tokens. * - `seal` { table, id, expect_version, data, blind? }: the owner's device seals a row, only while it is at `expect_version` (src/seal.ts). * - `set_role` { phone, role, name? }: the owner makes staff. */export type ActName = "book" | "order" | "cancel" | "record_act" | "message" | "profile" | "create" | "update" | "delete" | "seal" | "seal_many" | "seal_stage" | "seal_commit" | "seal_purge" | "set_role";export interface ActRequest {  act: ActName;  args: Record<string, unknown>;}export interface ActAnswer {  version: number;  changed: WireRow[];  /** What the act made, when it made one row: its table and id. */  made?: { table: string; id: string };}export interface Refusal {  code: string;  message: string;}/** `+91 98765 43210` → `+919876543210`; anything without a leading + or with letters is refused. */export function normalizePhone(raw: string): string | null {  const trimmed = raw.trim();  if (!trimmed.startsWith("+")) return null;  const digits = trimmed.slice(1).replace(/[\s\-().]/g, "");  if (!/^[1-9]\d{6,14}$/.test(digits)) return null;  return `+${digits}`;}/** The ISO date (YYYY-MM-DD) `at` falls on in `timezone`. */export function localDate(at: Date, timezone: string): string {  const parts = new Intl.DateTimeFormat("en-CA", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(at);  const get = (type: string) => parts.find((p) => p.type === type)?.value ?? "";  return `${get("year")}-${get("month")}-${get("day")}`;}/** `d` plus `days` calendar days, both ISO dates. */export function addDays(d: string, days: number): string {  const [y, m, day] = d.split("-").map(Number) as [number, number, number];  const t = Date.UTC(y, m - 1, day + days);  return new Date(t).toISOString().slice(0, 10);}/** * Retired tables: the kit still ships them, so the rows an object holds stay, * read and sync as before, and no new row is written, by the direct `create` * act or by Cotton MCP's create_record. The importer still carries the rows a * person already had. session_message: the session inbox (owner, 15 Nov * 2026). The seven screenplay tables: Cotton Story took their place * (coordinator, 17 Nov 2026); no row is deleted, which is the owner's word, * until the owner erases them (POST /v1/admin/erase, src/erase.ts). * The AI account tables were here until TABLE DROP 1 held them retired whole * (src/retired.ts GONE_TABLES: never served, so never written). */export const RETIRED_TABLES: ReadonlySet<string> = new Set([  "session_message",  "screenplay",  "screenplay_scene",  "screenplay_character",  "screenplay_place",  "screenplay_draft",  "screenplay_draft_scene",  "screenplay_document",]);/** Why a retired table takes no new row, said the same at every door. */export const retiredRefusal = (table: string): string => `${table} is retired: the rows it holds are kept, and no new one is written`;